VirtualBox

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

Last change on this file since 65933 was 65933, checked in by vboxsync, 8 years ago

VMM: Nested Hw.virt: Implemented vmsave, vmload, invlpga in IEM.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 217.8 KB
Line 
1/* $Id: HMSVMR0.cpp 65933 2017-03-03 13:21:40Z vboxsync $ */
2/** @file
3 * HM SVM (AMD-V) - Host Context Ring-0.
4 */
5
6/*
7 * Copyright (C) 2013-2016 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#ifdef DEBUG_ramshankar
39# define HMSVM_SYNC_FULL_GUEST_STATE
40# define HMSVM_ALWAYS_TRAP_ALL_XCPTS
41# define HMSVM_ALWAYS_TRAP_PF
42# define HMSVM_ALWAYS_TRAP_TASK_SWITCH
43#endif
44
45
46/*********************************************************************************************************************************
47* Defined Constants And Macros *
48*********************************************************************************************************************************/
49#ifdef VBOX_WITH_STATISTICS
50# define HMSVM_EXITCODE_STAM_COUNTER_INC(u64ExitCode) do { \
51 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitAll); \
52 if ((u64ExitCode) == SVM_EXIT_NPF) \
53 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitReasonNpf); \
54 else \
55 STAM_COUNTER_INC(&pVCpu->hm.s.paStatExitReasonR0[(u64ExitCode) & MASK_EXITREASON_STAT]); \
56 } while (0)
57#else
58# define HMSVM_EXITCODE_STAM_COUNTER_INC(u64ExitCode) do { } while (0)
59#endif
60
61/** If we decide to use a function table approach this can be useful to
62 * switch to a "static DECLCALLBACK(int)". */
63#define HMSVM_EXIT_DECL static int
64
65/** Macro for checking and returning from the using function for
66 * \#VMEXIT intercepts that maybe caused during delivering of another
67 * event in the guest. */
68#define HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY() \
69 do \
70 { \
71 int rc = hmR0SvmCheckExitDueToEventDelivery(pVCpu, pCtx, pSvmTransient); \
72 if (RT_LIKELY(rc == VINF_SUCCESS)) { /* likely */ } \
73 else if (rc == VINF_HM_DOUBLE_FAULT) \
74 return VINF_SUCCESS; \
75 else \
76 return rc; \
77 } while (0)
78
79/** Macro for upgrading a @a a_rc to VINF_EM_DBG_STEPPED after emulating an
80 * instruction that exited. */
81#define HMSVM_CHECK_SINGLE_STEP(a_pVCpu, a_rc) \
82 do { \
83 if ((a_pVCpu)->hm.s.fSingleInstruction && (a_rc) == VINF_SUCCESS) \
84 (a_rc) = VINF_EM_DBG_STEPPED; \
85 } while (0)
86
87/** Assert that preemption is disabled or covered by thread-context hooks. */
88#define HMSVM_ASSERT_PREEMPT_SAFE() Assert( VMMR0ThreadCtxHookIsEnabled(pVCpu) \
89 || !RTThreadPreemptIsEnabled(NIL_RTTHREAD));
90
91/** Assert that we haven't migrated CPUs when thread-context hooks are not
92 * used. */
93#define HMSVM_ASSERT_CPU_SAFE() AssertMsg( VMMR0ThreadCtxHookIsEnabled(pVCpu) \
94 || pVCpu->hm.s.idEnteredCpu == RTMpCpuId(), \
95 ("Illegal migration! Entered on CPU %u Current %u\n", \
96 pVCpu->hm.s.idEnteredCpu, RTMpCpuId()));
97
98/** Exception bitmap mask for all contributory exceptions.
99 *
100 * Page fault is deliberately excluded here as it's conditional as to whether
101 * it's contributory or benign. Page faults are handled separately.
102 */
103#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) \
104 | RT_BIT(X86_XCPT_DE))
105
106/** @name VMCB Clean Bits.
107 *
108 * These flags are used for VMCB-state caching. A set VMCB Clean bit indicates
109 * AMD-V doesn't need to reload the corresponding value(s) from the VMCB in
110 * memory.
111 *
112 * @{ */
113/** All intercepts vectors, TSC offset, PAUSE filter counter. */
114#define HMSVM_VMCB_CLEAN_INTERCEPTS RT_BIT(0)
115/** I/O permission bitmap, MSR permission bitmap. */
116#define HMSVM_VMCB_CLEAN_IOPM_MSRPM RT_BIT(1)
117/** ASID. */
118#define HMSVM_VMCB_CLEAN_ASID RT_BIT(2)
119/** TRP: V_TPR, V_IRQ, V_INTR_PRIO, V_IGN_TPR, V_INTR_MASKING,
120V_INTR_VECTOR. */
121#define HMSVM_VMCB_CLEAN_TPR RT_BIT(3)
122/** Nested Paging: Nested CR3 (nCR3), PAT. */
123#define HMSVM_VMCB_CLEAN_NP RT_BIT(4)
124/** Control registers (CR0, CR3, CR4, EFER). */
125#define HMSVM_VMCB_CLEAN_CRX_EFER RT_BIT(5)
126/** Debug registers (DR6, DR7). */
127#define HMSVM_VMCB_CLEAN_DRX RT_BIT(6)
128/** GDT, IDT limit and base. */
129#define HMSVM_VMCB_CLEAN_DT RT_BIT(7)
130/** Segment register: CS, SS, DS, ES limit and base. */
131#define HMSVM_VMCB_CLEAN_SEG RT_BIT(8)
132/** CR2.*/
133#define HMSVM_VMCB_CLEAN_CR2 RT_BIT(9)
134/** Last-branch record (DbgCtlMsr, br_from, br_to, lastint_from, lastint_to) */
135#define HMSVM_VMCB_CLEAN_LBR RT_BIT(10)
136/** AVIC (AVIC APIC_BAR; AVIC APIC_BACKING_PAGE, AVIC
137PHYSICAL_TABLE and AVIC LOGICAL_TABLE Pointers). */
138#define HMSVM_VMCB_CLEAN_AVIC RT_BIT(11)
139/** Mask of all valid VMCB Clean bits. */
140#define HMSVM_VMCB_CLEAN_ALL ( HMSVM_VMCB_CLEAN_INTERCEPTS \
141 | HMSVM_VMCB_CLEAN_IOPM_MSRPM \
142 | HMSVM_VMCB_CLEAN_ASID \
143 | HMSVM_VMCB_CLEAN_TPR \
144 | HMSVM_VMCB_CLEAN_NP \
145 | HMSVM_VMCB_CLEAN_CRX_EFER \
146 | HMSVM_VMCB_CLEAN_DRX \
147 | HMSVM_VMCB_CLEAN_DT \
148 | HMSVM_VMCB_CLEAN_SEG \
149 | HMSVM_VMCB_CLEAN_CR2 \
150 | HMSVM_VMCB_CLEAN_LBR \
151 | HMSVM_VMCB_CLEAN_AVIC)
152/** @} */
153
154/** @name SVM transient.
155 *
156 * A state structure for holding miscellaneous information across AMD-V
157 * VMRUN/\#VMEXIT operation, restored after the transition.
158 *
159 * @{ */
160typedef struct SVMTRANSIENT
161{
162 /** The host's rflags/eflags. */
163 RTCCUINTREG fEFlags;
164#if HC_ARCH_BITS == 32
165 uint32_t u32Alignment0;
166#endif
167
168 /** The \#VMEXIT exit code (the EXITCODE field in the VMCB). */
169 uint64_t u64ExitCode;
170 /** The guest's TPR value used for TPR shadowing. */
171 uint8_t u8GuestTpr;
172 /** Alignment. */
173 uint8_t abAlignment0[7];
174
175 /** Whether the guest FPU state was active at the time of \#VMEXIT. */
176 bool fWasGuestFPUStateActive;
177 /** Whether the guest debug state was active at the time of \#VMEXIT. */
178 bool fWasGuestDebugStateActive;
179 /** Whether the hyper debug state was active at the time of \#VMEXIT. */
180 bool fWasHyperDebugStateActive;
181 /** Whether the TSC offset mode needs to be updated. */
182 bool fUpdateTscOffsetting;
183 /** Whether the TSC_AUX MSR needs restoring on \#VMEXIT. */
184 bool fRestoreTscAuxMsr;
185 /** Whether the \#VMEXIT was caused by a page-fault during delivery of a
186 * contributary exception or a page-fault. */
187 bool fVectoringDoublePF;
188 /** Whether the \#VMEXIT was caused by a page-fault during delivery of an
189 * external interrupt or NMI. */
190 bool fVectoringPF;
191} SVMTRANSIENT, *PSVMTRANSIENT;
192AssertCompileMemberAlignment(SVMTRANSIENT, u64ExitCode, sizeof(uint64_t));
193AssertCompileMemberAlignment(SVMTRANSIENT, fWasGuestFPUStateActive, sizeof(uint64_t));
194/** @} */
195
196/**
197 * MSRPM (MSR permission bitmap) read permissions (for guest RDMSR).
198 */
199typedef enum SVMMSREXITREAD
200{
201 /** Reading this MSR causes a \#VMEXIT. */
202 SVMMSREXIT_INTERCEPT_READ = 0xb,
203 /** Reading this MSR does not cause a \#VMEXIT. */
204 SVMMSREXIT_PASSTHRU_READ
205} SVMMSREXITREAD;
206
207/**
208 * MSRPM (MSR permission bitmap) write permissions (for guest WRMSR).
209 */
210typedef enum SVMMSREXITWRITE
211{
212 /** Writing to this MSR causes a \#VMEXIT. */
213 SVMMSREXIT_INTERCEPT_WRITE = 0xd,
214 /** Writing to this MSR does not cause a \#VMEXIT. */
215 SVMMSREXIT_PASSTHRU_WRITE
216} SVMMSREXITWRITE;
217
218/**
219 * SVM \#VMEXIT handler.
220 *
221 * @returns VBox status code.
222 * @param pVCpu The cross context virtual CPU structure.
223 * @param pMixedCtx Pointer to the guest-CPU context.
224 * @param pSvmTransient Pointer to the SVM-transient structure.
225 */
226typedef int FNSVMEXITHANDLER(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient);
227
228
229/*********************************************************************************************************************************
230* Internal Functions *
231*********************************************************************************************************************************/
232static void hmR0SvmSetMsrPermission(PVMCPU pVCpu, unsigned uMsr, SVMMSREXITREAD enmRead, SVMMSREXITWRITE enmWrite);
233static void hmR0SvmPendingEventToTrpmTrap(PVMCPU pVCpu);
234static void hmR0SvmLeave(PVMCPU pVCpu);
235
236/** @name \#VMEXIT handlers.
237 * @{
238 */
239static FNSVMEXITHANDLER hmR0SvmExitIntr;
240static FNSVMEXITHANDLER hmR0SvmExitWbinvd;
241static FNSVMEXITHANDLER hmR0SvmExitInvd;
242static FNSVMEXITHANDLER hmR0SvmExitCpuid;
243static FNSVMEXITHANDLER hmR0SvmExitRdtsc;
244static FNSVMEXITHANDLER hmR0SvmExitRdtscp;
245static FNSVMEXITHANDLER hmR0SvmExitRdpmc;
246static FNSVMEXITHANDLER hmR0SvmExitInvlpg;
247static FNSVMEXITHANDLER hmR0SvmExitHlt;
248static FNSVMEXITHANDLER hmR0SvmExitMonitor;
249static FNSVMEXITHANDLER hmR0SvmExitMwait;
250static FNSVMEXITHANDLER hmR0SvmExitShutdown;
251static FNSVMEXITHANDLER hmR0SvmExitReadCRx;
252static FNSVMEXITHANDLER hmR0SvmExitWriteCRx;
253static FNSVMEXITHANDLER hmR0SvmExitSetPendingXcptUD;
254static FNSVMEXITHANDLER hmR0SvmExitMsr;
255static FNSVMEXITHANDLER hmR0SvmExitReadDRx;
256static FNSVMEXITHANDLER hmR0SvmExitWriteDRx;
257static FNSVMEXITHANDLER hmR0SvmExitXsetbv;
258static FNSVMEXITHANDLER hmR0SvmExitIOInstr;
259static FNSVMEXITHANDLER hmR0SvmExitNestedPF;
260static FNSVMEXITHANDLER hmR0SvmExitVIntr;
261static FNSVMEXITHANDLER hmR0SvmExitTaskSwitch;
262static FNSVMEXITHANDLER hmR0SvmExitVmmCall;
263static FNSVMEXITHANDLER hmR0SvmExitPause;
264static FNSVMEXITHANDLER hmR0SvmExitIret;
265static FNSVMEXITHANDLER hmR0SvmExitXcptPF;
266static FNSVMEXITHANDLER hmR0SvmExitXcptNM;
267static FNSVMEXITHANDLER hmR0SvmExitXcptUD;
268static FNSVMEXITHANDLER hmR0SvmExitXcptMF;
269static FNSVMEXITHANDLER hmR0SvmExitXcptDB;
270static FNSVMEXITHANDLER hmR0SvmExitXcptAC;
271static FNSVMEXITHANDLER hmR0SvmExitXcptBP;
272#ifdef VBOX_WITH_NESTED_HWVIRT
273static FNSVMEXITHANDLER hmR0SvmExitClgi;
274static FNSVMEXITHANDLER hmR0SvmExitStgi;
275static FNSVMEXITHANDLER hmR0SvmExitVmload;
276static FNSVMEXITHANDLER hmR0SvmExitVmsave;
277#endif
278/** @} */
279
280DECLINLINE(int) hmR0SvmHandleExit(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PSVMTRANSIENT pSvmTransient);
281
282
283/*********************************************************************************************************************************
284* Global Variables *
285*********************************************************************************************************************************/
286/** Ring-0 memory object for the IO bitmap. */
287RTR0MEMOBJ g_hMemObjIOBitmap = NIL_RTR0MEMOBJ;
288/** Physical address of the IO bitmap. */
289RTHCPHYS g_HCPhysIOBitmap = 0;
290/** Virtual address of the IO bitmap. */
291R0PTRTYPE(void *) g_pvIOBitmap = NULL;
292
293
294/**
295 * Sets up and activates AMD-V on the current CPU.
296 *
297 * @returns VBox status code.
298 * @param pCpu Pointer to the CPU info struct.
299 * @param pVM The cross context VM structure. Can be
300 * NULL after a resume!
301 * @param pvCpuPage Pointer to the global CPU page.
302 * @param HCPhysCpuPage Physical address of the global CPU page.
303 * @param fEnabledByHost Whether the host OS has already initialized AMD-V.
304 * @param pvArg Unused on AMD-V.
305 */
306VMMR0DECL(int) SVMR0EnableCpu(PHMGLOBALCPUINFO pCpu, PVM pVM, void *pvCpuPage, RTHCPHYS HCPhysCpuPage, bool fEnabledByHost,
307 void *pvArg)
308{
309 Assert(!fEnabledByHost);
310 Assert(HCPhysCpuPage && HCPhysCpuPage != NIL_RTHCPHYS);
311 Assert(RT_ALIGN_T(HCPhysCpuPage, _4K, RTHCPHYS) == HCPhysCpuPage);
312 Assert(pvCpuPage); NOREF(pvCpuPage);
313 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
314
315 NOREF(pvArg);
316 NOREF(fEnabledByHost);
317
318 /* Paranoid: Disable interrupt as, in theory, interrupt handlers might mess with EFER. */
319 RTCCUINTREG fEFlags = ASMIntDisableFlags();
320
321 /*
322 * We must turn on AMD-V and setup the host state physical address, as those MSRs are per CPU.
323 */
324 uint64_t u64HostEfer = ASMRdMsr(MSR_K6_EFER);
325 if (u64HostEfer & MSR_K6_EFER_SVME)
326 {
327 /* If the VBOX_HWVIRTEX_IGNORE_SVM_IN_USE is active, then we blindly use AMD-V. */
328 if ( pVM
329 && pVM->hm.s.svm.fIgnoreInUseError)
330 {
331 pCpu->fIgnoreAMDVInUseError = true;
332 }
333
334 if (!pCpu->fIgnoreAMDVInUseError)
335 {
336 ASMSetFlags(fEFlags);
337 return VERR_SVM_IN_USE;
338 }
339 }
340
341 /* Turn on AMD-V in the EFER MSR. */
342 ASMWrMsr(MSR_K6_EFER, u64HostEfer | MSR_K6_EFER_SVME);
343
344 /* Write the physical page address where the CPU will store the host state while executing the VM. */
345 ASMWrMsr(MSR_K8_VM_HSAVE_PA, HCPhysCpuPage);
346
347 /* Restore interrupts. */
348 ASMSetFlags(fEFlags);
349
350 /*
351 * Theoretically, other hypervisors may have used ASIDs, ideally we should flush all non-zero ASIDs
352 * when enabling SVM. AMD doesn't have an SVM instruction to flush all ASIDs (flushing is done
353 * upon VMRUN). Therefore, just set the fFlushAsidBeforeUse flag which instructs hmR0SvmSetupTLB()
354 * to flush the TLB with before using a new ASID.
355 */
356 pCpu->fFlushAsidBeforeUse = true;
357
358 /*
359 * Ensure each VCPU scheduled on this CPU gets a new VPID on resume. See @bugref{6255}.
360 */
361 ++pCpu->cTlbFlushes;
362
363 return VINF_SUCCESS;
364}
365
366
367/**
368 * Deactivates AMD-V on the current CPU.
369 *
370 * @returns VBox status code.
371 * @param pCpu Pointer to the CPU info struct.
372 * @param pvCpuPage Pointer to the global CPU page.
373 * @param HCPhysCpuPage Physical address of the global CPU page.
374 */
375VMMR0DECL(int) SVMR0DisableCpu(PHMGLOBALCPUINFO pCpu, void *pvCpuPage, RTHCPHYS HCPhysCpuPage)
376{
377 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
378 AssertReturn( HCPhysCpuPage
379 && HCPhysCpuPage != NIL_RTHCPHYS, VERR_INVALID_PARAMETER);
380 AssertReturn(pvCpuPage, VERR_INVALID_PARAMETER);
381 NOREF(pCpu);
382
383 /* Paranoid: Disable interrupts as, in theory, interrupt handlers might mess with EFER. */
384 RTCCUINTREG fEFlags = ASMIntDisableFlags();
385
386 /* Turn off AMD-V in the EFER MSR. */
387 uint64_t u64HostEfer = ASMRdMsr(MSR_K6_EFER);
388 ASMWrMsr(MSR_K6_EFER, u64HostEfer & ~MSR_K6_EFER_SVME);
389
390 /* Invalidate host state physical address. */
391 ASMWrMsr(MSR_K8_VM_HSAVE_PA, 0);
392
393 /* Restore interrupts. */
394 ASMSetFlags(fEFlags);
395
396 return VINF_SUCCESS;
397}
398
399
400/**
401 * Does global AMD-V initialization (called during module initialization).
402 *
403 * @returns VBox status code.
404 */
405VMMR0DECL(int) SVMR0GlobalInit(void)
406{
407 /*
408 * Allocate 12 KB for the IO bitmap. Since this is non-optional and we always intercept all IO accesses, it's done
409 * once globally here instead of per-VM.
410 */
411 Assert(g_hMemObjIOBitmap == NIL_RTR0MEMOBJ);
412 int rc = RTR0MemObjAllocCont(&g_hMemObjIOBitmap, 3 << PAGE_SHIFT, false /* fExecutable */);
413 if (RT_FAILURE(rc))
414 return rc;
415
416 g_pvIOBitmap = RTR0MemObjAddress(g_hMemObjIOBitmap);
417 g_HCPhysIOBitmap = RTR0MemObjGetPagePhysAddr(g_hMemObjIOBitmap, 0 /* iPage */);
418
419 /* Set all bits to intercept all IO accesses. */
420 ASMMemFill32(g_pvIOBitmap, 3 << PAGE_SHIFT, UINT32_C(0xffffffff));
421 return VINF_SUCCESS;
422}
423
424
425/**
426 * Does global AMD-V termination (called during module termination).
427 */
428VMMR0DECL(void) SVMR0GlobalTerm(void)
429{
430 if (g_hMemObjIOBitmap != NIL_RTR0MEMOBJ)
431 {
432 RTR0MemObjFree(g_hMemObjIOBitmap, true /* fFreeMappings */);
433 g_pvIOBitmap = NULL;
434 g_HCPhysIOBitmap = 0;
435 g_hMemObjIOBitmap = NIL_RTR0MEMOBJ;
436 }
437}
438
439
440/**
441 * Frees any allocated per-VCPU structures for a VM.
442 *
443 * @param pVM The cross context VM structure.
444 */
445DECLINLINE(void) hmR0SvmFreeStructs(PVM pVM)
446{
447 for (uint32_t i = 0; i < pVM->cCpus; i++)
448 {
449 PVMCPU pVCpu = &pVM->aCpus[i];
450 AssertPtr(pVCpu);
451
452 if (pVCpu->hm.s.svm.hMemObjVmcbHost != NIL_RTR0MEMOBJ)
453 {
454 RTR0MemObjFree(pVCpu->hm.s.svm.hMemObjVmcbHost, false);
455 pVCpu->hm.s.svm.pvVmcbHost = 0;
456 pVCpu->hm.s.svm.HCPhysVmcbHost = 0;
457 pVCpu->hm.s.svm.hMemObjVmcbHost = NIL_RTR0MEMOBJ;
458 }
459
460 if (pVCpu->hm.s.svm.hMemObjVmcb != NIL_RTR0MEMOBJ)
461 {
462 RTR0MemObjFree(pVCpu->hm.s.svm.hMemObjVmcb, false);
463 pVCpu->hm.s.svm.pvVmcb = 0;
464 pVCpu->hm.s.svm.HCPhysVmcb = 0;
465 pVCpu->hm.s.svm.hMemObjVmcb = NIL_RTR0MEMOBJ;
466 }
467
468 if (pVCpu->hm.s.svm.hMemObjMsrBitmap != NIL_RTR0MEMOBJ)
469 {
470 RTR0MemObjFree(pVCpu->hm.s.svm.hMemObjMsrBitmap, false);
471 pVCpu->hm.s.svm.pvMsrBitmap = 0;
472 pVCpu->hm.s.svm.HCPhysMsrBitmap = 0;
473 pVCpu->hm.s.svm.hMemObjMsrBitmap = NIL_RTR0MEMOBJ;
474 }
475 }
476}
477
478
479/**
480 * Does per-VM AMD-V initialization.
481 *
482 * @returns VBox status code.
483 * @param pVM The cross context VM structure.
484 */
485VMMR0DECL(int) SVMR0InitVM(PVM pVM)
486{
487 int rc = VERR_INTERNAL_ERROR_5;
488
489 /*
490 * Check for an AMD CPU erratum which requires us to flush the TLB before every world-switch.
491 */
492 uint32_t u32Family;
493 uint32_t u32Model;
494 uint32_t u32Stepping;
495 if (HMAmdIsSubjectToErratum170(&u32Family, &u32Model, &u32Stepping))
496 {
497 Log4(("SVMR0InitVM: AMD cpu with erratum 170 family %#x model %#x stepping %#x\n", u32Family, u32Model, u32Stepping));
498 pVM->hm.s.svm.fAlwaysFlushTLB = true;
499 }
500
501 /*
502 * Initialize the R0 memory objects up-front so we can properly cleanup on allocation failures.
503 */
504 for (VMCPUID i = 0; i < pVM->cCpus; i++)
505 {
506 PVMCPU pVCpu = &pVM->aCpus[i];
507 pVCpu->hm.s.svm.hMemObjVmcbHost = NIL_RTR0MEMOBJ;
508 pVCpu->hm.s.svm.hMemObjVmcb = NIL_RTR0MEMOBJ;
509 pVCpu->hm.s.svm.hMemObjMsrBitmap = NIL_RTR0MEMOBJ;
510 }
511
512 for (VMCPUID i = 0; i < pVM->cCpus; i++)
513 {
514 PVMCPU pVCpu = &pVM->aCpus[i];
515
516 /*
517 * Allocate one page for the host-context VM control block (VMCB). This is used for additional host-state (such as
518 * FS, GS, Kernel GS Base, etc.) apart from the host-state save area specified in MSR_K8_VM_HSAVE_PA.
519 */
520 rc = RTR0MemObjAllocCont(&pVCpu->hm.s.svm.hMemObjVmcbHost, 1 << PAGE_SHIFT, false /* fExecutable */);
521 if (RT_FAILURE(rc))
522 goto failure_cleanup;
523
524 pVCpu->hm.s.svm.pvVmcbHost = RTR0MemObjAddress(pVCpu->hm.s.svm.hMemObjVmcbHost);
525 pVCpu->hm.s.svm.HCPhysVmcbHost = RTR0MemObjGetPagePhysAddr(pVCpu->hm.s.svm.hMemObjVmcbHost, 0 /* iPage */);
526 Assert(pVCpu->hm.s.svm.HCPhysVmcbHost < _4G);
527 ASMMemZeroPage(pVCpu->hm.s.svm.pvVmcbHost);
528
529 /*
530 * Allocate one page for the guest-state VMCB.
531 */
532 rc = RTR0MemObjAllocCont(&pVCpu->hm.s.svm.hMemObjVmcb, 1 << PAGE_SHIFT, false /* fExecutable */);
533 if (RT_FAILURE(rc))
534 goto failure_cleanup;
535
536 pVCpu->hm.s.svm.pvVmcb = RTR0MemObjAddress(pVCpu->hm.s.svm.hMemObjVmcb);
537 pVCpu->hm.s.svm.HCPhysVmcb = RTR0MemObjGetPagePhysAddr(pVCpu->hm.s.svm.hMemObjVmcb, 0 /* iPage */);
538 Assert(pVCpu->hm.s.svm.HCPhysVmcb < _4G);
539 ASMMemZeroPage(pVCpu->hm.s.svm.pvVmcb);
540
541 /*
542 * Allocate two pages (8 KB) for the MSR permission bitmap. There doesn't seem to be a way to convince
543 * SVM to not require one.
544 */
545 rc = RTR0MemObjAllocCont(&pVCpu->hm.s.svm.hMemObjMsrBitmap, 2 << PAGE_SHIFT, false /* fExecutable */);
546 if (RT_FAILURE(rc))
547 goto failure_cleanup;
548
549 pVCpu->hm.s.svm.pvMsrBitmap = RTR0MemObjAddress(pVCpu->hm.s.svm.hMemObjMsrBitmap);
550 pVCpu->hm.s.svm.HCPhysMsrBitmap = RTR0MemObjGetPagePhysAddr(pVCpu->hm.s.svm.hMemObjMsrBitmap, 0 /* iPage */);
551 /* Set all bits to intercept all MSR accesses (changed later on). */
552 ASMMemFill32(pVCpu->hm.s.svm.pvMsrBitmap, 2 << PAGE_SHIFT, UINT32_C(0xffffffff));
553 }
554
555 return VINF_SUCCESS;
556
557failure_cleanup:
558 hmR0SvmFreeStructs(pVM);
559 return rc;
560}
561
562
563/**
564 * Does per-VM AMD-V termination.
565 *
566 * @returns VBox status code.
567 * @param pVM The cross context VM structure.
568 */
569VMMR0DECL(int) SVMR0TermVM(PVM pVM)
570{
571 hmR0SvmFreeStructs(pVM);
572 return VINF_SUCCESS;
573}
574
575
576/**
577 * Sets the permission bits for the specified MSR in the MSRPM.
578 *
579 * @param pVCpu The cross context virtual CPU structure.
580 * @param uMsr The MSR for which the access permissions are being set.
581 * @param enmRead MSR read permissions.
582 * @param enmWrite MSR write permissions.
583 */
584static void hmR0SvmSetMsrPermission(PVMCPU pVCpu, unsigned uMsr, SVMMSREXITREAD enmRead, SVMMSREXITWRITE enmWrite)
585{
586 unsigned uBit;
587 uint8_t *pbMsrBitmap = (uint8_t *)pVCpu->hm.s.svm.pvMsrBitmap;
588
589 /*
590 * Layout:
591 * Byte offset MSR range
592 * 0x000 - 0x7ff 0x00000000 - 0x00001fff
593 * 0x800 - 0xfff 0xc0000000 - 0xc0001fff
594 * 0x1000 - 0x17ff 0xc0010000 - 0xc0011fff
595 * 0x1800 - 0x1fff Reserved
596 */
597 if (uMsr <= 0x00001FFF)
598 {
599 /* Pentium-compatible MSRs. */
600 uBit = uMsr * 2;
601 }
602 else if ( uMsr >= 0xC0000000
603 && uMsr <= 0xC0001FFF)
604 {
605 /* AMD Sixth Generation x86 Processor MSRs. */
606 uBit = (uMsr - 0xC0000000) * 2;
607 pbMsrBitmap += 0x800;
608 }
609 else if ( uMsr >= 0xC0010000
610 && uMsr <= 0xC0011FFF)
611 {
612 /* AMD Seventh and Eighth Generation Processor MSRs. */
613 uBit = (uMsr - 0xC0001000) * 2;
614 pbMsrBitmap += 0x1000;
615 }
616 else
617 {
618 AssertFailed();
619 return;
620 }
621
622 Assert(uBit < 0x3fff /* 16 * 1024 - 1 */);
623 if (enmRead == SVMMSREXIT_INTERCEPT_READ)
624 ASMBitSet(pbMsrBitmap, uBit);
625 else
626 ASMBitClear(pbMsrBitmap, uBit);
627
628 if (enmWrite == SVMMSREXIT_INTERCEPT_WRITE)
629 ASMBitSet(pbMsrBitmap, uBit + 1);
630 else
631 ASMBitClear(pbMsrBitmap, uBit + 1);
632
633 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
634 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_IOPM_MSRPM;
635}
636
637
638/**
639 * Sets up AMD-V for the specified VM.
640 * This function is only called once per-VM during initalization.
641 *
642 * @returns VBox status code.
643 * @param pVM The cross context VM structure.
644 */
645VMMR0DECL(int) SVMR0SetupVM(PVM pVM)
646{
647 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
648 AssertReturn(pVM, VERR_INVALID_PARAMETER);
649 Assert(pVM->hm.s.svm.fSupported);
650
651 bool const fPauseFilter = RT_BOOL(pVM->hm.s.svm.u32Features & AMD_CPUID_SVM_FEATURE_EDX_PAUSE_FILTER);
652 bool const fPauseFilterThreshold = RT_BOOL(pVM->hm.s.svm.u32Features & AMD_CPUID_SVM_FEATURE_EDX_PAUSE_FILTER_THRESHOLD);
653 bool const fUsePauseFilter = fPauseFilter && pVM->hm.s.svm.cPauseFilter && pVM->hm.s.svm.cPauseFilterThresholdTicks;
654
655 for (VMCPUID i = 0; i < pVM->cCpus; i++)
656 {
657 PVMCPU pVCpu = &pVM->aCpus[i];
658 PSVMVMCB pVmcb = (PSVMVMCB)pVM->aCpus[i].hm.s.svm.pvVmcb;
659
660 AssertMsgReturn(pVmcb, ("Invalid pVmcb for vcpu[%u]\n", i), VERR_SVM_INVALID_PVMCB);
661
662 /* Initialize the #VMEXIT history array with end-of-array markers (UINT16_MAX). */
663 Assert(!pVCpu->hm.s.idxExitHistoryFree);
664 HMCPU_EXIT_HISTORY_RESET(pVCpu);
665
666 /* Always trap #AC for reasons of security. */
667 pVmcb->ctrl.u32InterceptException |= RT_BIT_32(X86_XCPT_AC);
668
669 /* Always trap #DB for reasons of security. */
670 pVmcb->ctrl.u32InterceptException |= RT_BIT_32(X86_XCPT_DB);
671
672 /* Trap exceptions unconditionally (debug purposes). */
673#ifdef HMSVM_ALWAYS_TRAP_PF
674 pVmcb->ctrl.u32InterceptException |= RT_BIT(X86_XCPT_PF);
675#endif
676#ifdef HMSVM_ALWAYS_TRAP_ALL_XCPTS
677 /* If you add any exceptions here, make sure to update hmR0SvmHandleExit(). */
678 pVmcb->ctrl.u32InterceptException |= 0
679 | RT_BIT(X86_XCPT_BP)
680 | RT_BIT(X86_XCPT_DE)
681 | RT_BIT(X86_XCPT_NM)
682 | RT_BIT(X86_XCPT_UD)
683 | RT_BIT(X86_XCPT_NP)
684 | RT_BIT(X86_XCPT_SS)
685 | RT_BIT(X86_XCPT_GP)
686 | RT_BIT(X86_XCPT_PF)
687 | RT_BIT(X86_XCPT_MF)
688 ;
689#endif
690
691 /* Set up unconditional intercepts and conditions. */
692 pVmcb->ctrl.u64InterceptCtrl = SVM_CTRL_INTERCEPT_INTR /* External interrupt causes a #VMEXIT. */
693 | SVM_CTRL_INTERCEPT_NMI /* Non-maskable interrupts causes a #VMEXIT. */
694 | SVM_CTRL_INTERCEPT_INIT /* INIT signal causes a #VMEXIT. */
695 | SVM_CTRL_INTERCEPT_RDPMC /* RDPMC causes a #VMEXIT. */
696 | SVM_CTRL_INTERCEPT_CPUID /* CPUID causes a #VMEXIT. */
697 | SVM_CTRL_INTERCEPT_RSM /* RSM causes a #VMEXIT. */
698 | SVM_CTRL_INTERCEPT_HLT /* HLT causes a #VMEXIT. */
699 | SVM_CTRL_INTERCEPT_INOUT_BITMAP /* Use the IOPM to cause IOIO #VMEXITs. */
700 | SVM_CTRL_INTERCEPT_MSR_SHADOW /* MSR access not covered by MSRPM causes a #VMEXIT.*/
701 | SVM_CTRL_INTERCEPT_INVLPGA /* INVLPGA causes a #VMEXIT. */
702 | SVM_CTRL_INTERCEPT_SHUTDOWN /* Shutdown events causes a #VMEXIT. */
703 | SVM_CTRL_INTERCEPT_FERR_FREEZE /* Intercept "freezing" during legacy FPU handling. */
704 | SVM_CTRL_INTERCEPT_VMRUN /* VMRUN causes a #VMEXIT. */
705 | SVM_CTRL_INTERCEPT_VMMCALL /* VMMCALL causes a #VMEXIT. */
706 | SVM_CTRL_INTERCEPT_VMLOAD /* VMLOAD causes a #VMEXIT. */
707 | SVM_CTRL_INTERCEPT_VMSAVE /* VMSAVE causes a #VMEXIT. */
708 | SVM_CTRL_INTERCEPT_STGI /* STGI causes a #VMEXIT. */
709 | SVM_CTRL_INTERCEPT_CLGI /* CLGI causes a #VMEXIT. */
710 | SVM_CTRL_INTERCEPT_SKINIT /* SKINIT causes a #VMEXIT. */
711 | SVM_CTRL_INTERCEPT_WBINVD /* WBINVD causes a #VMEXIT. */
712 | SVM_CTRL_INTERCEPT_MONITOR /* MONITOR causes a #VMEXIT. */
713 | SVM_CTRL_INTERCEPT_MWAIT /* MWAIT causes a #VMEXIT. */
714 | SVM_CTRL_INTERCEPT_XSETBV; /* XSETBV causes a #VMEXIT. */
715
716 /* CR0, CR4 reads must be intercepted, our shadow values are not necessarily the same as the guest's. */
717 pVmcb->ctrl.u16InterceptRdCRx = RT_BIT(0) | RT_BIT(4);
718
719 /* CR0, CR4 writes must be intercepted for the same reasons as above. */
720 pVmcb->ctrl.u16InterceptWrCRx = RT_BIT(0) | RT_BIT(4);
721
722 /* Intercept all DRx reads and writes by default. Changed later on. */
723 pVmcb->ctrl.u16InterceptRdDRx = 0xffff;
724 pVmcb->ctrl.u16InterceptWrDRx = 0xffff;
725
726 /* Virtualize masking of INTR interrupts. (reads/writes from/to CR8 go to the V_TPR register) */
727 pVmcb->ctrl.IntCtrl.n.u1VIrqMasking = 1;
728
729 /* Ignore the priority in the TPR. This is necessary for delivering PIC style (ExtInt) interrupts and we currently
730 deliver both PIC and APIC interrupts alike. See hmR0SvmInjectPendingEvent() */
731 pVmcb->ctrl.IntCtrl.n.u1IgnoreTPR = 1;
732
733 /* Set IO and MSR bitmap permission bitmap physical addresses. */
734 pVmcb->ctrl.u64IOPMPhysAddr = g_HCPhysIOBitmap;
735 pVmcb->ctrl.u64MSRPMPhysAddr = pVCpu->hm.s.svm.HCPhysMsrBitmap;
736
737 /* No LBR virtualization. */
738 pVmcb->ctrl.u64LBRVirt = 0;
739
740 /* Initially set all VMCB clean bits to 0 indicating that everything should be loaded from the VMCB in memory. */
741 pVmcb->ctrl.u64VmcbCleanBits = 0;
742
743 /* The host ASID MBZ, for the guest start with 1. */
744 pVmcb->ctrl.TLBCtrl.n.u32ASID = 1;
745
746 /*
747 * Setup the PAT MSR (applicable for Nested Paging only).
748 * The default value should be 0x0007040600070406ULL, but we want to treat all guest memory as WB,
749 * so choose type 6 for all PAT slots.
750 */
751 pVmcb->guest.u64GPAT = UINT64_C(0x0006060606060606);
752
753 /* Setup Nested Paging. This doesn't change throughout the execution time of the VM. */
754 pVmcb->ctrl.NestedPaging.n.u1NestedPaging = pVM->hm.s.fNestedPaging;
755
756 /* Without Nested Paging, we need additionally intercepts. */
757 if (!pVM->hm.s.fNestedPaging)
758 {
759 /* CR3 reads/writes must be intercepted; our shadow values differ from the guest values. */
760 pVmcb->ctrl.u16InterceptRdCRx |= RT_BIT(3);
761 pVmcb->ctrl.u16InterceptWrCRx |= RT_BIT(3);
762
763 /* Intercept INVLPG and task switches (may change CR3, EFLAGS, LDT). */
764 pVmcb->ctrl.u64InterceptCtrl |= SVM_CTRL_INTERCEPT_INVLPG
765 | SVM_CTRL_INTERCEPT_TASK_SWITCH;
766
767 /* Page faults must be intercepted to implement shadow paging. */
768 pVmcb->ctrl.u32InterceptException |= RT_BIT(X86_XCPT_PF);
769 }
770
771#ifdef HMSVM_ALWAYS_TRAP_TASK_SWITCH
772 pVmcb->ctrl.u64InterceptCtrl |= SVM_CTRL_INTERCEPT_TASK_SWITCH;
773#endif
774
775 /* Apply the exceptions intercepts needed by the GIM provider. */
776 if (pVCpu->hm.s.fGIMTrapXcptUD)
777 pVmcb->ctrl.u32InterceptException |= RT_BIT(X86_XCPT_UD);
778
779 /* Setup Pause Filter for guest pause-loop (spinlock) exiting. */
780 if (fUsePauseFilter)
781 {
782 pVmcb->ctrl.u16PauseFilterCount = pVM->hm.s.svm.cPauseFilter;
783 if (fPauseFilterThreshold)
784 pVmcb->ctrl.u16PauseFilterThreshold = pVM->hm.s.svm.cPauseFilterThresholdTicks;
785 }
786
787 /*
788 * The following MSRs are saved/restored automatically during the world-switch.
789 * Don't intercept guest read/write accesses to these MSRs.
790 */
791 hmR0SvmSetMsrPermission(pVCpu, MSR_K8_LSTAR, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
792 hmR0SvmSetMsrPermission(pVCpu, MSR_K8_CSTAR, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
793 hmR0SvmSetMsrPermission(pVCpu, MSR_K6_STAR, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
794 hmR0SvmSetMsrPermission(pVCpu, MSR_K8_SF_MASK, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
795 hmR0SvmSetMsrPermission(pVCpu, MSR_K8_FS_BASE, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
796 hmR0SvmSetMsrPermission(pVCpu, MSR_K8_GS_BASE, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
797 hmR0SvmSetMsrPermission(pVCpu, MSR_K8_KERNEL_GS_BASE, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
798 hmR0SvmSetMsrPermission(pVCpu, MSR_IA32_SYSENTER_CS, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
799 hmR0SvmSetMsrPermission(pVCpu, MSR_IA32_SYSENTER_ESP, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
800 hmR0SvmSetMsrPermission(pVCpu, MSR_IA32_SYSENTER_EIP, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
801 }
802
803 return VINF_SUCCESS;
804}
805
806
807/**
808 * Invalidates a guest page by guest virtual address.
809 *
810 * @returns VBox status code.
811 * @param pVM The cross context VM structure.
812 * @param pVCpu The cross context virtual CPU structure.
813 * @param GCVirt Guest virtual address of the page to invalidate.
814 */
815VMMR0DECL(int) SVMR0InvalidatePage(PVM pVM, PVMCPU pVCpu, RTGCPTR GCVirt)
816{
817 AssertReturn(pVM, VERR_INVALID_PARAMETER);
818 Assert(pVM->hm.s.svm.fSupported);
819
820 bool fFlushPending = pVM->hm.s.svm.fAlwaysFlushTLB || VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_TLB_FLUSH);
821
822 /* Skip it if a TLB flush is already pending. */
823 if (!fFlushPending)
824 {
825 Log4(("SVMR0InvalidatePage %RGv\n", GCVirt));
826
827 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
828 AssertMsgReturn(pVmcb, ("Invalid pVmcb!\n"), VERR_SVM_INVALID_PVMCB);
829
830#if HC_ARCH_BITS == 32
831 /* If we get a flush in 64-bit guest mode, then force a full TLB flush. INVLPGA takes only 32-bit addresses. */
832 if (CPUMIsGuestInLongMode(pVCpu))
833 VMCPU_FF_SET(pVCpu, VMCPU_FF_TLB_FLUSH);
834 else
835#endif
836 {
837 SVMR0InvlpgA(GCVirt, pVmcb->ctrl.TLBCtrl.n.u32ASID);
838 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlbInvlpgVirt);
839 }
840 }
841 return VINF_SUCCESS;
842}
843
844
845/**
846 * Flushes the appropriate tagged-TLB entries.
847 *
848 * @param pVCpu The cross context virtual CPU structure.
849 */
850static void hmR0SvmFlushTaggedTlb(PVMCPU pVCpu)
851{
852 PVM pVM = pVCpu->CTX_SUFF(pVM);
853 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
854 PHMGLOBALCPUINFO pCpu = hmR0GetCurrentCpu();
855
856 /*
857 * Force a TLB flush for the first world switch if the current CPU differs from the one we ran on last.
858 * This can happen both for start & resume due to long jumps back to ring-3.
859 * If the TLB flush count changed, another VM (VCPU rather) has hit the ASID limit while flushing the TLB,
860 * so we cannot reuse the ASIDs without flushing.
861 */
862 bool fNewAsid = false;
863 Assert(pCpu->idCpu != NIL_RTCPUID);
864 if ( pVCpu->hm.s.idLastCpu != pCpu->idCpu
865 || pVCpu->hm.s.cTlbFlushes != pCpu->cTlbFlushes)
866 {
867 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlbWorldSwitch);
868 pVCpu->hm.s.fForceTLBFlush = true;
869 fNewAsid = true;
870 }
871
872 /* Set TLB flush state as checked until we return from the world switch. */
873 ASMAtomicWriteBool(&pVCpu->hm.s.fCheckedTLBFlush, true);
874
875 /* Check for explicit TLB flushes. */
876 if (VMCPU_FF_TEST_AND_CLEAR(pVCpu, VMCPU_FF_TLB_FLUSH))
877 {
878 pVCpu->hm.s.fForceTLBFlush = true;
879 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlb);
880 }
881
882 pVmcb->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_NOTHING;
883
884 if (pVM->hm.s.svm.fAlwaysFlushTLB)
885 {
886 /*
887 * This is the AMD erratum 170. We need to flush the entire TLB for each world switch. Sad.
888 */
889 pCpu->uCurrentAsid = 1;
890 pVCpu->hm.s.uCurrentAsid = 1;
891 pVCpu->hm.s.cTlbFlushes = pCpu->cTlbFlushes;
892 pVmcb->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_ENTIRE;
893
894 /* Clear the VMCB Clean Bit for NP while flushing the TLB. See @bugref{7152}. */
895 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_NP;
896
897 /* Keep track of last CPU ID even when flushing all the time. */
898 if (fNewAsid)
899 pVCpu->hm.s.idLastCpu = pCpu->idCpu;
900 }
901 else if (pVCpu->hm.s.fForceTLBFlush)
902 {
903 /* Clear the VMCB Clean Bit for NP while flushing the TLB. See @bugref{7152}. */
904 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_NP;
905
906 if (fNewAsid)
907 {
908 ++pCpu->uCurrentAsid;
909 bool fHitASIDLimit = false;
910 if (pCpu->uCurrentAsid >= pVM->hm.s.uMaxAsid)
911 {
912 pCpu->uCurrentAsid = 1; /* Wraparound at 1; host uses 0 */
913 pCpu->cTlbFlushes++; /* All VCPUs that run on this host CPU must use a new VPID. */
914 fHitASIDLimit = true;
915
916 if (pVM->hm.s.svm.u32Features & AMD_CPUID_SVM_FEATURE_EDX_FLUSH_BY_ASID)
917 {
918 pVmcb->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_SINGLE_CONTEXT;
919 pCpu->fFlushAsidBeforeUse = true;
920 }
921 else
922 {
923 pVmcb->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_ENTIRE;
924 pCpu->fFlushAsidBeforeUse = false;
925 }
926 }
927
928 if ( !fHitASIDLimit
929 && pCpu->fFlushAsidBeforeUse)
930 {
931 if (pVM->hm.s.svm.u32Features & AMD_CPUID_SVM_FEATURE_EDX_FLUSH_BY_ASID)
932 pVmcb->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_SINGLE_CONTEXT;
933 else
934 {
935 pVmcb->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_ENTIRE;
936 pCpu->fFlushAsidBeforeUse = false;
937 }
938 }
939
940 pVCpu->hm.s.uCurrentAsid = pCpu->uCurrentAsid;
941 pVCpu->hm.s.idLastCpu = pCpu->idCpu;
942 pVCpu->hm.s.cTlbFlushes = pCpu->cTlbFlushes;
943 }
944 else
945 {
946 if (pVM->hm.s.svm.u32Features & AMD_CPUID_SVM_FEATURE_EDX_FLUSH_BY_ASID)
947 pVmcb->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_SINGLE_CONTEXT;
948 else
949 pVmcb->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_ENTIRE;
950 }
951
952 pVCpu->hm.s.fForceTLBFlush = false;
953 }
954
955 /* Update VMCB with the ASID. */
956 if (pVmcb->ctrl.TLBCtrl.n.u32ASID != pVCpu->hm.s.uCurrentAsid)
957 {
958 pVmcb->ctrl.TLBCtrl.n.u32ASID = pVCpu->hm.s.uCurrentAsid;
959 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_ASID;
960 }
961
962 AssertMsg(pVCpu->hm.s.idLastCpu == pCpu->idCpu,
963 ("vcpu idLastCpu=%u pcpu idCpu=%u\n", pVCpu->hm.s.idLastCpu, pCpu->idCpu));
964 AssertMsg(pVCpu->hm.s.cTlbFlushes == pCpu->cTlbFlushes,
965 ("Flush count mismatch for cpu %u (%u vs %u)\n", pCpu->idCpu, pVCpu->hm.s.cTlbFlushes, pCpu->cTlbFlushes));
966 AssertMsg(pCpu->uCurrentAsid >= 1 && pCpu->uCurrentAsid < pVM->hm.s.uMaxAsid,
967 ("cpu%d uCurrentAsid = %x\n", pCpu->idCpu, pCpu->uCurrentAsid));
968 AssertMsg(pVCpu->hm.s.uCurrentAsid >= 1 && pVCpu->hm.s.uCurrentAsid < pVM->hm.s.uMaxAsid,
969 ("cpu%d VM uCurrentAsid = %x\n", pCpu->idCpu, pVCpu->hm.s.uCurrentAsid));
970
971#ifdef VBOX_WITH_STATISTICS
972 if (pVmcb->ctrl.TLBCtrl.n.u8TLBFlush == SVM_TLB_FLUSH_NOTHING)
973 STAM_COUNTER_INC(&pVCpu->hm.s.StatNoFlushTlbWorldSwitch);
974 else if ( pVmcb->ctrl.TLBCtrl.n.u8TLBFlush == SVM_TLB_FLUSH_SINGLE_CONTEXT
975 || pVmcb->ctrl.TLBCtrl.n.u8TLBFlush == SVM_TLB_FLUSH_SINGLE_CONTEXT_RETAIN_GLOBALS)
976 {
977 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushAsid);
978 }
979 else
980 {
981 Assert(pVmcb->ctrl.TLBCtrl.n.u8TLBFlush == SVM_TLB_FLUSH_ENTIRE);
982 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushEntire);
983 }
984#endif
985}
986
987
988/** @name 64-bit guest on 32-bit host OS helper functions.
989 *
990 * The host CPU is still 64-bit capable but the host OS is running in 32-bit
991 * mode (code segment, paging). These wrappers/helpers perform the necessary
992 * bits for the 32->64 switcher.
993 *
994 * @{ */
995#if HC_ARCH_BITS == 32 && defined(VBOX_ENABLE_64_BITS_GUESTS)
996/**
997 * Prepares for and executes VMRUN (64-bit guests on a 32-bit host).
998 *
999 * @returns VBox status code.
1000 * @param HCPhysVmcbHost Physical address of host VMCB.
1001 * @param HCPhysVmcb Physical address of the VMCB.
1002 * @param pCtx Pointer to the guest-CPU context.
1003 * @param pVM The cross context VM structure.
1004 * @param pVCpu The cross context virtual CPU structure.
1005 */
1006DECLASM(int) SVMR0VMSwitcherRun64(RTHCPHYS HCPhysVmcbHost, RTHCPHYS HCPhysVmcb, PCPUMCTX pCtx, PVM pVM, PVMCPU pVCpu)
1007{
1008 uint32_t aParam[8];
1009 aParam[0] = (uint32_t)(HCPhysVmcbHost); /* Param 1: HCPhysVmcbHost - Lo. */
1010 aParam[1] = (uint32_t)(HCPhysVmcbHost >> 32); /* Param 1: HCPhysVmcbHost - Hi. */
1011 aParam[2] = (uint32_t)(HCPhysVmcb); /* Param 2: HCPhysVmcb - Lo. */
1012 aParam[3] = (uint32_t)(HCPhysVmcb >> 32); /* Param 2: HCPhysVmcb - Hi. */
1013 aParam[4] = VM_RC_ADDR(pVM, pVM);
1014 aParam[5] = 0;
1015 aParam[6] = VM_RC_ADDR(pVM, pVCpu);
1016 aParam[7] = 0;
1017
1018 return SVMR0Execute64BitsHandler(pVM, pVCpu, pCtx, HM64ON32OP_SVMRCVMRun64, RT_ELEMENTS(aParam), &aParam[0]);
1019}
1020
1021
1022/**
1023 * Executes the specified VMRUN handler in 64-bit mode.
1024 *
1025 * @returns VBox status code.
1026 * @param pVM The cross context VM structure.
1027 * @param pVCpu The cross context virtual CPU structure.
1028 * @param pCtx Pointer to the guest-CPU context.
1029 * @param enmOp The operation to perform.
1030 * @param cParams Number of parameters.
1031 * @param paParam Array of 32-bit parameters.
1032 */
1033VMMR0DECL(int) SVMR0Execute64BitsHandler(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, HM64ON32OP enmOp,
1034 uint32_t cParams, uint32_t *paParam)
1035{
1036 AssertReturn(pVM->hm.s.pfnHost32ToGuest64R0, VERR_HM_NO_32_TO_64_SWITCHER);
1037 Assert(enmOp > HM64ON32OP_INVALID && enmOp < HM64ON32OP_END);
1038
1039 NOREF(pCtx);
1040
1041 /* Disable interrupts. */
1042 RTHCUINTREG uOldEFlags = ASMIntDisableFlags();
1043
1044#ifdef VBOX_WITH_VMMR0_DISABLE_LAPIC_NMI
1045 RTCPUID idHostCpu = RTMpCpuId();
1046 CPUMR0SetLApic(pVCpu, idHostCpu);
1047#endif
1048
1049 CPUMSetHyperESP(pVCpu, VMMGetStackRC(pVCpu));
1050 CPUMSetHyperEIP(pVCpu, enmOp);
1051 for (int i = (int)cParams - 1; i >= 0; i--)
1052 CPUMPushHyper(pVCpu, paParam[i]);
1053
1054 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatWorldSwitch3264, z);
1055 /* Call the switcher. */
1056 int rc = pVM->hm.s.pfnHost32ToGuest64R0(pVM, RT_OFFSETOF(VM, aCpus[pVCpu->idCpu].cpum) - RT_OFFSETOF(VM, cpum));
1057 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatWorldSwitch3264, z);
1058
1059 /* Restore interrupts. */
1060 ASMSetFlags(uOldEFlags);
1061 return rc;
1062}
1063
1064#endif /* HC_ARCH_BITS == 32 && defined(VBOX_ENABLE_64_BITS_GUESTS) */
1065/** @} */
1066
1067
1068/**
1069 * Adds an exception to the intercept exception bitmap in the VMCB and updates
1070 * the corresponding VMCB Clean bit.
1071 *
1072 * @param pVmcb Pointer to the VM control block.
1073 * @param u32Xcpt The value of the exception (X86_XCPT_*).
1074 */
1075DECLINLINE(void) hmR0SvmAddXcptIntercept(PSVMVMCB pVmcb, uint32_t u32Xcpt)
1076{
1077 if (!(pVmcb->ctrl.u32InterceptException & RT_BIT(u32Xcpt)))
1078 {
1079 pVmcb->ctrl.u32InterceptException |= RT_BIT(u32Xcpt);
1080 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
1081 }
1082}
1083
1084
1085/**
1086 * Removes an exception from the intercept-exception bitmap in the VMCB and
1087 * updates the corresponding VMCB Clean bit.
1088 *
1089 * @param pVmcb Pointer to the VM control block.
1090 * @param u32Xcpt The value of the exception (X86_XCPT_*).
1091 */
1092DECLINLINE(void) hmR0SvmRemoveXcptIntercept(PSVMVMCB pVmcb, uint32_t u32Xcpt)
1093{
1094 Assert(u32Xcpt != X86_XCPT_DB);
1095 Assert(u32Xcpt != X86_XCPT_AC);
1096#ifndef HMSVM_ALWAYS_TRAP_ALL_XCPTS
1097 if (pVmcb->ctrl.u32InterceptException & RT_BIT(u32Xcpt))
1098 {
1099 pVmcb->ctrl.u32InterceptException &= ~RT_BIT(u32Xcpt);
1100 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
1101 }
1102#endif
1103}
1104
1105
1106/**
1107 * Loads the guest CR0 control register into the guest-state area in the VMCB.
1108 * Although the guest CR0 is a separate field in the VMCB we have to consider
1109 * the FPU state itself which is shared between the host and the guest.
1110 *
1111 * @returns VBox status code.
1112 * @param pVCpu The cross context virtual CPU structure.
1113 * @param pVmcb Pointer to the VM control block.
1114 * @param pCtx Pointer to the guest-CPU context.
1115 *
1116 * @remarks No-long-jump zone!!!
1117 */
1118static void hmR0SvmLoadSharedCR0(PVMCPU pVCpu, PSVMVMCB pVmcb, PCPUMCTX pCtx)
1119{
1120 /*
1121 * Guest CR0.
1122 */
1123 PVM pVM = pVCpu->CTX_SUFF(pVM);
1124 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_CR0))
1125 {
1126 uint64_t u64GuestCR0 = pCtx->cr0;
1127
1128 /* Always enable caching. */
1129 u64GuestCR0 &= ~(X86_CR0_CD | X86_CR0_NW);
1130
1131 /*
1132 * When Nested Paging is not available use shadow page tables and intercept #PFs (the latter done in SVMR0SetupVM()).
1133 */
1134 if (!pVM->hm.s.fNestedPaging)
1135 {
1136 u64GuestCR0 |= X86_CR0_PG; /* When Nested Paging is not available, use shadow page tables. */
1137 u64GuestCR0 |= X86_CR0_WP; /* Guest CPL 0 writes to its read-only pages should cause a #PF #VMEXIT. */
1138 }
1139
1140 /*
1141 * Guest FPU bits.
1142 */
1143 bool fInterceptNM = false;
1144 bool fInterceptMF = false;
1145 u64GuestCR0 |= X86_CR0_NE; /* Use internal x87 FPU exceptions handling rather than external interrupts. */
1146 if (CPUMIsGuestFPUStateActive(pVCpu))
1147 {
1148 /* Catch floating point exceptions if we need to report them to the guest in a different way. */
1149 if (!(pCtx->cr0 & X86_CR0_NE))
1150 {
1151 Log4(("hmR0SvmLoadGuestControlRegs: Intercepting Guest CR0.MP Old-style FPU handling!!!\n"));
1152 fInterceptMF = true;
1153 }
1154 }
1155 else
1156 {
1157 fInterceptNM = true; /* Guest FPU inactive, #VMEXIT on #NM for lazy FPU loading. */
1158 u64GuestCR0 |= X86_CR0_TS /* Guest can task switch quickly and do lazy FPU syncing. */
1159 | X86_CR0_MP; /* FWAIT/WAIT should not ignore CR0.TS and should generate #NM. */
1160 }
1161
1162 /*
1163 * Update the exception intercept bitmap.
1164 */
1165 if (fInterceptNM)
1166 hmR0SvmAddXcptIntercept(pVmcb, X86_XCPT_NM);
1167 else
1168 hmR0SvmRemoveXcptIntercept(pVmcb, X86_XCPT_NM);
1169
1170 if (fInterceptMF)
1171 hmR0SvmAddXcptIntercept(pVmcb, X86_XCPT_MF);
1172 else
1173 hmR0SvmRemoveXcptIntercept(pVmcb, X86_XCPT_MF);
1174
1175 pVmcb->guest.u64CR0 = u64GuestCR0;
1176 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_CRX_EFER;
1177 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_CR0);
1178 }
1179}
1180
1181
1182/**
1183 * Loads the guest control registers (CR2, CR3, CR4) into the VMCB.
1184 *
1185 * @returns VBox status code.
1186 * @param pVCpu The cross context virtual CPU structure.
1187 * @param pVmcb Pointer to the VM control block.
1188 * @param pCtx Pointer to the guest-CPU context.
1189 *
1190 * @remarks No-long-jump zone!!!
1191 */
1192static int hmR0SvmLoadGuestControlRegs(PVMCPU pVCpu, PSVMVMCB pVmcb, PCPUMCTX pCtx)
1193{
1194 PVM pVM = pVCpu->CTX_SUFF(pVM);
1195
1196 /*
1197 * Guest CR2.
1198 */
1199 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_CR2))
1200 {
1201 pVmcb->guest.u64CR2 = pCtx->cr2;
1202 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_CR2;
1203 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_CR2);
1204 }
1205
1206 /*
1207 * Guest CR3.
1208 */
1209 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_CR3))
1210 {
1211 if (pVM->hm.s.fNestedPaging)
1212 {
1213 PGMMODE enmShwPagingMode;
1214#if HC_ARCH_BITS == 32
1215 if (CPUMIsGuestInLongModeEx(pCtx))
1216 enmShwPagingMode = PGMMODE_AMD64_NX;
1217 else
1218#endif
1219 enmShwPagingMode = PGMGetHostMode(pVM);
1220
1221 pVmcb->ctrl.u64NestedPagingCR3 = PGMGetNestedCR3(pVCpu, enmShwPagingMode);
1222 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_NP;
1223 Assert(pVmcb->ctrl.u64NestedPagingCR3);
1224 pVmcb->guest.u64CR3 = pCtx->cr3;
1225 }
1226 else
1227 pVmcb->guest.u64CR3 = PGMGetHyperCR3(pVCpu);
1228
1229 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_CRX_EFER;
1230 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_CR3);
1231 }
1232
1233 /*
1234 * Guest CR4.
1235 * ASSUMES this is done everytime we get in from ring-3! (XCR0)
1236 */
1237 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_CR4))
1238 {
1239 uint64_t u64GuestCR4 = pCtx->cr4;
1240 if (!pVM->hm.s.fNestedPaging)
1241 {
1242 switch (pVCpu->hm.s.enmShadowMode)
1243 {
1244 case PGMMODE_REAL:
1245 case PGMMODE_PROTECTED: /* Protected mode, no paging. */
1246 AssertFailed();
1247 return VERR_PGM_UNSUPPORTED_SHADOW_PAGING_MODE;
1248
1249 case PGMMODE_32_BIT: /* 32-bit paging. */
1250 u64GuestCR4 &= ~X86_CR4_PAE;
1251 break;
1252
1253 case PGMMODE_PAE: /* PAE paging. */
1254 case PGMMODE_PAE_NX: /* PAE paging with NX enabled. */
1255 /** Must use PAE paging as we could use physical memory > 4 GB */
1256 u64GuestCR4 |= X86_CR4_PAE;
1257 break;
1258
1259 case PGMMODE_AMD64: /* 64-bit AMD paging (long mode). */
1260 case PGMMODE_AMD64_NX: /* 64-bit AMD paging (long mode) with NX enabled. */
1261#ifdef VBOX_ENABLE_64_BITS_GUESTS
1262 break;
1263#else
1264 AssertFailed();
1265 return VERR_PGM_UNSUPPORTED_SHADOW_PAGING_MODE;
1266#endif
1267
1268 default: /* shut up gcc */
1269 AssertFailed();
1270 return VERR_PGM_UNSUPPORTED_SHADOW_PAGING_MODE;
1271 }
1272 }
1273
1274 pVmcb->guest.u64CR4 = u64GuestCR4;
1275 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_CRX_EFER;
1276
1277 /* Whether to save/load/restore XCR0 during world switch depends on CR4.OSXSAVE and host+guest XCR0. */
1278 pVCpu->hm.s.fLoadSaveGuestXcr0 = (u64GuestCR4 & X86_CR4_OSXSAVE) && pCtx->aXcr[0] != ASMGetXcr0();
1279
1280 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_CR4);
1281 }
1282
1283 return VINF_SUCCESS;
1284}
1285
1286
1287/**
1288 * Loads the guest segment registers into the VMCB.
1289 *
1290 * @returns VBox status code.
1291 * @param pVCpu The cross context virtual CPU structure.
1292 * @param pVmcb Pointer to the VM control block.
1293 * @param pCtx Pointer to the guest-CPU context.
1294 *
1295 * @remarks No-long-jump zone!!!
1296 */
1297static void hmR0SvmLoadGuestSegmentRegs(PVMCPU pVCpu, PSVMVMCB pVmcb, PCPUMCTX pCtx)
1298{
1299 /* Guest Segment registers: CS, SS, DS, ES, FS, GS. */
1300 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_SEGMENT_REGS))
1301 {
1302 HMSVM_SEG_REG_COPY_TO_VMCB(pCtx, pVmcb, CS, cs);
1303 HMSVM_SEG_REG_COPY_TO_VMCB(pCtx, pVmcb, SS, ss);
1304 HMSVM_SEG_REG_COPY_TO_VMCB(pCtx, pVmcb, DS, ds);
1305 HMSVM_SEG_REG_COPY_TO_VMCB(pCtx, pVmcb, ES, es);
1306 HMSVM_SEG_REG_COPY_TO_VMCB(pCtx, pVmcb, FS, fs);
1307 HMSVM_SEG_REG_COPY_TO_VMCB(pCtx, pVmcb, GS, gs);
1308
1309 pVmcb->guest.u8CPL = pCtx->ss.Attr.n.u2Dpl;
1310 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_SEG;
1311 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_SEGMENT_REGS);
1312 }
1313
1314 /* Guest TR. */
1315 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_TR))
1316 {
1317 HMSVM_SEG_REG_COPY_TO_VMCB(pCtx, pVmcb, TR, tr);
1318 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_TR);
1319 }
1320
1321 /* Guest LDTR. */
1322 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_LDTR))
1323 {
1324 HMSVM_SEG_REG_COPY_TO_VMCB(pCtx, pVmcb, LDTR, ldtr);
1325 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_LDTR);
1326 }
1327
1328 /* Guest GDTR. */
1329 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_GDTR))
1330 {
1331 pVmcb->guest.GDTR.u32Limit = pCtx->gdtr.cbGdt;
1332 pVmcb->guest.GDTR.u64Base = pCtx->gdtr.pGdt;
1333 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_DT;
1334 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_GDTR);
1335 }
1336
1337 /* Guest IDTR. */
1338 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_IDTR))
1339 {
1340 pVmcb->guest.IDTR.u32Limit = pCtx->idtr.cbIdt;
1341 pVmcb->guest.IDTR.u64Base = pCtx->idtr.pIdt;
1342 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_DT;
1343 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_IDTR);
1344 }
1345}
1346
1347
1348/**
1349 * Loads the guest MSRs into the VMCB.
1350 *
1351 * @param pVCpu The cross context virtual CPU structure.
1352 * @param pVmcb Pointer to the VM control block.
1353 * @param pCtx Pointer to the guest-CPU context.
1354 *
1355 * @remarks No-long-jump zone!!!
1356 */
1357static void hmR0SvmLoadGuestMsrs(PVMCPU pVCpu, PSVMVMCB pVmcb, PCPUMCTX pCtx)
1358{
1359 /* Guest Sysenter MSRs. */
1360 pVmcb->guest.u64SysEnterCS = pCtx->SysEnter.cs;
1361 pVmcb->guest.u64SysEnterEIP = pCtx->SysEnter.eip;
1362 pVmcb->guest.u64SysEnterESP = pCtx->SysEnter.esp;
1363
1364 /*
1365 * Guest EFER MSR.
1366 * AMD-V requires guest EFER.SVME to be set. Weird.
1367 * See AMD spec. 15.5.1 "Basic Operation" | "Canonicalization and Consistency Checks".
1368 */
1369 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_EFER_MSR))
1370 {
1371 pVmcb->guest.u64EFER = pCtx->msrEFER | MSR_K6_EFER_SVME;
1372 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_CRX_EFER;
1373 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_EFER_MSR);
1374 }
1375
1376 /* 64-bit MSRs. */
1377 if (CPUMIsGuestInLongModeEx(pCtx))
1378 {
1379 pVmcb->guest.FS.u64Base = pCtx->fs.u64Base;
1380 pVmcb->guest.GS.u64Base = pCtx->gs.u64Base;
1381 }
1382 else
1383 {
1384 /* If the guest isn't in 64-bit mode, clear MSR_K6_LME bit from guest EFER otherwise AMD-V expects amd64 shadow paging. */
1385 if (pCtx->msrEFER & MSR_K6_EFER_LME)
1386 {
1387 pVmcb->guest.u64EFER &= ~MSR_K6_EFER_LME;
1388 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_CRX_EFER;
1389 }
1390 }
1391
1392
1393 /** @todo The following are used in 64-bit only (SYSCALL/SYSRET) but they might
1394 * be writable in 32-bit mode. Clarify with AMD spec. */
1395 pVmcb->guest.u64STAR = pCtx->msrSTAR;
1396 pVmcb->guest.u64LSTAR = pCtx->msrLSTAR;
1397 pVmcb->guest.u64CSTAR = pCtx->msrCSTAR;
1398 pVmcb->guest.u64SFMASK = pCtx->msrSFMASK;
1399 pVmcb->guest.u64KernelGSBase = pCtx->msrKERNELGSBASE;
1400}
1401
1402
1403/**
1404 * Loads the guest state into the VMCB and programs the necessary intercepts
1405 * accordingly.
1406 *
1407 * @param pVCpu The cross context virtual CPU structure.
1408 * @param pVmcb Pointer to the VM control block.
1409 * @param pCtx Pointer to the guest-CPU context.
1410 *
1411 * @remarks No-long-jump zone!!!
1412 * @remarks Requires EFLAGS to be up-to-date in the VMCB!
1413 */
1414static void hmR0SvmLoadSharedDebugState(PVMCPU pVCpu, PSVMVMCB pVmcb, PCPUMCTX pCtx)
1415{
1416 if (!HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_DEBUG))
1417 return;
1418 Assert((pCtx->dr[6] & X86_DR6_RA1_MASK) == X86_DR6_RA1_MASK); Assert((pCtx->dr[6] & X86_DR6_RAZ_MASK) == 0);
1419 Assert((pCtx->dr[7] & X86_DR7_RA1_MASK) == X86_DR7_RA1_MASK); Assert((pCtx->dr[7] & X86_DR7_RAZ_MASK) == 0);
1420
1421 bool fInterceptMovDRx = false;
1422
1423 /*
1424 * Anyone single stepping on the host side? If so, we'll have to use the
1425 * trap flag in the guest EFLAGS since AMD-V doesn't have a trap flag on
1426 * the VMM level like the VT-x implementations does.
1427 */
1428 bool const fStepping = pVCpu->hm.s.fSingleInstruction;
1429 if (fStepping)
1430 {
1431 pVCpu->hm.s.fClearTrapFlag = true;
1432 pVmcb->guest.u64RFlags |= X86_EFL_TF;
1433 fInterceptMovDRx = true; /* Need clean DR6, no guest mess. */
1434 }
1435 else
1436 Assert(!DBGFIsStepping(pVCpu));
1437
1438 if ( fStepping
1439 || (CPUMGetHyperDR7(pVCpu) & X86_DR7_ENABLED_MASK))
1440 {
1441 /*
1442 * Use the combined guest and host DRx values found in the hypervisor
1443 * register set because the debugger has breakpoints active or someone
1444 * is single stepping on the host side.
1445 *
1446 * Note! DBGF expects a clean DR6 state before executing guest code.
1447 */
1448#if HC_ARCH_BITS == 32 && defined(VBOX_WITH_64_BITS_GUESTS)
1449 if ( CPUMIsGuestInLongModeEx(pCtx)
1450 && !CPUMIsHyperDebugStateActivePending(pVCpu))
1451 {
1452 CPUMR0LoadHyperDebugState(pVCpu, false /* include DR6 */);
1453 Assert(!CPUMIsGuestDebugStateActivePending(pVCpu));
1454 Assert(CPUMIsHyperDebugStateActivePending(pVCpu));
1455 }
1456 else
1457#endif
1458 if (!CPUMIsHyperDebugStateActive(pVCpu))
1459 {
1460 CPUMR0LoadHyperDebugState(pVCpu, false /* include DR6 */);
1461 Assert(!CPUMIsGuestDebugStateActive(pVCpu));
1462 Assert(CPUMIsHyperDebugStateActive(pVCpu));
1463 }
1464
1465 /* Update DR6 & DR7. (The other DRx values are handled by CPUM one way or the other.) */
1466 if ( pVmcb->guest.u64DR6 != X86_DR6_INIT_VAL
1467 || pVmcb->guest.u64DR7 != CPUMGetHyperDR7(pVCpu))
1468 {
1469 pVmcb->guest.u64DR7 = CPUMGetHyperDR7(pVCpu);
1470 pVmcb->guest.u64DR6 = X86_DR6_INIT_VAL;
1471 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_DRX;
1472 pVCpu->hm.s.fUsingHyperDR7 = true;
1473 }
1474
1475 /** @todo If we cared, we could optimize to allow the guest to read registers
1476 * with the same values. */
1477 fInterceptMovDRx = true;
1478 Log5(("hmR0SvmLoadSharedDebugState: Loaded hyper DRx\n"));
1479 }
1480 else
1481 {
1482 /*
1483 * Update DR6, DR7 with the guest values if necessary.
1484 */
1485 if ( pVmcb->guest.u64DR7 != pCtx->dr[7]
1486 || pVmcb->guest.u64DR6 != pCtx->dr[6])
1487 {
1488 pVmcb->guest.u64DR7 = pCtx->dr[7];
1489 pVmcb->guest.u64DR6 = pCtx->dr[6];
1490 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_DRX;
1491 pVCpu->hm.s.fUsingHyperDR7 = false;
1492 }
1493
1494 /*
1495 * If the guest has enabled debug registers, we need to load them prior to
1496 * executing guest code so they'll trigger at the right time.
1497 */
1498 if (pCtx->dr[7] & (X86_DR7_ENABLED_MASK | X86_DR7_GD)) /** @todo Why GD? */
1499 {
1500#if HC_ARCH_BITS == 32 && defined(VBOX_WITH_64_BITS_GUESTS)
1501 if ( CPUMIsGuestInLongModeEx(pCtx)
1502 && !CPUMIsGuestDebugStateActivePending(pVCpu))
1503 {
1504 CPUMR0LoadGuestDebugState(pVCpu, false /* include DR6 */);
1505 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxArmed);
1506 Assert(!CPUMIsHyperDebugStateActivePending(pVCpu));
1507 Assert(CPUMIsGuestDebugStateActivePending(pVCpu));
1508 }
1509 else
1510#endif
1511 if (!CPUMIsGuestDebugStateActive(pVCpu))
1512 {
1513 CPUMR0LoadGuestDebugState(pVCpu, false /* include DR6 */);
1514 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxArmed);
1515 Assert(!CPUMIsHyperDebugStateActive(pVCpu));
1516 Assert(CPUMIsGuestDebugStateActive(pVCpu));
1517 }
1518 Log5(("hmR0SvmLoadSharedDebugState: Loaded guest DRx\n"));
1519 }
1520 /*
1521 * If no debugging enabled, we'll lazy load DR0-3. We don't need to
1522 * intercept #DB as DR6 is updated in the VMCB.
1523 *
1524 * Note! If we cared and dared, we could skip intercepting \#DB here.
1525 * However, \#DB shouldn't be performance critical, so we'll play safe
1526 * and keep the code similar to the VT-x code and always intercept it.
1527 */
1528#if HC_ARCH_BITS == 32 && defined(VBOX_WITH_64_BITS_GUESTS)
1529 else if ( !CPUMIsGuestDebugStateActivePending(pVCpu)
1530 && !CPUMIsGuestDebugStateActive(pVCpu))
1531#else
1532 else if (!CPUMIsGuestDebugStateActive(pVCpu))
1533#endif
1534 {
1535 fInterceptMovDRx = true;
1536 }
1537 }
1538
1539 Assert(pVmcb->ctrl.u32InterceptException & RT_BIT_32(X86_XCPT_DB));
1540 if (fInterceptMovDRx)
1541 {
1542 if ( pVmcb->ctrl.u16InterceptRdDRx != 0xffff
1543 || pVmcb->ctrl.u16InterceptWrDRx != 0xffff)
1544 {
1545 pVmcb->ctrl.u16InterceptRdDRx = 0xffff;
1546 pVmcb->ctrl.u16InterceptWrDRx = 0xffff;
1547 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
1548 }
1549 }
1550 else
1551 {
1552 if ( pVmcb->ctrl.u16InterceptRdDRx
1553 || pVmcb->ctrl.u16InterceptWrDRx)
1554 {
1555 pVmcb->ctrl.u16InterceptRdDRx = 0;
1556 pVmcb->ctrl.u16InterceptWrDRx = 0;
1557 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
1558 }
1559 }
1560
1561 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_DEBUG);
1562}
1563
1564
1565/**
1566 * Loads the guest APIC state (currently just the TPR).
1567 *
1568 * @returns VBox status code.
1569 * @param pVCpu The cross context virtual CPU structure.
1570 * @param pVmcb Pointer to the VM control block.
1571 * @param pCtx Pointer to the guest-CPU context.
1572 */
1573static int hmR0SvmLoadGuestApicState(PVMCPU pVCpu, PSVMVMCB pVmcb, PCPUMCTX pCtx)
1574{
1575 if (!HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_SVM_GUEST_APIC_STATE))
1576 return VINF_SUCCESS;
1577
1578 int rc = VINF_SUCCESS;
1579 PVM pVM = pVCpu->CTX_SUFF(pVM);
1580 if ( PDMHasApic(pVM)
1581 && APICIsEnabled(pVCpu))
1582 {
1583 bool fPendingIntr;
1584 uint8_t u8Tpr;
1585 rc = APICGetTpr(pVCpu, &u8Tpr, &fPendingIntr, NULL /* pu8PendingIrq */);
1586 AssertRCReturn(rc, rc);
1587
1588 /* Assume that we need to trap all TPR accesses and thus need not check on
1589 every #VMEXIT if we should update the TPR. */
1590 Assert(pVmcb->ctrl.IntCtrl.n.u1VIrqMasking);
1591 pVCpu->hm.s.svm.fSyncVTpr = false;
1592
1593 /* 32-bit guests uses LSTAR MSR for patching guest code which touches the TPR. */
1594 if (pVM->hm.s.fTPRPatchingActive)
1595 {
1596 pCtx->msrLSTAR = u8Tpr;
1597
1598 /* If there are interrupts pending, intercept LSTAR writes, otherwise don't intercept reads or writes. */
1599 if (fPendingIntr)
1600 hmR0SvmSetMsrPermission(pVCpu, MSR_K8_LSTAR, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_INTERCEPT_WRITE);
1601 else
1602 {
1603 hmR0SvmSetMsrPermission(pVCpu, MSR_K8_LSTAR, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
1604 pVCpu->hm.s.svm.fSyncVTpr = true;
1605 }
1606 }
1607 else
1608 {
1609 /* Bits 3-0 of the VTPR field correspond to bits 7-4 of the TPR (which is the Task-Priority Class). */
1610 pVmcb->ctrl.IntCtrl.n.u8VTPR = (u8Tpr >> 4);
1611
1612 /* If there are interrupts pending, intercept CR8 writes to evaluate ASAP if we can deliver the interrupt to the guest. */
1613 if (fPendingIntr)
1614 pVmcb->ctrl.u16InterceptWrCRx |= RT_BIT(8);
1615 else
1616 {
1617 pVmcb->ctrl.u16InterceptWrCRx &= ~RT_BIT(8);
1618 pVCpu->hm.s.svm.fSyncVTpr = true;
1619 }
1620
1621 pVmcb->ctrl.u64VmcbCleanBits &= ~(HMSVM_VMCB_CLEAN_INTERCEPTS | HMSVM_VMCB_CLEAN_TPR);
1622 }
1623 }
1624
1625 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_SVM_GUEST_APIC_STATE);
1626 return rc;
1627}
1628
1629
1630/**
1631 * Loads the exception interrupts required for guest execution in the VMCB.
1632 *
1633 * @returns VBox status code.
1634 * @param pVCpu The cross context virtual CPU structure.
1635 * @param pVmcb Pointer to the VM control block.
1636 * @param pCtx Pointer to the guest-CPU context.
1637 */
1638static int hmR0SvmLoadGuestXcptIntercepts(PVMCPU pVCpu, PSVMVMCB pVmcb, PCPUMCTX pCtx)
1639{
1640 NOREF(pCtx);
1641 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_XCPT_INTERCEPTS))
1642 {
1643 /* Trap #UD for GIM provider (e.g. for hypercalls). */
1644 if (pVCpu->hm.s.fGIMTrapXcptUD)
1645 hmR0SvmAddXcptIntercept(pVmcb, X86_XCPT_UD);
1646 else
1647 hmR0SvmRemoveXcptIntercept(pVmcb, X86_XCPT_UD);
1648
1649 /* Trap #BP for INT3 debug breakpoints set by the VM debugger. */
1650 if (pVCpu->CTX_SUFF(pVM)->dbgf.ro.cEnabledInt3Breakpoints)
1651 hmR0SvmAddXcptIntercept(pVmcb, X86_XCPT_BP);
1652 else
1653 hmR0SvmRemoveXcptIntercept(pVmcb, X86_XCPT_BP);
1654
1655 /* The remaining intercepts are handled elsewhere, e.g. in hmR0SvmLoadSharedCR0(). */
1656 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_XCPT_INTERCEPTS);
1657 }
1658 return VINF_SUCCESS;
1659}
1660
1661
1662/**
1663 * Sets up the appropriate function to run guest code.
1664 *
1665 * @returns VBox status code.
1666 * @param pVCpu The cross context virtual CPU structure.
1667 * @param pCtx Pointer to the guest-CPU context.
1668 *
1669 * @remarks No-long-jump zone!!!
1670 */
1671static int hmR0SvmSetupVMRunHandler(PVMCPU pVCpu, PCPUMCTX pCtx)
1672{
1673 if (CPUMIsGuestInLongModeEx(pCtx))
1674 {
1675#ifndef VBOX_ENABLE_64_BITS_GUESTS
1676 return VERR_PGM_UNSUPPORTED_SHADOW_PAGING_MODE;
1677#endif
1678 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.fAllow64BitGuests); /* Guaranteed by hmR3InitFinalizeR0(). */
1679#if HC_ARCH_BITS == 32
1680 /* 32-bit host. We need to switch to 64-bit before running the 64-bit guest. */
1681 pVCpu->hm.s.svm.pfnVMRun = SVMR0VMSwitcherRun64;
1682#else
1683 /* 64-bit host or hybrid host. */
1684 pVCpu->hm.s.svm.pfnVMRun = SVMR0VMRun64;
1685#endif
1686 }
1687 else
1688 {
1689 /* Guest is not in long mode, use the 32-bit handler. */
1690 pVCpu->hm.s.svm.pfnVMRun = SVMR0VMRun;
1691 }
1692 return VINF_SUCCESS;
1693}
1694
1695
1696/**
1697 * Enters the AMD-V session.
1698 *
1699 * @returns VBox status code.
1700 * @param pVM The cross context VM structure.
1701 * @param pVCpu The cross context virtual CPU structure.
1702 * @param pCpu Pointer to the CPU info struct.
1703 */
1704VMMR0DECL(int) SVMR0Enter(PVM pVM, PVMCPU pVCpu, PHMGLOBALCPUINFO pCpu)
1705{
1706 AssertPtr(pVM);
1707 AssertPtr(pVCpu);
1708 Assert(pVM->hm.s.svm.fSupported);
1709 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1710 NOREF(pVM); NOREF(pCpu);
1711
1712 LogFlowFunc(("pVM=%p pVCpu=%p\n", pVM, pVCpu));
1713 Assert(HMCPU_CF_IS_SET(pVCpu, HM_CHANGED_HOST_CONTEXT | HM_CHANGED_HOST_GUEST_SHARED_STATE));
1714
1715 pVCpu->hm.s.fLeaveDone = false;
1716 return VINF_SUCCESS;
1717}
1718
1719
1720/**
1721 * Thread-context callback for AMD-V.
1722 *
1723 * @param enmEvent The thread-context event.
1724 * @param pVCpu The cross context virtual CPU structure.
1725 * @param fGlobalInit Whether global VT-x/AMD-V init. is used.
1726 * @thread EMT(pVCpu)
1727 */
1728VMMR0DECL(void) SVMR0ThreadCtxCallback(RTTHREADCTXEVENT enmEvent, PVMCPU pVCpu, bool fGlobalInit)
1729{
1730 NOREF(fGlobalInit);
1731
1732 switch (enmEvent)
1733 {
1734 case RTTHREADCTXEVENT_OUT:
1735 {
1736 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1737 Assert(VMMR0ThreadCtxHookIsEnabled(pVCpu));
1738 VMCPU_ASSERT_EMT(pVCpu);
1739
1740 /* No longjmps (log-flush, locks) in this fragile context. */
1741 VMMRZCallRing3Disable(pVCpu);
1742
1743 if (!pVCpu->hm.s.fLeaveDone)
1744 {
1745 hmR0SvmLeave(pVCpu);
1746 pVCpu->hm.s.fLeaveDone = true;
1747 }
1748
1749 /* Leave HM context, takes care of local init (term). */
1750 int rc = HMR0LeaveCpu(pVCpu);
1751 AssertRC(rc); NOREF(rc);
1752
1753 /* Restore longjmp state. */
1754 VMMRZCallRing3Enable(pVCpu);
1755 STAM_REL_COUNTER_INC(&pVCpu->hm.s.StatSwitchPreempt);
1756 break;
1757 }
1758
1759 case RTTHREADCTXEVENT_IN:
1760 {
1761 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1762 Assert(VMMR0ThreadCtxHookIsEnabled(pVCpu));
1763 VMCPU_ASSERT_EMT(pVCpu);
1764
1765 /* No longjmps (log-flush, locks) in this fragile context. */
1766 VMMRZCallRing3Disable(pVCpu);
1767
1768 /*
1769 * Initialize the bare minimum state required for HM. This takes care of
1770 * initializing AMD-V if necessary (onlined CPUs, local init etc.)
1771 */
1772 int rc = HMR0EnterCpu(pVCpu);
1773 AssertRC(rc); NOREF(rc);
1774 Assert(HMCPU_CF_IS_SET(pVCpu, HM_CHANGED_HOST_CONTEXT | HM_CHANGED_HOST_GUEST_SHARED_STATE));
1775
1776 pVCpu->hm.s.fLeaveDone = false;
1777
1778 /* Restore longjmp state. */
1779 VMMRZCallRing3Enable(pVCpu);
1780 break;
1781 }
1782
1783 default:
1784 break;
1785 }
1786}
1787
1788
1789/**
1790 * Saves the host state.
1791 *
1792 * @returns VBox status code.
1793 * @param pVM The cross context VM structure.
1794 * @param pVCpu The cross context virtual CPU structure.
1795 *
1796 * @remarks No-long-jump zone!!!
1797 */
1798VMMR0DECL(int) SVMR0SaveHostState(PVM pVM, PVMCPU pVCpu)
1799{
1800 NOREF(pVM);
1801 NOREF(pVCpu);
1802 /* Nothing to do here. AMD-V does this for us automatically during the world-switch. */
1803 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_HOST_CONTEXT);
1804 return VINF_SUCCESS;
1805}
1806
1807
1808/**
1809 * Loads the guest state into the VMCB.
1810 *
1811 * The CPU state will be loaded from these fields on every successful VM-entry.
1812 * Also sets up the appropriate VMRUN function to execute guest code based on
1813 * the guest CPU mode.
1814 *
1815 * @returns VBox status code.
1816 * @param pVM The cross context VM structure.
1817 * @param pVCpu The cross context virtual CPU structure.
1818 * @param pCtx Pointer to the guest-CPU context.
1819 *
1820 * @remarks No-long-jump zone!!!
1821 */
1822static int hmR0SvmLoadGuestState(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
1823{
1824 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
1825 AssertMsgReturn(pVmcb, ("Invalid pVmcb\n"), VERR_SVM_INVALID_PVMCB);
1826
1827 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatLoadGuestState, x);
1828
1829 int rc = hmR0SvmLoadGuestControlRegs(pVCpu, pVmcb, pCtx);
1830 AssertLogRelMsgRCReturn(rc, ("hmR0SvmLoadGuestControlRegs! rc=%Rrc (pVM=%p pVCpu=%p)\n", rc, pVM, pVCpu), rc);
1831
1832 hmR0SvmLoadGuestSegmentRegs(pVCpu, pVmcb, pCtx);
1833 hmR0SvmLoadGuestMsrs(pVCpu, pVmcb, pCtx);
1834
1835 pVmcb->guest.u64RIP = pCtx->rip;
1836 pVmcb->guest.u64RSP = pCtx->rsp;
1837 pVmcb->guest.u64RFlags = pCtx->eflags.u32;
1838 pVmcb->guest.u64RAX = pCtx->rax;
1839
1840 rc = hmR0SvmLoadGuestApicState(pVCpu, pVmcb, pCtx);
1841 AssertLogRelMsgRCReturn(rc, ("hmR0SvmLoadGuestApicState! rc=%Rrc (pVM=%p pVCpu=%p)\n", rc, pVM, pVCpu), rc);
1842
1843 rc = hmR0SvmLoadGuestXcptIntercepts(pVCpu, pVmcb, pCtx);
1844 AssertLogRelMsgRCReturn(rc, ("hmR0SvmLoadGuestXcptIntercepts! rc=%Rrc (pVM=%p pVCpu=%p)\n", rc, pVM, pVCpu), rc);
1845
1846 rc = hmR0SvmSetupVMRunHandler(pVCpu, pCtx);
1847 AssertLogRelMsgRCReturn(rc, ("hmR0SvmSetupVMRunHandler! rc=%Rrc (pVM=%p pVCpu=%p)\n", rc, pVM, pVCpu), rc);
1848
1849 /* Clear any unused and reserved bits. */
1850 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_RIP /* Unused (loaded unconditionally). */
1851 | HM_CHANGED_GUEST_RSP
1852 | HM_CHANGED_GUEST_RFLAGS
1853 | HM_CHANGED_GUEST_SYSENTER_CS_MSR
1854 | HM_CHANGED_GUEST_SYSENTER_EIP_MSR
1855 | HM_CHANGED_GUEST_SYSENTER_ESP_MSR
1856 | HM_CHANGED_GUEST_LAZY_MSRS /* Unused. */
1857 | HM_CHANGED_SVM_RESERVED1 /* Reserved. */
1858 | HM_CHANGED_SVM_RESERVED2
1859 | HM_CHANGED_SVM_RESERVED3
1860 | HM_CHANGED_SVM_RESERVED4);
1861
1862 /* All the guest state bits should be loaded except maybe the host context and/or shared host/guest bits. */
1863 AssertMsg( !HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_ALL_GUEST)
1864 || HMCPU_CF_IS_PENDING_ONLY(pVCpu, HM_CHANGED_HOST_CONTEXT | HM_CHANGED_HOST_GUEST_SHARED_STATE),
1865 ("fContextUseFlags=%#RX32\n", HMCPU_CF_VALUE(pVCpu)));
1866
1867 Log4(("Load: CS:RIP=%04x:%RX64 EFL=%#x SS:RSP=%04x:%RX64\n", pCtx->cs.Sel, pCtx->rip, pCtx->eflags.u, pCtx->ss.Sel, pCtx->rsp));
1868 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatLoadGuestState, x);
1869 return rc;
1870}
1871
1872
1873/**
1874 * Loads the state shared between the host and guest into the
1875 * VMCB.
1876 *
1877 * @param pVCpu The cross context virtual CPU structure.
1878 * @param pVmcb Pointer to the VM control block.
1879 * @param pCtx Pointer to the guest-CPU context.
1880 *
1881 * @remarks No-long-jump zone!!!
1882 */
1883static void hmR0SvmLoadSharedState(PVMCPU pVCpu, PSVMVMCB pVmcb, PCPUMCTX pCtx)
1884{
1885 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1886 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
1887
1888 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_CR0))
1889 hmR0SvmLoadSharedCR0(pVCpu, pVmcb, pCtx);
1890
1891 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_DEBUG))
1892 hmR0SvmLoadSharedDebugState(pVCpu, pVmcb, pCtx);
1893
1894 /* Unused on AMD-V. */
1895 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_GUEST_LAZY_MSRS);
1896
1897 AssertMsg(!HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_HOST_GUEST_SHARED_STATE),
1898 ("fContextUseFlags=%#RX32\n", HMCPU_CF_VALUE(pVCpu)));
1899}
1900
1901
1902/**
1903 * Saves the entire guest state from the VMCB into the
1904 * guest-CPU context. Currently there is no residual state left in the CPU that
1905 * is not updated in the VMCB.
1906 *
1907 * @returns VBox status code.
1908 * @param pVCpu The cross context virtual CPU structure.
1909 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
1910 * out-of-sync. Make sure to update the required fields
1911 * before using them.
1912 */
1913static void hmR0SvmSaveGuestState(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
1914{
1915 Assert(VMMRZCallRing3IsEnabled(pVCpu));
1916
1917 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
1918
1919 pMixedCtx->rip = pVmcb->guest.u64RIP;
1920 pMixedCtx->rsp = pVmcb->guest.u64RSP;
1921 pMixedCtx->eflags.u32 = pVmcb->guest.u64RFlags;
1922 pMixedCtx->rax = pVmcb->guest.u64RAX;
1923
1924 /*
1925 * Guest interrupt shadow.
1926 */
1927 if (pVmcb->ctrl.u64IntShadow & SVM_INTERRUPT_SHADOW_ACTIVE)
1928 EMSetInhibitInterruptsPC(pVCpu, pMixedCtx->rip);
1929 else if (VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
1930 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
1931
1932 /*
1933 * Guest Control registers: CR2, CR3 (handled at the end) - accesses to other control registers are always intercepted.
1934 */
1935 pMixedCtx->cr2 = pVmcb->guest.u64CR2;
1936
1937 /*
1938 * Guest MSRs.
1939 */
1940 pMixedCtx->msrSTAR = pVmcb->guest.u64STAR; /* legacy syscall eip, cs & ss */
1941 pMixedCtx->msrLSTAR = pVmcb->guest.u64LSTAR; /* 64-bit mode syscall rip */
1942 pMixedCtx->msrCSTAR = pVmcb->guest.u64CSTAR; /* compatibility mode syscall rip */
1943 pMixedCtx->msrSFMASK = pVmcb->guest.u64SFMASK; /* syscall flag mask */
1944 pMixedCtx->msrKERNELGSBASE = pVmcb->guest.u64KernelGSBase; /* swapgs exchange value */
1945 pMixedCtx->SysEnter.cs = pVmcb->guest.u64SysEnterCS;
1946 pMixedCtx->SysEnter.eip = pVmcb->guest.u64SysEnterEIP;
1947 pMixedCtx->SysEnter.esp = pVmcb->guest.u64SysEnterESP;
1948
1949 /*
1950 * Guest segment registers (includes FS, GS base MSRs for 64-bit guests).
1951 */
1952 HMSVM_SEG_REG_COPY_FROM_VMCB(pMixedCtx, pVmcb, CS, cs);
1953 HMSVM_SEG_REG_COPY_FROM_VMCB(pMixedCtx, pVmcb, SS, ss);
1954 HMSVM_SEG_REG_COPY_FROM_VMCB(pMixedCtx, pVmcb, DS, ds);
1955 HMSVM_SEG_REG_COPY_FROM_VMCB(pMixedCtx, pVmcb, ES, es);
1956 HMSVM_SEG_REG_COPY_FROM_VMCB(pMixedCtx, pVmcb, FS, fs);
1957 HMSVM_SEG_REG_COPY_FROM_VMCB(pMixedCtx, pVmcb, GS, gs);
1958
1959 /*
1960 * Correct the hidden CS granularity bit. Haven't seen it being wrong in any other
1961 * register (yet).
1962 */
1963 /** @todo SELM might need to be fixed as it too should not care about the
1964 * granularity bit. See @bugref{6785}. */
1965 if ( !pMixedCtx->cs.Attr.n.u1Granularity
1966 && pMixedCtx->cs.Attr.n.u1Present
1967 && pMixedCtx->cs.u32Limit > UINT32_C(0xfffff))
1968 {
1969 Assert((pMixedCtx->cs.u32Limit & 0xfff) == 0xfff);
1970 pMixedCtx->cs.Attr.n.u1Granularity = 1;
1971 }
1972
1973#ifdef VBOX_STRICT
1974# define HMSVM_ASSERT_SEG_GRANULARITY(reg) \
1975 AssertMsg( !pMixedCtx->reg.Attr.n.u1Present \
1976 || ( pMixedCtx->reg.Attr.n.u1Granularity \
1977 ? (pMixedCtx->reg.u32Limit & 0xfff) == 0xfff \
1978 : pMixedCtx->reg.u32Limit <= UINT32_C(0xfffff)), \
1979 ("Invalid Segment Attributes Limit=%#RX32 Attr=%#RX32 Base=%#RX64\n", pMixedCtx->reg.u32Limit, \
1980 pMixedCtx->reg.Attr.u, pMixedCtx->reg.u64Base))
1981
1982 HMSVM_ASSERT_SEG_GRANULARITY(cs);
1983 HMSVM_ASSERT_SEG_GRANULARITY(ss);
1984 HMSVM_ASSERT_SEG_GRANULARITY(ds);
1985 HMSVM_ASSERT_SEG_GRANULARITY(es);
1986 HMSVM_ASSERT_SEG_GRANULARITY(fs);
1987 HMSVM_ASSERT_SEG_GRANULARITY(gs);
1988
1989# undef HMSVM_ASSERT_SEL_GRANULARITY
1990#endif
1991
1992 /*
1993 * Sync the hidden SS DPL field. AMD CPUs have a separate CPL field in the VMCB and uses that
1994 * and thus it's possible that when the CPL changes during guest execution that the SS DPL
1995 * isn't updated by AMD-V. Observed on some AMD Fusion CPUs with 64-bit guests.
1996 * See AMD spec. 15.5.1 "Basic operation".
1997 */
1998 Assert(!(pVmcb->guest.u8CPL & ~0x3));
1999 pMixedCtx->ss.Attr.n.u2Dpl = pVmcb->guest.u8CPL & 0x3;
2000
2001 /*
2002 * Guest TR.
2003 * Fixup TR attributes so it's compatible with Intel. Important when saved-states are used
2004 * between Intel and AMD. See @bugref{6208#c39}.
2005 * ASSUME that it's normally correct and that we're in 32-bit or 64-bit mode.
2006 */
2007 HMSVM_SEG_REG_COPY_FROM_VMCB(pMixedCtx, pVmcb, TR, tr);
2008 if (pMixedCtx->tr.Attr.n.u4Type != X86_SEL_TYPE_SYS_386_TSS_BUSY)
2009 {
2010 if ( pMixedCtx->tr.Attr.n.u4Type == X86_SEL_TYPE_SYS_386_TSS_AVAIL
2011 || CPUMIsGuestInLongModeEx(pMixedCtx))
2012 pMixedCtx->tr.Attr.n.u4Type = X86_SEL_TYPE_SYS_386_TSS_BUSY;
2013 else if (pMixedCtx->tr.Attr.n.u4Type == X86_SEL_TYPE_SYS_286_TSS_AVAIL)
2014 pMixedCtx->tr.Attr.n.u4Type = X86_SEL_TYPE_SYS_286_TSS_BUSY;
2015 }
2016
2017 /*
2018 * Guest Descriptor-Table registers.
2019 */
2020 HMSVM_SEG_REG_COPY_FROM_VMCB(pMixedCtx, pVmcb, LDTR, ldtr);
2021 pMixedCtx->gdtr.cbGdt = pVmcb->guest.GDTR.u32Limit;
2022 pMixedCtx->gdtr.pGdt = pVmcb->guest.GDTR.u64Base;
2023
2024 pMixedCtx->idtr.cbIdt = pVmcb->guest.IDTR.u32Limit;
2025 pMixedCtx->idtr.pIdt = pVmcb->guest.IDTR.u64Base;
2026
2027 /*
2028 * Guest Debug registers.
2029 */
2030 if (!pVCpu->hm.s.fUsingHyperDR7)
2031 {
2032 pMixedCtx->dr[6] = pVmcb->guest.u64DR6;
2033 pMixedCtx->dr[7] = pVmcb->guest.u64DR7;
2034 }
2035 else
2036 {
2037 Assert(pVmcb->guest.u64DR7 == CPUMGetHyperDR7(pVCpu));
2038 CPUMSetHyperDR6(pVCpu, pVmcb->guest.u64DR6);
2039 }
2040
2041 /*
2042 * With Nested Paging, CR3 changes are not intercepted. Therefore, sync. it now.
2043 * This is done as the very last step of syncing the guest state, as PGMUpdateCR3() may cause longjmp's to ring-3.
2044 */
2045 if ( pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging
2046 && pMixedCtx->cr3 != pVmcb->guest.u64CR3)
2047 {
2048 CPUMSetGuestCR3(pVCpu, pVmcb->guest.u64CR3);
2049 PGMUpdateCR3(pVCpu, pVmcb->guest.u64CR3);
2050 }
2051}
2052
2053
2054/**
2055 * Does the necessary state syncing before returning to ring-3 for any reason
2056 * (longjmp, preemption, voluntary exits to ring-3) from AMD-V.
2057 *
2058 * @param pVCpu The cross context virtual CPU structure.
2059 *
2060 * @remarks No-long-jmp zone!!!
2061 */
2062static void hmR0SvmLeave(PVMCPU pVCpu)
2063{
2064 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
2065 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
2066 Assert(VMMR0IsLogFlushDisabled(pVCpu));
2067
2068 /*
2069 * !!! IMPORTANT !!!
2070 * If you modify code here, make sure to check whether hmR0SvmCallRing3Callback() needs to be updated too.
2071 */
2072
2073 /* Restore host FPU state if necessary and resync on next R0 reentry .*/
2074 if (CPUMR0FpuStateMaybeSaveGuestAndRestoreHost(pVCpu))
2075 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR0);
2076
2077 /*
2078 * Restore host debug registers if necessary and resync on next R0 reentry.
2079 */
2080#ifdef VBOX_STRICT
2081 if (CPUMIsHyperDebugStateActive(pVCpu))
2082 {
2083 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
2084 Assert(pVmcb->ctrl.u16InterceptRdDRx == 0xffff);
2085 Assert(pVmcb->ctrl.u16InterceptWrDRx == 0xffff);
2086 }
2087#endif
2088 if (CPUMR0DebugStateMaybeSaveGuestAndRestoreHost(pVCpu, false /* save DR6 */))
2089 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_DEBUG);
2090
2091 Assert(!CPUMIsHyperDebugStateActive(pVCpu));
2092 Assert(!CPUMIsGuestDebugStateActive(pVCpu));
2093
2094 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatEntry);
2095 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatLoadGuestState);
2096 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatExit1);
2097 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hm.s.StatExit2);
2098 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchLongJmpToR3);
2099
2100 VMCPU_CMPXCHG_STATE(pVCpu, VMCPUSTATE_STARTED_HM, VMCPUSTATE_STARTED_EXEC);
2101}
2102
2103
2104/**
2105 * Leaves the AMD-V session.
2106 *
2107 * @returns VBox status code.
2108 * @param pVCpu The cross context virtual CPU structure.
2109 */
2110static int hmR0SvmLeaveSession(PVMCPU pVCpu)
2111{
2112 HM_DISABLE_PREEMPT();
2113 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
2114 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
2115
2116 /* When thread-context hooks are used, we can avoid doing the leave again if we had been preempted before
2117 and done this from the SVMR0ThreadCtxCallback(). */
2118 if (!pVCpu->hm.s.fLeaveDone)
2119 {
2120 hmR0SvmLeave(pVCpu);
2121 pVCpu->hm.s.fLeaveDone = true;
2122 }
2123
2124 /*
2125 * !!! IMPORTANT !!!
2126 * If you modify code here, make sure to check whether hmR0SvmCallRing3Callback() needs to be updated too.
2127 */
2128
2129 /** @todo eliminate the need for calling VMMR0ThreadCtxHookDisable here! */
2130 /* Deregister hook now that we've left HM context before re-enabling preemption. */
2131 VMMR0ThreadCtxHookDisable(pVCpu);
2132
2133 /* Leave HM context. This takes care of local init (term). */
2134 int rc = HMR0LeaveCpu(pVCpu);
2135
2136 HM_RESTORE_PREEMPT();
2137 return rc;
2138}
2139
2140
2141/**
2142 * Does the necessary state syncing before doing a longjmp to ring-3.
2143 *
2144 * @returns VBox status code.
2145 * @param pVCpu The cross context virtual CPU structure.
2146 *
2147 * @remarks No-long-jmp zone!!!
2148 */
2149static int hmR0SvmLongJmpToRing3(PVMCPU pVCpu)
2150{
2151 return hmR0SvmLeaveSession(pVCpu);
2152}
2153
2154
2155/**
2156 * VMMRZCallRing3() callback wrapper which saves the guest state (or restores
2157 * any remaining host state) before we longjump to ring-3 and possibly get
2158 * preempted.
2159 *
2160 * @param pVCpu The cross context virtual CPU structure.
2161 * @param enmOperation The operation causing the ring-3 longjump.
2162 * @param pvUser The user argument (pointer to the possibly
2163 * out-of-date guest-CPU context).
2164 */
2165static DECLCALLBACK(int) hmR0SvmCallRing3Callback(PVMCPU pVCpu, VMMCALLRING3 enmOperation, void *pvUser)
2166{
2167 RT_NOREF_PV(pvUser);
2168
2169 if (enmOperation == VMMCALLRING3_VM_R0_ASSERTION)
2170 {
2171 /*
2172 * !!! IMPORTANT !!!
2173 * If you modify code here, make sure to check whether hmR0SvmLeave() and hmR0SvmLeaveSession() needs
2174 * to be updated too. This is a stripped down version which gets out ASAP trying to not trigger any assertion.
2175 */
2176 VMMRZCallRing3RemoveNotification(pVCpu);
2177 VMMRZCallRing3Disable(pVCpu);
2178 HM_DISABLE_PREEMPT();
2179
2180 /* Restore host FPU state if necessary and resync on next R0 reentry. */
2181 CPUMR0FpuStateMaybeSaveGuestAndRestoreHost(pVCpu);
2182
2183 /* Restore host debug registers if necessary and resync on next R0 reentry. */
2184 CPUMR0DebugStateMaybeSaveGuestAndRestoreHost(pVCpu, false /* save DR6 */);
2185
2186 /* Deregister the hook now that we've left HM context before re-enabling preemption. */
2187 /** @todo eliminate the need for calling VMMR0ThreadCtxHookDisable here! */
2188 VMMR0ThreadCtxHookDisable(pVCpu);
2189
2190 /* Leave HM context. This takes care of local init (term). */
2191 HMR0LeaveCpu(pVCpu);
2192
2193 HM_RESTORE_PREEMPT();
2194 return VINF_SUCCESS;
2195 }
2196
2197 Assert(pVCpu);
2198 Assert(pvUser);
2199 Assert(VMMRZCallRing3IsEnabled(pVCpu));
2200 HMSVM_ASSERT_PREEMPT_SAFE();
2201
2202 VMMRZCallRing3Disable(pVCpu);
2203 Assert(VMMR0IsLogFlushDisabled(pVCpu));
2204
2205 Log4(("hmR0SvmCallRing3Callback->hmR0SvmLongJmpToRing3\n"));
2206 int rc = hmR0SvmLongJmpToRing3(pVCpu);
2207 AssertRCReturn(rc, rc);
2208
2209 VMMRZCallRing3Enable(pVCpu);
2210 return VINF_SUCCESS;
2211}
2212
2213
2214/**
2215 * Take necessary actions before going back to ring-3.
2216 *
2217 * An action requires us to go back to ring-3. This function does the necessary
2218 * steps before we can safely return to ring-3. This is not the same as longjmps
2219 * to ring-3, this is voluntary.
2220 *
2221 * @param pVM The cross context VM structure.
2222 * @param pVCpu The cross context virtual CPU structure.
2223 * @param pCtx Pointer to the guest-CPU context.
2224 * @param rcExit The reason for exiting to ring-3. Can be
2225 * VINF_VMM_UNKNOWN_RING3_CALL.
2226 */
2227static void hmR0SvmExitToRing3(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, int rcExit)
2228{
2229 Assert(pVM);
2230 Assert(pVCpu);
2231 Assert(pCtx);
2232 HMSVM_ASSERT_PREEMPT_SAFE();
2233
2234 /* Please, no longjumps here (any logging shouldn't flush jump back to ring-3). NO LOGGING BEFORE THIS POINT! */
2235 VMMRZCallRing3Disable(pVCpu);
2236 Log4(("hmR0SvmExitToRing3: rcExit=%d\n", rcExit));
2237
2238 /* We need to do this only while truly exiting the "inner loop" back to ring-3 and -not- for any longjmp to ring3. */
2239 if (pVCpu->hm.s.Event.fPending)
2240 {
2241 hmR0SvmPendingEventToTrpmTrap(pVCpu);
2242 Assert(!pVCpu->hm.s.Event.fPending);
2243 }
2244
2245 /* If we're emulating an instruction, we shouldn't have any TRPM traps pending
2246 and if we're injecting an event we should have a TRPM trap pending. */
2247 AssertMsg(rcExit != VINF_EM_RAW_INJECT_TRPM_EVENT || TRPMHasTrap(pVCpu), ("rcExit=%Rrc\n", rcExit));
2248 AssertMsg(rcExit != VINF_EM_RAW_EMULATE_INSTR || !TRPMHasTrap(pVCpu), ("rcExit=%Rrc\n", rcExit));
2249
2250 /* Sync. the necessary state for going back to ring-3. */
2251 hmR0SvmLeaveSession(pVCpu);
2252 STAM_COUNTER_DEC(&pVCpu->hm.s.StatSwitchLongJmpToR3);
2253
2254 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_TO_R3);
2255 CPUMSetChangedFlags(pVCpu, CPUM_CHANGED_SYSENTER_MSR
2256 | CPUM_CHANGED_LDTR
2257 | CPUM_CHANGED_GDTR
2258 | CPUM_CHANGED_IDTR
2259 | CPUM_CHANGED_TR
2260 | CPUM_CHANGED_HIDDEN_SEL_REGS);
2261 if ( pVM->hm.s.fNestedPaging
2262 && CPUMIsGuestPagingEnabledEx(pCtx))
2263 {
2264 CPUMSetChangedFlags(pVCpu, CPUM_CHANGED_GLOBAL_TLB_FLUSH);
2265 }
2266
2267 /* On our way back from ring-3 reload the guest state if there is a possibility of it being changed. */
2268 if (rcExit != VINF_EM_RAW_INTERRUPT)
2269 HMCPU_CF_SET(pVCpu, HM_CHANGED_ALL_GUEST);
2270
2271 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchExitToR3);
2272
2273 /* We do -not- want any longjmp notifications after this! We must return to ring-3 ASAP. */
2274 VMMRZCallRing3RemoveNotification(pVCpu);
2275 VMMRZCallRing3Enable(pVCpu);
2276}
2277
2278
2279/**
2280 * Updates the use of TSC offsetting mode for the CPU and adjusts the necessary
2281 * intercepts.
2282 *
2283 * @param pVM The cross context VM structure.
2284 * @param pVCpu The cross context virtual CPU structure.
2285 *
2286 * @remarks No-long-jump zone!!!
2287 */
2288static void hmR0SvmUpdateTscOffsetting(PVM pVM, PVMCPU pVCpu)
2289{
2290 bool fParavirtTsc;
2291 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
2292 bool fCanUseRealTsc = TMCpuTickCanUseRealTSC(pVM, pVCpu, &pVmcb->ctrl.u64TSCOffset, &fParavirtTsc);
2293 if (fCanUseRealTsc)
2294 {
2295 pVmcb->ctrl.u64InterceptCtrl &= ~SVM_CTRL_INTERCEPT_RDTSC;
2296 pVmcb->ctrl.u64InterceptCtrl &= ~SVM_CTRL_INTERCEPT_RDTSCP;
2297 STAM_COUNTER_INC(&pVCpu->hm.s.StatTscOffset);
2298 }
2299 else
2300 {
2301 pVmcb->ctrl.u64InterceptCtrl |= SVM_CTRL_INTERCEPT_RDTSC;
2302 pVmcb->ctrl.u64InterceptCtrl |= SVM_CTRL_INTERCEPT_RDTSCP;
2303 STAM_COUNTER_INC(&pVCpu->hm.s.StatTscIntercept);
2304 }
2305 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
2306
2307 /** @todo later optimize this to be done elsewhere and not before every
2308 * VM-entry. */
2309 if (fParavirtTsc)
2310 {
2311 /* Currently neither Hyper-V nor KVM need to update their paravirt. TSC
2312 information before every VM-entry, hence disable it for performance sake. */
2313#if 0
2314 int rc = GIMR0UpdateParavirtTsc(pVM, 0 /* u64Offset */);
2315 AssertRC(rc);
2316#endif
2317 STAM_COUNTER_INC(&pVCpu->hm.s.StatTscParavirt);
2318 }
2319}
2320
2321
2322/**
2323 * Sets an event as a pending event to be injected into the guest.
2324 *
2325 * @param pVCpu The cross context virtual CPU structure.
2326 * @param pEvent Pointer to the SVM event.
2327 * @param GCPtrFaultAddress The fault-address (CR2) in case it's a
2328 * page-fault.
2329 *
2330 * @remarks Statistics counter assumes this is a guest event being reflected to
2331 * the guest i.e. 'StatInjectPendingReflect' is incremented always.
2332 */
2333DECLINLINE(void) hmR0SvmSetPendingEvent(PVMCPU pVCpu, PSVMEVENT pEvent, RTGCUINTPTR GCPtrFaultAddress)
2334{
2335 Assert(!pVCpu->hm.s.Event.fPending);
2336 Assert(pEvent->n.u1Valid);
2337
2338 pVCpu->hm.s.Event.u64IntInfo = pEvent->u;
2339 pVCpu->hm.s.Event.fPending = true;
2340 pVCpu->hm.s.Event.GCPtrFaultAddress = GCPtrFaultAddress;
2341
2342 Log4(("hmR0SvmSetPendingEvent: u=%#RX64 u8Vector=%#x Type=%#x ErrorCodeValid=%RTbool ErrorCode=%#RX32\n", pEvent->u,
2343 pEvent->n.u8Vector, (uint8_t)pEvent->n.u3Type, !!pEvent->n.u1ErrorCodeValid, pEvent->n.u32ErrorCode));
2344}
2345
2346
2347/**
2348 * Injects an event into the guest upon VMRUN by updating the relevant field
2349 * in the VMCB.
2350 *
2351 * @param pVCpu The cross context virtual CPU structure.
2352 * @param pVmcb Pointer to the guest VM control block.
2353 * @param pCtx Pointer to the guest-CPU context.
2354 * @param pEvent Pointer to the event.
2355 *
2356 * @remarks No-long-jump zone!!!
2357 * @remarks Requires CR0!
2358 */
2359DECLINLINE(void) hmR0SvmInjectEventVmcb(PVMCPU pVCpu, PSVMVMCB pVmcb, PCPUMCTX pCtx, PSVMEVENT pEvent)
2360{
2361 NOREF(pVCpu); NOREF(pCtx);
2362
2363 pVmcb->ctrl.EventInject.u = pEvent->u;
2364 STAM_COUNTER_INC(&pVCpu->hm.s.paStatInjectedIrqsR0[pEvent->n.u8Vector & MASK_INJECT_IRQ_STAT]);
2365
2366 Log4(("hmR0SvmInjectEventVmcb: u=%#RX64 u8Vector=%#x Type=%#x ErrorCodeValid=%RTbool ErrorCode=%#RX32\n", pEvent->u,
2367 pEvent->n.u8Vector, (uint8_t)pEvent->n.u3Type, !!pEvent->n.u1ErrorCodeValid, pEvent->n.u32ErrorCode));
2368}
2369
2370
2371
2372/**
2373 * Converts any TRPM trap into a pending HM event. This is typically used when
2374 * entering from ring-3 (not longjmp returns).
2375 *
2376 * @param pVCpu The cross context virtual CPU structure.
2377 */
2378static void hmR0SvmTrpmTrapToPendingEvent(PVMCPU pVCpu)
2379{
2380 Assert(TRPMHasTrap(pVCpu));
2381 Assert(!pVCpu->hm.s.Event.fPending);
2382
2383 uint8_t uVector;
2384 TRPMEVENT enmTrpmEvent;
2385 RTGCUINT uErrCode;
2386 RTGCUINTPTR GCPtrFaultAddress;
2387 uint8_t cbInstr;
2388
2389 int rc = TRPMQueryTrapAll(pVCpu, &uVector, &enmTrpmEvent, &uErrCode, &GCPtrFaultAddress, &cbInstr);
2390 AssertRC(rc);
2391
2392 SVMEVENT Event;
2393 Event.u = 0;
2394 Event.n.u1Valid = 1;
2395 Event.n.u8Vector = uVector;
2396
2397 /* Refer AMD spec. 15.20 "Event Injection" for the format. */
2398 if (enmTrpmEvent == TRPM_TRAP)
2399 {
2400 Event.n.u3Type = SVM_EVENT_EXCEPTION;
2401 switch (uVector)
2402 {
2403 case X86_XCPT_NMI:
2404 {
2405 Event.n.u3Type = SVM_EVENT_NMI;
2406 break;
2407 }
2408
2409 case X86_XCPT_PF:
2410 case X86_XCPT_DF:
2411 case X86_XCPT_TS:
2412 case X86_XCPT_NP:
2413 case X86_XCPT_SS:
2414 case X86_XCPT_GP:
2415 case X86_XCPT_AC:
2416 {
2417 Event.n.u1ErrorCodeValid = 1;
2418 Event.n.u32ErrorCode = uErrCode;
2419 break;
2420 }
2421 }
2422 }
2423 else if (enmTrpmEvent == TRPM_HARDWARE_INT)
2424 Event.n.u3Type = SVM_EVENT_EXTERNAL_IRQ;
2425 else if (enmTrpmEvent == TRPM_SOFTWARE_INT)
2426 Event.n.u3Type = SVM_EVENT_SOFTWARE_INT;
2427 else
2428 AssertMsgFailed(("Invalid TRPM event type %d\n", enmTrpmEvent));
2429
2430 rc = TRPMResetTrap(pVCpu);
2431 AssertRC(rc);
2432
2433 Log4(("TRPM->HM event: u=%#RX64 u8Vector=%#x uErrorCodeValid=%RTbool uErrorCode=%#RX32\n", Event.u, Event.n.u8Vector,
2434 !!Event.n.u1ErrorCodeValid, Event.n.u32ErrorCode));
2435
2436 hmR0SvmSetPendingEvent(pVCpu, &Event, GCPtrFaultAddress);
2437}
2438
2439
2440/**
2441 * Converts any pending SVM event into a TRPM trap. Typically used when leaving
2442 * AMD-V to execute any instruction.
2443 *
2444 * @param pVCpu The cross context virtual CPU structure.
2445 */
2446static void hmR0SvmPendingEventToTrpmTrap(PVMCPU pVCpu)
2447{
2448 Assert(pVCpu->hm.s.Event.fPending);
2449 Assert(TRPMQueryTrap(pVCpu, NULL /* pu8TrapNo */, NULL /* pEnmType */) == VERR_TRPM_NO_ACTIVE_TRAP);
2450
2451 SVMEVENT Event;
2452 Event.u = pVCpu->hm.s.Event.u64IntInfo;
2453
2454 uint8_t uVector = Event.n.u8Vector;
2455 uint8_t uVectorType = Event.n.u3Type;
2456
2457 TRPMEVENT enmTrapType;
2458 switch (uVectorType)
2459 {
2460 case SVM_EVENT_EXTERNAL_IRQ:
2461 enmTrapType = TRPM_HARDWARE_INT;
2462 break;
2463 case SVM_EVENT_SOFTWARE_INT:
2464 enmTrapType = TRPM_SOFTWARE_INT;
2465 break;
2466 case SVM_EVENT_EXCEPTION:
2467 case SVM_EVENT_NMI:
2468 enmTrapType = TRPM_TRAP;
2469 break;
2470 default:
2471 AssertMsgFailed(("Invalid pending-event type %#x\n", uVectorType));
2472 enmTrapType = TRPM_32BIT_HACK;
2473 break;
2474 }
2475
2476 Log4(("HM event->TRPM: uVector=%#x enmTrapType=%d\n", uVector, uVectorType));
2477
2478 int rc = TRPMAssertTrap(pVCpu, uVector, enmTrapType);
2479 AssertRC(rc);
2480
2481 if (Event.n.u1ErrorCodeValid)
2482 TRPMSetErrorCode(pVCpu, Event.n.u32ErrorCode);
2483
2484 if ( uVectorType == SVM_EVENT_EXCEPTION
2485 && uVector == X86_XCPT_PF)
2486 {
2487 TRPMSetFaultAddress(pVCpu, pVCpu->hm.s.Event.GCPtrFaultAddress);
2488 Assert(pVCpu->hm.s.Event.GCPtrFaultAddress == CPUMGetGuestCR2(pVCpu));
2489 }
2490 else if (uVectorType == SVM_EVENT_SOFTWARE_INT)
2491 {
2492 AssertMsg( uVectorType == SVM_EVENT_SOFTWARE_INT
2493 || (uVector == X86_XCPT_BP || uVector == X86_XCPT_OF),
2494 ("Invalid vector: uVector=%#x uVectorType=%#x\n", uVector, uVectorType));
2495 TRPMSetInstrLength(pVCpu, pVCpu->hm.s.Event.cbInstr);
2496 }
2497 pVCpu->hm.s.Event.fPending = false;
2498}
2499
2500
2501/**
2502 * Gets the guest's interrupt-shadow.
2503 *
2504 * @returns The guest's interrupt-shadow.
2505 * @param pVCpu The cross context virtual CPU structure.
2506 * @param pCtx Pointer to the guest-CPU context.
2507 *
2508 * @remarks No-long-jump zone!!!
2509 * @remarks Has side-effects with VMCPU_FF_INHIBIT_INTERRUPTS force-flag.
2510 */
2511DECLINLINE(uint32_t) hmR0SvmGetGuestIntrShadow(PVMCPU pVCpu, PCPUMCTX pCtx)
2512{
2513 /*
2514 * Instructions like STI and MOV SS inhibit interrupts till the next instruction completes. Check if we should
2515 * inhibit interrupts or clear any existing interrupt-inhibition.
2516 */
2517 uint32_t uIntrState = 0;
2518 if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
2519 {
2520 if (pCtx->rip != EMGetInhibitInterruptsPC(pVCpu))
2521 {
2522 /*
2523 * We can clear the inhibit force flag as even if we go back to the recompiler without executing guest code in
2524 * AMD-V, the flag's condition to be cleared is met and thus the cleared state is correct.
2525 */
2526 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
2527 }
2528 else
2529 uIntrState = SVM_INTERRUPT_SHADOW_ACTIVE;
2530 }
2531 return uIntrState;
2532}
2533
2534
2535/**
2536 * Sets the virtual interrupt intercept control in the VMCB which
2537 * instructs AMD-V to cause a \#VMEXIT as soon as the guest is in a state to
2538 * receive interrupts.
2539 *
2540 * @param pVmcb Pointer to the VM control block.
2541 */
2542DECLINLINE(void) hmR0SvmSetVirtIntrIntercept(PSVMVMCB pVmcb)
2543{
2544 if (!(pVmcb->ctrl.u64InterceptCtrl & SVM_CTRL_INTERCEPT_VINTR))
2545 {
2546 pVmcb->ctrl.IntCtrl.n.u1VIrqValid = 1; /* A virtual interrupt is pending. */
2547 pVmcb->ctrl.IntCtrl.n.u8VIrqVector = 0; /* Not necessary as we #VMEXIT for delivering the interrupt. */
2548 pVmcb->ctrl.u64InterceptCtrl |= SVM_CTRL_INTERCEPT_VINTR;
2549 pVmcb->ctrl.u64VmcbCleanBits &= ~(HMSVM_VMCB_CLEAN_INTERCEPTS | HMSVM_VMCB_CLEAN_TPR);
2550
2551 Log4(("Setting VINTR intercept\n"));
2552 }
2553}
2554
2555
2556#if 0
2557/**
2558 * Clears the virtual interrupt intercept control in the VMCB as
2559 * we are figured the guest is unable process any interrupts
2560 * at this point of time.
2561 *
2562 * @param pVmcb Pointer to the VM control block.
2563 */
2564DECLINLINE(void) hmR0SvmClearVirtIntrIntercept(PSVMVMCB pVmcb)
2565{
2566 if (pVmcb->ctrl.u64InterceptCtrl & SVM_CTRL_INTERCEPT_VINTR)
2567 {
2568 pVmcb->ctrl.u64InterceptCtrl &= ~SVM_CTRL_INTERCEPT_VINTR;
2569 pVmcb->ctrl.u64VmcbCleanBits &= ~(HMSVM_VMCB_CLEAN_INTERCEPTS);
2570 Log4(("Clearing VINTR intercept\n"));
2571 }
2572}
2573#endif
2574
2575
2576/**
2577 * Sets the IRET intercept control in the VMCB which instructs AMD-V to cause a
2578 * \#VMEXIT as soon as a guest starts executing an IRET. This is used to unblock
2579 * virtual NMIs.
2580 *
2581 * @param pVmcb Pointer to the VM control block.
2582 */
2583DECLINLINE(void) hmR0SvmSetIretIntercept(PSVMVMCB pVmcb)
2584{
2585 if (!(pVmcb->ctrl.u64InterceptCtrl & SVM_CTRL_INTERCEPT_IRET))
2586 {
2587 pVmcb->ctrl.u64InterceptCtrl |= SVM_CTRL_INTERCEPT_IRET;
2588 pVmcb->ctrl.u64VmcbCleanBits &= ~(HMSVM_VMCB_CLEAN_INTERCEPTS);
2589
2590 Log4(("Setting IRET intercept\n"));
2591 }
2592}
2593
2594
2595/**
2596 * Clears the IRET intercept control in the VMCB.
2597 *
2598 * @param pVmcb Pointer to the VM control block.
2599 */
2600DECLINLINE(void) hmR0SvmClearIretIntercept(PSVMVMCB pVmcb)
2601{
2602 if (pVmcb->ctrl.u64InterceptCtrl & SVM_CTRL_INTERCEPT_IRET)
2603 {
2604 pVmcb->ctrl.u64InterceptCtrl &= ~SVM_CTRL_INTERCEPT_IRET;
2605 pVmcb->ctrl.u64VmcbCleanBits &= ~(HMSVM_VMCB_CLEAN_INTERCEPTS);
2606
2607 Log4(("Clearing IRET intercept\n"));
2608 }
2609}
2610
2611
2612/**
2613 * Evaluates the event to be delivered to the guest and sets it as the pending
2614 * event.
2615 *
2616 * @param pVCpu The cross context virtual CPU structure.
2617 * @param pCtx Pointer to the guest-CPU context.
2618 */
2619static void hmR0SvmEvaluatePendingEvent(PVMCPU pVCpu, PCPUMCTX pCtx)
2620{
2621 Assert(!pVCpu->hm.s.Event.fPending);
2622 Log4Func(("\n"));
2623
2624 bool const fIntShadow = RT_BOOL(hmR0SvmGetGuestIntrShadow(pVCpu, pCtx));
2625 bool const fBlockInt = !(pCtx->eflags.u32 & X86_EFL_IF);
2626 bool const fBlockNmi = RT_BOOL(VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_BLOCK_NMIS));
2627 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
2628
2629 if (VMCPU_FF_TEST_AND_CLEAR(pVCpu, VMCPU_FF_UPDATE_APIC))
2630 APICUpdatePendingInterrupts(pVCpu);
2631
2632 SVMEVENT Event;
2633 Event.u = 0;
2634 /** @todo SMI. SMIs take priority over NMIs. */
2635 if (VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INTERRUPT_NMI)) /* NMI. NMIs take priority over regular interrupts . */
2636 {
2637 if (fBlockNmi)
2638 hmR0SvmSetIretIntercept(pVmcb);
2639 else if (fIntShadow)
2640 hmR0SvmSetVirtIntrIntercept(pVmcb);
2641 else
2642 {
2643 Log4(("Pending NMI\n"));
2644
2645 Event.n.u1Valid = 1;
2646 Event.n.u8Vector = X86_XCPT_NMI;
2647 Event.n.u3Type = SVM_EVENT_NMI;
2648
2649 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
2650 hmR0SvmSetIretIntercept(pVmcb);
2651 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INTERRUPT_NMI);
2652 }
2653 }
2654 else if ( VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INTERRUPT_APIC | VMCPU_FF_INTERRUPT_PIC)
2655 && !pVCpu->hm.s.fSingleInstruction)
2656 {
2657 /*
2658 * Check if the guest can receive external interrupts (PIC/APIC). Once PDMGetInterrupt() returns
2659 * a valid interrupt we must- deliver the interrupt. We can no longer re-request it from the APIC.
2660 */
2661 if ( !fBlockInt
2662 && !fIntShadow)
2663 {
2664 uint8_t u8Interrupt;
2665 int rc = PDMGetInterrupt(pVCpu, &u8Interrupt);
2666 if (RT_SUCCESS(rc))
2667 {
2668 Log4(("Injecting external interrupt u8Interrupt=%#x\n", u8Interrupt));
2669
2670 Event.n.u1Valid = 1;
2671 Event.n.u8Vector = u8Interrupt;
2672 Event.n.u3Type = SVM_EVENT_EXTERNAL_IRQ;
2673
2674 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
2675 }
2676 else if (rc == VERR_APIC_INTR_MASKED_BY_TPR)
2677 {
2678 /*
2679 * AMD-V has no TPR thresholding feature. We just avoid posting the interrupt.
2680 * We just avoid delivering the TPR-masked interrupt here. TPR will be updated
2681 * always via hmR0SvmLoadGuestState() -> hmR0SvmLoadGuestApicState().
2682 */
2683 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchTprMaskedIrq);
2684 }
2685 else
2686 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchGuestIrq);
2687 }
2688 else
2689 hmR0SvmSetVirtIntrIntercept(pVmcb);
2690 }
2691}
2692
2693
2694/**
2695 * Injects any pending events into the guest if the guest is in a state to
2696 * receive them.
2697 *
2698 * @param pVCpu The cross context virtual CPU structure.
2699 * @param pCtx Pointer to the guest-CPU context.
2700 */
2701static void hmR0SvmInjectPendingEvent(PVMCPU pVCpu, PCPUMCTX pCtx)
2702{
2703 Assert(!TRPMHasTrap(pVCpu));
2704 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
2705
2706 bool const fIntShadow = RT_BOOL(hmR0SvmGetGuestIntrShadow(pVCpu, pCtx));
2707 bool const fBlockInt = !(pCtx->eflags.u32 & X86_EFL_IF);
2708 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
2709
2710 if (pVCpu->hm.s.Event.fPending) /* First, inject any pending HM events. */
2711 {
2712 SVMEVENT Event;
2713 Event.u = pVCpu->hm.s.Event.u64IntInfo;
2714 Assert(Event.n.u1Valid);
2715#ifdef VBOX_STRICT
2716 if (Event.n.u3Type == SVM_EVENT_EXTERNAL_IRQ)
2717 {
2718 Assert(!fBlockInt);
2719 Assert(!fIntShadow);
2720 }
2721 else if (Event.n.u3Type == SVM_EVENT_NMI)
2722 Assert(!fIntShadow);
2723#endif
2724
2725 Log4(("Injecting pending HM event.\n"));
2726 hmR0SvmInjectEventVmcb(pVCpu, pVmcb, pCtx, &Event);
2727 pVCpu->hm.s.Event.fPending = false;
2728
2729#ifdef VBOX_WITH_STATISTICS
2730 if (Event.n.u3Type == SVM_EVENT_EXTERNAL_IRQ)
2731 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectInterrupt);
2732 else
2733 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectXcpt);
2734#endif
2735 }
2736
2737 /* Update the guest interrupt shadow in the VMCB. */
2738 pVmcb->ctrl.u64IntShadow = !!fIntShadow;
2739 NOREF(fBlockInt);
2740}
2741
2742
2743/**
2744 * Reports world-switch error and dumps some useful debug info.
2745 *
2746 * @param pVM The cross context VM structure.
2747 * @param pVCpu The cross context virtual CPU structure.
2748 * @param rcVMRun The return code from VMRUN (or
2749 * VERR_SVM_INVALID_GUEST_STATE for invalid
2750 * guest-state).
2751 * @param pCtx Pointer to the guest-CPU context.
2752 */
2753static void hmR0SvmReportWorldSwitchError(PVM pVM, PVMCPU pVCpu, int rcVMRun, PCPUMCTX pCtx)
2754{
2755 NOREF(pCtx);
2756 HMSVM_ASSERT_PREEMPT_SAFE();
2757 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
2758
2759 if (rcVMRun == VERR_SVM_INVALID_GUEST_STATE)
2760 {
2761 hmDumpRegs(pVM, pVCpu, pCtx); NOREF(pVM);
2762#ifdef VBOX_STRICT
2763 Log4(("ctrl.u64VmcbCleanBits %#RX64\n", pVmcb->ctrl.u64VmcbCleanBits));
2764 Log4(("ctrl.u16InterceptRdCRx %#x\n", pVmcb->ctrl.u16InterceptRdCRx));
2765 Log4(("ctrl.u16InterceptWrCRx %#x\n", pVmcb->ctrl.u16InterceptWrCRx));
2766 Log4(("ctrl.u16InterceptRdDRx %#x\n", pVmcb->ctrl.u16InterceptRdDRx));
2767 Log4(("ctrl.u16InterceptWrDRx %#x\n", pVmcb->ctrl.u16InterceptWrDRx));
2768 Log4(("ctrl.u32InterceptException %#x\n", pVmcb->ctrl.u32InterceptException));
2769 Log4(("ctrl.u64InterceptCtrl %#RX64\n", pVmcb->ctrl.u64InterceptCtrl));
2770 Log4(("ctrl.u64IOPMPhysAddr %#RX64\n", pVmcb->ctrl.u64IOPMPhysAddr));
2771 Log4(("ctrl.u64MSRPMPhysAddr %#RX64\n", pVmcb->ctrl.u64MSRPMPhysAddr));
2772 Log4(("ctrl.u64TSCOffset %#RX64\n", pVmcb->ctrl.u64TSCOffset));
2773
2774 Log4(("ctrl.TLBCtrl.u32ASID %#x\n", pVmcb->ctrl.TLBCtrl.n.u32ASID));
2775 Log4(("ctrl.TLBCtrl.u8TLBFlush %#x\n", pVmcb->ctrl.TLBCtrl.n.u8TLBFlush));
2776 Log4(("ctrl.TLBCtrl.u24Reserved %#x\n", pVmcb->ctrl.TLBCtrl.n.u24Reserved));
2777
2778 Log4(("ctrl.IntCtrl.u8VTPR %#x\n", pVmcb->ctrl.IntCtrl.n.u8VTPR));
2779 Log4(("ctrl.IntCtrl.u1VIrqValid %#x\n", pVmcb->ctrl.IntCtrl.n.u1VIrqValid));
2780 Log4(("ctrl.IntCtrl.u7Reserved %#x\n", pVmcb->ctrl.IntCtrl.n.u7Reserved));
2781 Log4(("ctrl.IntCtrl.u4VIrqPriority %#x\n", pVmcb->ctrl.IntCtrl.n.u4VIrqPriority));
2782 Log4(("ctrl.IntCtrl.u1IgnoreTPR %#x\n", pVmcb->ctrl.IntCtrl.n.u1IgnoreTPR));
2783 Log4(("ctrl.IntCtrl.u3Reserved %#x\n", pVmcb->ctrl.IntCtrl.n.u3Reserved));
2784 Log4(("ctrl.IntCtrl.u1VIrqMasking %#x\n", pVmcb->ctrl.IntCtrl.n.u1VIrqMasking));
2785 Log4(("ctrl.IntCtrl.u6Reserved %#x\n", pVmcb->ctrl.IntCtrl.n.u6Reserved));
2786 Log4(("ctrl.IntCtrl.u8VIrqVector %#x\n", pVmcb->ctrl.IntCtrl.n.u8VIrqVector));
2787 Log4(("ctrl.IntCtrl.u24Reserved %#x\n", pVmcb->ctrl.IntCtrl.n.u24Reserved));
2788
2789 Log4(("ctrl.u64IntShadow %#RX64\n", pVmcb->ctrl.u64IntShadow));
2790 Log4(("ctrl.u64ExitCode %#RX64\n", pVmcb->ctrl.u64ExitCode));
2791 Log4(("ctrl.u64ExitInfo1 %#RX64\n", pVmcb->ctrl.u64ExitInfo1));
2792 Log4(("ctrl.u64ExitInfo2 %#RX64\n", pVmcb->ctrl.u64ExitInfo2));
2793 Log4(("ctrl.ExitIntInfo.u8Vector %#x\n", pVmcb->ctrl.ExitIntInfo.n.u8Vector));
2794 Log4(("ctrl.ExitIntInfo.u3Type %#x\n", pVmcb->ctrl.ExitIntInfo.n.u3Type));
2795 Log4(("ctrl.ExitIntInfo.u1ErrorCodeValid %#x\n", pVmcb->ctrl.ExitIntInfo.n.u1ErrorCodeValid));
2796 Log4(("ctrl.ExitIntInfo.u19Reserved %#x\n", pVmcb->ctrl.ExitIntInfo.n.u19Reserved));
2797 Log4(("ctrl.ExitIntInfo.u1Valid %#x\n", pVmcb->ctrl.ExitIntInfo.n.u1Valid));
2798 Log4(("ctrl.ExitIntInfo.u32ErrorCode %#x\n", pVmcb->ctrl.ExitIntInfo.n.u32ErrorCode));
2799 Log4(("ctrl.NestedPaging %#RX64\n", pVmcb->ctrl.NestedPaging.u));
2800 Log4(("ctrl.EventInject.u8Vector %#x\n", pVmcb->ctrl.EventInject.n.u8Vector));
2801 Log4(("ctrl.EventInject.u3Type %#x\n", pVmcb->ctrl.EventInject.n.u3Type));
2802 Log4(("ctrl.EventInject.u1ErrorCodeValid %#x\n", pVmcb->ctrl.EventInject.n.u1ErrorCodeValid));
2803 Log4(("ctrl.EventInject.u19Reserved %#x\n", pVmcb->ctrl.EventInject.n.u19Reserved));
2804 Log4(("ctrl.EventInject.u1Valid %#x\n", pVmcb->ctrl.EventInject.n.u1Valid));
2805 Log4(("ctrl.EventInject.u32ErrorCode %#x\n", pVmcb->ctrl.EventInject.n.u32ErrorCode));
2806
2807 Log4(("ctrl.u64NestedPagingCR3 %#RX64\n", pVmcb->ctrl.u64NestedPagingCR3));
2808 Log4(("ctrl.u64LBRVirt %#RX64\n", pVmcb->ctrl.u64LBRVirt));
2809
2810 Log4(("guest.CS.u16Sel %RTsel\n", pVmcb->guest.CS.u16Sel));
2811 Log4(("guest.CS.u16Attr %#x\n", pVmcb->guest.CS.u16Attr));
2812 Log4(("guest.CS.u32Limit %#RX32\n", pVmcb->guest.CS.u32Limit));
2813 Log4(("guest.CS.u64Base %#RX64\n", pVmcb->guest.CS.u64Base));
2814 Log4(("guest.DS.u16Sel %#RTsel\n", pVmcb->guest.DS.u16Sel));
2815 Log4(("guest.DS.u16Attr %#x\n", pVmcb->guest.DS.u16Attr));
2816 Log4(("guest.DS.u32Limit %#RX32\n", pVmcb->guest.DS.u32Limit));
2817 Log4(("guest.DS.u64Base %#RX64\n", pVmcb->guest.DS.u64Base));
2818 Log4(("guest.ES.u16Sel %RTsel\n", pVmcb->guest.ES.u16Sel));
2819 Log4(("guest.ES.u16Attr %#x\n", pVmcb->guest.ES.u16Attr));
2820 Log4(("guest.ES.u32Limit %#RX32\n", pVmcb->guest.ES.u32Limit));
2821 Log4(("guest.ES.u64Base %#RX64\n", pVmcb->guest.ES.u64Base));
2822 Log4(("guest.FS.u16Sel %RTsel\n", pVmcb->guest.FS.u16Sel));
2823 Log4(("guest.FS.u16Attr %#x\n", pVmcb->guest.FS.u16Attr));
2824 Log4(("guest.FS.u32Limit %#RX32\n", pVmcb->guest.FS.u32Limit));
2825 Log4(("guest.FS.u64Base %#RX64\n", pVmcb->guest.FS.u64Base));
2826 Log4(("guest.GS.u16Sel %RTsel\n", pVmcb->guest.GS.u16Sel));
2827 Log4(("guest.GS.u16Attr %#x\n", pVmcb->guest.GS.u16Attr));
2828 Log4(("guest.GS.u32Limit %#RX32\n", pVmcb->guest.GS.u32Limit));
2829 Log4(("guest.GS.u64Base %#RX64\n", pVmcb->guest.GS.u64Base));
2830
2831 Log4(("guest.GDTR.u32Limit %#RX32\n", pVmcb->guest.GDTR.u32Limit));
2832 Log4(("guest.GDTR.u64Base %#RX64\n", pVmcb->guest.GDTR.u64Base));
2833
2834 Log4(("guest.LDTR.u16Sel %RTsel\n", pVmcb->guest.LDTR.u16Sel));
2835 Log4(("guest.LDTR.u16Attr %#x\n", pVmcb->guest.LDTR.u16Attr));
2836 Log4(("guest.LDTR.u32Limit %#RX32\n", pVmcb->guest.LDTR.u32Limit));
2837 Log4(("guest.LDTR.u64Base %#RX64\n", pVmcb->guest.LDTR.u64Base));
2838
2839 Log4(("guest.IDTR.u32Limit %#RX32\n", pVmcb->guest.IDTR.u32Limit));
2840 Log4(("guest.IDTR.u64Base %#RX64\n", pVmcb->guest.IDTR.u64Base));
2841
2842 Log4(("guest.TR.u16Sel %RTsel\n", pVmcb->guest.TR.u16Sel));
2843 Log4(("guest.TR.u16Attr %#x\n", pVmcb->guest.TR.u16Attr));
2844 Log4(("guest.TR.u32Limit %#RX32\n", pVmcb->guest.TR.u32Limit));
2845 Log4(("guest.TR.u64Base %#RX64\n", pVmcb->guest.TR.u64Base));
2846
2847 Log4(("guest.u8CPL %#x\n", pVmcb->guest.u8CPL));
2848 Log4(("guest.u64CR0 %#RX64\n", pVmcb->guest.u64CR0));
2849 Log4(("guest.u64CR2 %#RX64\n", pVmcb->guest.u64CR2));
2850 Log4(("guest.u64CR3 %#RX64\n", pVmcb->guest.u64CR3));
2851 Log4(("guest.u64CR4 %#RX64\n", pVmcb->guest.u64CR4));
2852 Log4(("guest.u64DR6 %#RX64\n", pVmcb->guest.u64DR6));
2853 Log4(("guest.u64DR7 %#RX64\n", pVmcb->guest.u64DR7));
2854
2855 Log4(("guest.u64RIP %#RX64\n", pVmcb->guest.u64RIP));
2856 Log4(("guest.u64RSP %#RX64\n", pVmcb->guest.u64RSP));
2857 Log4(("guest.u64RAX %#RX64\n", pVmcb->guest.u64RAX));
2858 Log4(("guest.u64RFlags %#RX64\n", pVmcb->guest.u64RFlags));
2859
2860 Log4(("guest.u64SysEnterCS %#RX64\n", pVmcb->guest.u64SysEnterCS));
2861 Log4(("guest.u64SysEnterEIP %#RX64\n", pVmcb->guest.u64SysEnterEIP));
2862 Log4(("guest.u64SysEnterESP %#RX64\n", pVmcb->guest.u64SysEnterESP));
2863
2864 Log4(("guest.u64EFER %#RX64\n", pVmcb->guest.u64EFER));
2865 Log4(("guest.u64STAR %#RX64\n", pVmcb->guest.u64STAR));
2866 Log4(("guest.u64LSTAR %#RX64\n", pVmcb->guest.u64LSTAR));
2867 Log4(("guest.u64CSTAR %#RX64\n", pVmcb->guest.u64CSTAR));
2868 Log4(("guest.u64SFMASK %#RX64\n", pVmcb->guest.u64SFMASK));
2869 Log4(("guest.u64KernelGSBase %#RX64\n", pVmcb->guest.u64KernelGSBase));
2870 Log4(("guest.u64GPAT %#RX64\n", pVmcb->guest.u64GPAT));
2871 Log4(("guest.u64DBGCTL %#RX64\n", pVmcb->guest.u64DBGCTL));
2872 Log4(("guest.u64BR_FROM %#RX64\n", pVmcb->guest.u64BR_FROM));
2873 Log4(("guest.u64BR_TO %#RX64\n", pVmcb->guest.u64BR_TO));
2874 Log4(("guest.u64LASTEXCPFROM %#RX64\n", pVmcb->guest.u64LASTEXCPFROM));
2875 Log4(("guest.u64LASTEXCPTO %#RX64\n", pVmcb->guest.u64LASTEXCPTO));
2876#endif /* VBOX_STRICT */
2877 }
2878 else
2879 Log4(("hmR0SvmReportWorldSwitchError: rcVMRun=%d\n", rcVMRun));
2880
2881 NOREF(pVmcb);
2882}
2883
2884
2885/**
2886 * Check per-VM and per-VCPU force flag actions that require us to go back to
2887 * ring-3 for one reason or another.
2888 *
2889 * @returns VBox status code (information status code included).
2890 * @retval VINF_SUCCESS if we don't have any actions that require going back to
2891 * ring-3.
2892 * @retval VINF_PGM_SYNC_CR3 if we have pending PGM CR3 sync.
2893 * @retval VINF_EM_PENDING_REQUEST if we have pending requests (like hardware
2894 * interrupts)
2895 * @retval VINF_PGM_POOL_FLUSH_PENDING if PGM is doing a pool flush and requires
2896 * all EMTs to be in ring-3.
2897 * @retval VINF_EM_RAW_TO_R3 if there is pending DMA requests.
2898 * @retval VINF_EM_NO_MEMORY PGM is out of memory, we need to return
2899 * to the EM loop.
2900 *
2901 * @param pVM The cross context VM structure.
2902 * @param pVCpu The cross context virtual CPU structure.
2903 * @param pCtx Pointer to the guest-CPU context.
2904 */
2905static int hmR0SvmCheckForceFlags(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
2906{
2907 Assert(VMMRZCallRing3IsEnabled(pVCpu));
2908
2909 /* On AMD-V we don't need to update CR3, PAE PDPES lazily. See hmR0SvmSaveGuestState(). */
2910 Assert(!VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_UPDATE_CR3));
2911 Assert(!VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_UPDATE_PAE_PDPES));
2912
2913 if ( VM_FF_IS_PENDING(pVM, !pVCpu->hm.s.fSingleInstruction
2914 ? VM_FF_HP_R0_PRE_HM_MASK : VM_FF_HP_R0_PRE_HM_STEP_MASK)
2915 || VMCPU_FF_IS_PENDING(pVCpu, !pVCpu->hm.s.fSingleInstruction
2916 ? VMCPU_FF_HP_R0_PRE_HM_MASK : VMCPU_FF_HP_R0_PRE_HM_STEP_MASK) )
2917 {
2918 /* Pending PGM C3 sync. */
2919 if (VMCPU_FF_IS_PENDING(pVCpu,VMCPU_FF_PGM_SYNC_CR3 | VMCPU_FF_PGM_SYNC_CR3_NON_GLOBAL))
2920 {
2921 int rc = PGMSyncCR3(pVCpu, pCtx->cr0, pCtx->cr3, pCtx->cr4, VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_PGM_SYNC_CR3));
2922 if (rc != VINF_SUCCESS)
2923 {
2924 Log4(("hmR0SvmCheckForceFlags: PGMSyncCR3 forcing us back to ring-3. rc=%d\n", rc));
2925 return rc;
2926 }
2927 }
2928
2929 /* Pending HM-to-R3 operations (critsects, timers, EMT rendezvous etc.) */
2930 /* -XXX- what was that about single stepping? */
2931 if ( VM_FF_IS_PENDING(pVM, VM_FF_HM_TO_R3_MASK)
2932 || VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_TO_R3_MASK))
2933 {
2934 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchHmToR3FF);
2935 int rc = RT_UNLIKELY(VM_FF_IS_PENDING(pVM, VM_FF_PGM_NO_MEMORY)) ? VINF_EM_NO_MEMORY : VINF_EM_RAW_TO_R3;
2936 Log4(("hmR0SvmCheckForceFlags: HM_TO_R3 forcing us back to ring-3. rc=%d\n", rc));
2937 return rc;
2938 }
2939
2940 /* Pending VM request packets, such as hardware interrupts. */
2941 if ( VM_FF_IS_PENDING(pVM, VM_FF_REQUEST)
2942 || VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_REQUEST))
2943 {
2944 Log4(("hmR0SvmCheckForceFlags: Pending VM request forcing us back to ring-3\n"));
2945 return VINF_EM_PENDING_REQUEST;
2946 }
2947
2948 /* Pending PGM pool flushes. */
2949 if (VM_FF_IS_PENDING(pVM, VM_FF_PGM_POOL_FLUSH_PENDING))
2950 {
2951 Log4(("hmR0SvmCheckForceFlags: PGM pool flush pending forcing us back to ring-3\n"));
2952 return VINF_PGM_POOL_FLUSH_PENDING;
2953 }
2954
2955 /* Pending DMA requests. */
2956 if (VM_FF_IS_PENDING(pVM, VM_FF_PDM_DMA))
2957 {
2958 Log4(("hmR0SvmCheckForceFlags: Pending DMA request forcing us back to ring-3\n"));
2959 return VINF_EM_RAW_TO_R3;
2960 }
2961 }
2962
2963 return VINF_SUCCESS;
2964}
2965
2966
2967/**
2968 * Does the preparations before executing guest code in AMD-V.
2969 *
2970 * This may cause longjmps to ring-3 and may even result in rescheduling to the
2971 * recompiler. We must be cautious what we do here regarding committing
2972 * guest-state information into the VMCB assuming we assuredly execute the guest
2973 * in AMD-V. If we fall back to the recompiler after updating the VMCB and
2974 * clearing the common-state (TRPM/forceflags), we must undo those changes so
2975 * that the recompiler can (and should) use them when it resumes guest
2976 * execution. Otherwise such operations must be done when we can no longer
2977 * exit to ring-3.
2978 *
2979 * @returns VBox status code (informational status codes included).
2980 * @retval VINF_SUCCESS if we can proceed with running the guest.
2981 * @retval VINF_* scheduling changes, we have to go back to ring-3.
2982 *
2983 * @param pVM The cross context VM structure.
2984 * @param pVCpu The cross context virtual CPU structure.
2985 * @param pCtx Pointer to the guest-CPU context.
2986 * @param pSvmTransient Pointer to the SVM transient structure.
2987 */
2988static int hmR0SvmPreRunGuest(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
2989{
2990 HMSVM_ASSERT_PREEMPT_SAFE();
2991
2992 /* Check force flag actions that might require us to go back to ring-3. */
2993 int rc = hmR0SvmCheckForceFlags(pVM, pVCpu, pCtx);
2994 if (rc != VINF_SUCCESS)
2995 return rc;
2996
2997 if (TRPMHasTrap(pVCpu))
2998 hmR0SvmTrpmTrapToPendingEvent(pVCpu);
2999 else if (!pVCpu->hm.s.Event.fPending)
3000 hmR0SvmEvaluatePendingEvent(pVCpu, pCtx);
3001
3002 /*
3003 * On the oldest AMD-V systems, we may not get enough information to reinject an NMI.
3004 * Just do it in software, see @bugref{8411}.
3005 * NB: If we could continue a task switch exit we wouldn't need to do this.
3006 */
3007 if (RT_UNLIKELY(pVCpu->hm.s.Event.fPending && (((pVCpu->hm.s.Event.u64IntInfo >> 8) & 7) == SVM_EVENT_NMI)))
3008 if (RT_UNLIKELY(!pVM->hm.s.svm.u32Features))
3009 return VINF_EM_RAW_INJECT_TRPM_EVENT;
3010
3011#ifdef HMSVM_SYNC_FULL_GUEST_STATE
3012 HMCPU_CF_SET(pVCpu, HM_CHANGED_ALL_GUEST);
3013#endif
3014
3015 /* Load the guest bits that are not shared with the host in any way since we can longjmp or get preempted. */
3016 rc = hmR0SvmLoadGuestState(pVM, pVCpu, pCtx);
3017 AssertRCReturn(rc, rc);
3018 STAM_COUNTER_INC(&pVCpu->hm.s.StatLoadFull);
3019
3020 /*
3021 * If we're not intercepting TPR changes in the guest, save the guest TPR before the world-switch
3022 * so we can update it on the way back if the guest changed the TPR.
3023 */
3024 if (pVCpu->hm.s.svm.fSyncVTpr)
3025 {
3026 if (pVM->hm.s.fTPRPatchingActive)
3027 pSvmTransient->u8GuestTpr = pCtx->msrLSTAR;
3028 else
3029 {
3030 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
3031 pSvmTransient->u8GuestTpr = pVmcb->ctrl.IntCtrl.n.u8VTPR;
3032 }
3033 }
3034
3035 /*
3036 * No longjmps to ring-3 from this point on!!!
3037 * Asserts() will still longjmp to ring-3 (but won't return), which is intentional, better than a kernel panic.
3038 * This also disables flushing of the R0-logger instance (if any).
3039 */
3040 VMMRZCallRing3Disable(pVCpu);
3041
3042 /*
3043 * We disable interrupts so that we don't miss any interrupts that would flag preemption (IPI/timers etc.)
3044 * when thread-context hooks aren't used and we've been running with preemption disabled for a while.
3045 *
3046 * We need to check for force-flags that could've possible been altered since we last checked them (e.g.
3047 * by PDMGetInterrupt() leaving the PDM critical section, see @bugref{6398}).
3048 *
3049 * We also check a couple of other force-flags as a last opportunity to get the EMT back to ring-3 before
3050 * executing guest code.
3051 */
3052 pSvmTransient->fEFlags = ASMIntDisableFlags();
3053 if ( VM_FF_IS_PENDING(pVM, VM_FF_EMT_RENDEZVOUS | VM_FF_TM_VIRTUAL_SYNC)
3054 || VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_TO_R3_MASK))
3055 {
3056 ASMSetFlags(pSvmTransient->fEFlags);
3057 VMMRZCallRing3Enable(pVCpu);
3058 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchHmToR3FF);
3059 return VINF_EM_RAW_TO_R3;
3060 }
3061 if (RTThreadPreemptIsPending(NIL_RTTHREAD))
3062 {
3063 ASMSetFlags(pSvmTransient->fEFlags);
3064 VMMRZCallRing3Enable(pVCpu);
3065 STAM_COUNTER_INC(&pVCpu->hm.s.StatPendingHostIrq);
3066 return VINF_EM_RAW_INTERRUPT;
3067 }
3068
3069 /*
3070 * If we are injecting an NMI, we must set VMCPU_FF_BLOCK_NMIS only when we are going to execute
3071 * guest code for certain (no exits to ring-3). Otherwise, we could re-read the flag on re-entry into
3072 * AMD-V and conclude that NMI inhibition is active when we have not even delivered the NMI.
3073 *
3074 * With VT-x, this is handled by the Guest interruptibility information VMCS field which will set the
3075 * VMCS field after actually delivering the NMI which we read on VM-exit to determine the state.
3076 */
3077 if (pVCpu->hm.s.Event.fPending)
3078 {
3079 SVMEVENT Event;
3080 Event.u = pVCpu->hm.s.Event.u64IntInfo;
3081 if ( Event.n.u1Valid
3082 && Event.n.u3Type == SVM_EVENT_NMI
3083 && Event.n.u8Vector == X86_XCPT_NMI
3084 && !VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_BLOCK_NMIS))
3085 {
3086 VMCPU_FF_SET(pVCpu, VMCPU_FF_BLOCK_NMIS);
3087 }
3088 }
3089
3090 return VINF_SUCCESS;
3091}
3092
3093
3094/**
3095 * Prepares to run guest code in AMD-V and we've committed to doing so. This
3096 * means there is no backing out to ring-3 or anywhere else at this
3097 * point.
3098 *
3099 * @param pVM The cross context VM structure.
3100 * @param pVCpu The cross context virtual CPU structure.
3101 * @param pCtx Pointer to the guest-CPU context.
3102 * @param pSvmTransient Pointer to the SVM transient structure.
3103 *
3104 * @remarks Called with preemption disabled.
3105 * @remarks No-long-jump zone!!!
3106 */
3107static void hmR0SvmPreRunGuestCommitted(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3108{
3109 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
3110 Assert(VMMR0IsLogFlushDisabled(pVCpu));
3111 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
3112
3113 VMCPU_ASSERT_STATE(pVCpu, VMCPUSTATE_STARTED_HM);
3114 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_EXEC); /* Indicate the start of guest execution. */
3115
3116 hmR0SvmInjectPendingEvent(pVCpu, pCtx);
3117
3118 if ( pVCpu->hm.s.fPreloadGuestFpu
3119 && !CPUMIsGuestFPUStateActive(pVCpu))
3120 {
3121 CPUMR0LoadGuestFPU(pVM, pVCpu); /* (Ignore rc, no need to set HM_CHANGED_HOST_CONTEXT for SVM.) */
3122 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR0);
3123 }
3124
3125 /* Load the state shared between host and guest (FPU, debug). */
3126 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
3127 if (HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_HOST_GUEST_SHARED_STATE))
3128 hmR0SvmLoadSharedState(pVCpu, pVmcb, pCtx);
3129 HMCPU_CF_CLEAR(pVCpu, HM_CHANGED_HOST_CONTEXT); /* Preemption might set this, nothing to do on AMD-V. */
3130 AssertMsg(!HMCPU_CF_VALUE(pVCpu), ("fContextUseFlags=%#RX32\n", HMCPU_CF_VALUE(pVCpu)));
3131
3132 /* Setup TSC offsetting. */
3133 RTCPUID idCurrentCpu = hmR0GetCurrentCpu()->idCpu;
3134 if ( pSvmTransient->fUpdateTscOffsetting
3135 || idCurrentCpu != pVCpu->hm.s.idLastCpu)
3136 {
3137 hmR0SvmUpdateTscOffsetting(pVM, pVCpu);
3138 pSvmTransient->fUpdateTscOffsetting = false;
3139 }
3140
3141 /* If we've migrating CPUs, mark the VMCB Clean bits as dirty. */
3142 if (idCurrentCpu != pVCpu->hm.s.idLastCpu)
3143 pVmcb->ctrl.u64VmcbCleanBits = 0;
3144
3145 /* Store status of the shared guest-host state at the time of VMRUN. */
3146#if HC_ARCH_BITS == 32 && defined(VBOX_WITH_64_BITS_GUESTS)
3147 if (CPUMIsGuestInLongModeEx(pCtx))
3148 {
3149 pSvmTransient->fWasGuestDebugStateActive = CPUMIsGuestDebugStateActivePending(pVCpu);
3150 pSvmTransient->fWasHyperDebugStateActive = CPUMIsHyperDebugStateActivePending(pVCpu);
3151 }
3152 else
3153#endif
3154 {
3155 pSvmTransient->fWasGuestDebugStateActive = CPUMIsGuestDebugStateActive(pVCpu);
3156 pSvmTransient->fWasHyperDebugStateActive = CPUMIsHyperDebugStateActive(pVCpu);
3157 }
3158 pSvmTransient->fWasGuestFPUStateActive = CPUMIsGuestFPUStateActive(pVCpu);
3159
3160 /* Flush the appropriate tagged-TLB entries. */
3161 ASMAtomicWriteBool(&pVCpu->hm.s.fCheckedTLBFlush, true); /* Used for TLB flushing, set this across the world switch. */
3162 hmR0SvmFlushTaggedTlb(pVCpu);
3163 Assert(hmR0GetCurrentCpu()->idCpu == pVCpu->hm.s.idLastCpu);
3164
3165 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatEntry, &pVCpu->hm.s.StatInGC, x);
3166
3167 TMNotifyStartOfExecution(pVCpu); /* Finally, notify TM to resume its clocks as we're about
3168 to start executing. */
3169
3170 /*
3171 * Save the current Host TSC_AUX and write the guest TSC_AUX to the host, so that
3172 * RDTSCPs (that don't cause exits) reads the guest MSR. See @bugref{3324}.
3173 *
3174 * This should be done -after- any RDTSCPs for obtaining the host timestamp (TM, STAM etc).
3175 */
3176 if ( (pVM->hm.s.cpuid.u32AMDFeatureEDX & X86_CPUID_EXT_FEATURE_EDX_RDTSCP)
3177 && !(pVmcb->ctrl.u64InterceptCtrl & SVM_CTRL_INTERCEPT_RDTSCP))
3178 {
3179 hmR0SvmSetMsrPermission(pVCpu, MSR_K8_TSC_AUX, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
3180 pVCpu->hm.s.u64HostTscAux = ASMRdMsr(MSR_K8_TSC_AUX);
3181 uint64_t u64GuestTscAux = CPUMR0GetGuestTscAux(pVCpu);
3182 if (u64GuestTscAux != pVCpu->hm.s.u64HostTscAux)
3183 ASMWrMsr(MSR_K8_TSC_AUX, u64GuestTscAux);
3184 pSvmTransient->fRestoreTscAuxMsr = true;
3185 }
3186 else
3187 {
3188 hmR0SvmSetMsrPermission(pVCpu, MSR_K8_TSC_AUX, SVMMSREXIT_INTERCEPT_READ, SVMMSREXIT_INTERCEPT_WRITE);
3189 pSvmTransient->fRestoreTscAuxMsr = false;
3190 }
3191
3192 /* If VMCB Clean bits isn't supported by the CPU, simply mark all state-bits as dirty, indicating (re)load-from-VMCB. */
3193 if (!(pVM->hm.s.svm.u32Features & AMD_CPUID_SVM_FEATURE_EDX_VMCB_CLEAN))
3194 pVmcb->ctrl.u64VmcbCleanBits = 0;
3195}
3196
3197
3198/**
3199 * Wrapper for running the guest code in AMD-V.
3200 *
3201 * @returns VBox strict status code.
3202 * @param pVM The cross context VM structure.
3203 * @param pVCpu The cross context virtual CPU structure.
3204 * @param pCtx Pointer to the guest-CPU context.
3205 *
3206 * @remarks No-long-jump zone!!!
3207 */
3208DECLINLINE(int) hmR0SvmRunGuest(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
3209{
3210 /*
3211 * 64-bit Windows uses XMM registers in the kernel as the Microsoft compiler expresses floating-point operations
3212 * using SSE instructions. Some XMM registers (XMM6-XMM15) are callee-saved and thus the need for this XMM wrapper.
3213 * Refer MSDN docs. "Configuring Programs for 64-bit / x64 Software Conventions / Register Usage" for details.
3214 */
3215#ifdef VBOX_WITH_KERNEL_USING_XMM
3216 return hmR0SVMRunWrapXMM(pVCpu->hm.s.svm.HCPhysVmcbHost, pVCpu->hm.s.svm.HCPhysVmcb, pCtx, pVM, pVCpu,
3217 pVCpu->hm.s.svm.pfnVMRun);
3218#else
3219 return pVCpu->hm.s.svm.pfnVMRun(pVCpu->hm.s.svm.HCPhysVmcbHost, pVCpu->hm.s.svm.HCPhysVmcb, pCtx, pVM, pVCpu);
3220#endif
3221}
3222
3223
3224/**
3225 * Performs some essential restoration of state after running guest code in
3226 * AMD-V.
3227 *
3228 * @param pVM The cross context VM structure.
3229 * @param pVCpu The cross context virtual CPU structure.
3230 * @param pMixedCtx Pointer to the guest-CPU context. The data maybe
3231 * out-of-sync. Make sure to update the required fields
3232 * before using them.
3233 * @param pSvmTransient Pointer to the SVM transient structure.
3234 * @param rcVMRun Return code of VMRUN.
3235 *
3236 * @remarks Called with interrupts disabled.
3237 * @remarks No-long-jump zone!!! This function will however re-enable longjmps
3238 * unconditionally when it is safe to do so.
3239 */
3240static void hmR0SvmPostRunGuest(PVM pVM, PVMCPU pVCpu, PCPUMCTX pMixedCtx, PSVMTRANSIENT pSvmTransient, int rcVMRun)
3241{
3242 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
3243
3244 ASMAtomicWriteBool(&pVCpu->hm.s.fCheckedTLBFlush, false); /* See HMInvalidatePageOnAllVCpus(): used for TLB flushing. */
3245 ASMAtomicIncU32(&pVCpu->hm.s.cWorldSwitchExits); /* Initialized in vmR3CreateUVM(): used for EMT poking. */
3246
3247 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
3248 pVmcb->ctrl.u64VmcbCleanBits = HMSVM_VMCB_CLEAN_ALL; /* Mark the VMCB-state cache as unmodified by VMM. */
3249
3250 /* TSC read must be done early for maximum accuracy. */
3251 if (!(pVmcb->ctrl.u64InterceptCtrl & SVM_CTRL_INTERCEPT_RDTSC))
3252 TMCpuTickSetLastSeen(pVCpu, ASMReadTSC() + pVmcb->ctrl.u64TSCOffset);
3253
3254 if (pSvmTransient->fRestoreTscAuxMsr)
3255 {
3256 uint64_t u64GuestTscAuxMsr = ASMRdMsr(MSR_K8_TSC_AUX);
3257 CPUMR0SetGuestTscAux(pVCpu, u64GuestTscAuxMsr);
3258 if (u64GuestTscAuxMsr != pVCpu->hm.s.u64HostTscAux)
3259 ASMWrMsr(MSR_K8_TSC_AUX, pVCpu->hm.s.u64HostTscAux);
3260 }
3261
3262 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatInGC, &pVCpu->hm.s.StatExit1, x);
3263 TMNotifyEndOfExecution(pVCpu); /* Notify TM that the guest is no longer running. */
3264 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_HM);
3265
3266 Assert(!(ASMGetFlags() & X86_EFL_IF));
3267 ASMSetFlags(pSvmTransient->fEFlags); /* Enable interrupts. */
3268 VMMRZCallRing3Enable(pVCpu); /* It is now safe to do longjmps to ring-3!!! */
3269
3270 /* If VMRUN failed, we can bail out early. This does -not- cover SVM_EXIT_INVALID. */
3271 if (RT_UNLIKELY(rcVMRun != VINF_SUCCESS))
3272 {
3273 Log4(("VMRUN failure: rcVMRun=%Rrc\n", rcVMRun));
3274 return;
3275 }
3276
3277 pSvmTransient->u64ExitCode = pVmcb->ctrl.u64ExitCode; /* Save the #VMEXIT reason. */
3278 HMCPU_EXIT_HISTORY_ADD(pVCpu, pVmcb->ctrl.u64ExitCode); /* Update the #VMEXIT history array. */
3279 pSvmTransient->fVectoringDoublePF = false; /* Vectoring double page-fault needs to be determined later. */
3280 pSvmTransient->fVectoringPF = false; /* Vectoring page-fault needs to be determined later. */
3281
3282 hmR0SvmSaveGuestState(pVCpu, pMixedCtx); /* Save the guest state from the VMCB to the guest-CPU context. */
3283
3284 if (RT_LIKELY(pSvmTransient->u64ExitCode != (uint64_t)SVM_EXIT_INVALID))
3285 {
3286 if (pVCpu->hm.s.svm.fSyncVTpr)
3287 {
3288 /* TPR patching (for 32-bit guests) uses LSTAR MSR for holding the TPR value, otherwise uses the VTPR. */
3289 if ( pVM->hm.s.fTPRPatchingActive
3290 && (pMixedCtx->msrLSTAR & 0xff) != pSvmTransient->u8GuestTpr)
3291 {
3292 int rc = APICSetTpr(pVCpu, pMixedCtx->msrLSTAR & 0xff);
3293 AssertRC(rc);
3294 HMCPU_CF_SET(pVCpu, HM_CHANGED_SVM_GUEST_APIC_STATE);
3295 }
3296 else if (pSvmTransient->u8GuestTpr != pVmcb->ctrl.IntCtrl.n.u8VTPR)
3297 {
3298 int rc = APICSetTpr(pVCpu, pVmcb->ctrl.IntCtrl.n.u8VTPR << 4);
3299 AssertRC(rc);
3300 HMCPU_CF_SET(pVCpu, HM_CHANGED_SVM_GUEST_APIC_STATE);
3301 }
3302 }
3303 }
3304}
3305
3306
3307/**
3308 * Runs the guest code using AMD-V.
3309 *
3310 * @returns VBox status code.
3311 * @param pVM The cross context VM structure.
3312 * @param pVCpu The cross context virtual CPU structure.
3313 * @param pCtx Pointer to the guest-CPU context.
3314 */
3315static int hmR0SvmRunGuestCodeNormal(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
3316{
3317 SVMTRANSIENT SvmTransient;
3318 SvmTransient.fUpdateTscOffsetting = true;
3319 uint32_t cLoops = 0;
3320 int rc = VERR_INTERNAL_ERROR_5;
3321
3322 for (;; cLoops++)
3323 {
3324 Assert(!HMR0SuspendPending());
3325 HMSVM_ASSERT_CPU_SAFE();
3326
3327 /* Preparatory work for running guest code, this may force us to return
3328 to ring-3. This bugger disables interrupts on VINF_SUCCESS! */
3329 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatEntry, x);
3330 rc = hmR0SvmPreRunGuest(pVM, pVCpu, pCtx, &SvmTransient);
3331 if (rc != VINF_SUCCESS)
3332 break;
3333
3334 /*
3335 * No longjmps to ring-3 from this point on!!!
3336 * Asserts() will still longjmp to ring-3 (but won't return), which is intentional, better than a kernel panic.
3337 * This also disables flushing of the R0-logger instance (if any).
3338 */
3339 hmR0SvmPreRunGuestCommitted(pVM, pVCpu, pCtx, &SvmTransient);
3340 rc = hmR0SvmRunGuest(pVM, pVCpu, pCtx);
3341
3342 /* Restore any residual host-state and save any bits shared between host
3343 and guest into the guest-CPU state. Re-enables interrupts! */
3344 hmR0SvmPostRunGuest(pVM, pVCpu, pCtx, &SvmTransient, rc);
3345
3346 if (RT_UNLIKELY( rc != VINF_SUCCESS /* Check for VMRUN errors. */
3347 || SvmTransient.u64ExitCode == (uint64_t)SVM_EXIT_INVALID)) /* Check for invalid guest-state errors. */
3348 {
3349 if (rc == VINF_SUCCESS)
3350 rc = VERR_SVM_INVALID_GUEST_STATE;
3351 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExit1, x);
3352 hmR0SvmReportWorldSwitchError(pVM, pVCpu, rc, pCtx);
3353 break;
3354 }
3355
3356 /* Handle the #VMEXIT. */
3357 HMSVM_EXITCODE_STAM_COUNTER_INC(SvmTransient.u64ExitCode);
3358 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatExit1, &pVCpu->hm.s.StatExit2, x);
3359 VBOXVMM_R0_HMSVM_VMEXIT(pVCpu, pCtx, SvmTransient.u64ExitCode, (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb);
3360 rc = hmR0SvmHandleExit(pVCpu, pCtx, &SvmTransient);
3361 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExit2, x);
3362 if (rc != VINF_SUCCESS)
3363 break;
3364 if (cLoops > pVM->hm.s.cMaxResumeLoops)
3365 {
3366 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchMaxResumeLoops);
3367 rc = VINF_EM_RAW_INTERRUPT;
3368 break;
3369 }
3370 }
3371
3372 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatEntry, x);
3373 return rc;
3374}
3375
3376
3377/**
3378 * Runs the guest code using AMD-V in single step mode.
3379 *
3380 * @returns VBox status code.
3381 * @param pVM The cross context VM structure.
3382 * @param pVCpu The cross context virtual CPU structure.
3383 * @param pCtx Pointer to the guest-CPU context.
3384 */
3385static int hmR0SvmRunGuestCodeStep(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
3386{
3387 SVMTRANSIENT SvmTransient;
3388 SvmTransient.fUpdateTscOffsetting = true;
3389 uint32_t cLoops = 0;
3390 int rc = VERR_INTERNAL_ERROR_5;
3391 uint16_t uCsStart = pCtx->cs.Sel;
3392 uint64_t uRipStart = pCtx->rip;
3393
3394 for (;; cLoops++)
3395 {
3396 Assert(!HMR0SuspendPending());
3397 AssertMsg(pVCpu->hm.s.idEnteredCpu == RTMpCpuId(),
3398 ("Illegal migration! Entered on CPU %u Current %u cLoops=%u\n", (unsigned)pVCpu->hm.s.idEnteredCpu,
3399 (unsigned)RTMpCpuId(), cLoops));
3400
3401 /* Preparatory work for running guest code, this may force us to return
3402 to ring-3. This bugger disables interrupts on VINF_SUCCESS! */
3403 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatEntry, x);
3404 rc = hmR0SvmPreRunGuest(pVM, pVCpu, pCtx, &SvmTransient);
3405 if (rc != VINF_SUCCESS)
3406 break;
3407
3408 /*
3409 * No longjmps to ring-3 from this point on!!!
3410 * Asserts() will still longjmp to ring-3 (but won't return), which is intentional, better than a kernel panic.
3411 * This also disables flushing of the R0-logger instance (if any).
3412 */
3413 VMMRZCallRing3Disable(pVCpu);
3414 VMMRZCallRing3RemoveNotification(pVCpu);
3415 hmR0SvmPreRunGuestCommitted(pVM, pVCpu, pCtx, &SvmTransient);
3416
3417 rc = hmR0SvmRunGuest(pVM, pVCpu, pCtx);
3418
3419 /*
3420 * Restore any residual host-state and save any bits shared between host and guest into the guest-CPU state.
3421 * This will also re-enable longjmps to ring-3 when it has reached a safe point!!!
3422 */
3423 hmR0SvmPostRunGuest(pVM, pVCpu, pCtx, &SvmTransient, rc);
3424 if (RT_UNLIKELY( rc != VINF_SUCCESS /* Check for VMRUN errors. */
3425 || SvmTransient.u64ExitCode == (uint64_t)SVM_EXIT_INVALID)) /* Check for invalid guest-state errors. */
3426 {
3427 if (rc == VINF_SUCCESS)
3428 rc = VERR_SVM_INVALID_GUEST_STATE;
3429 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExit1, x);
3430 hmR0SvmReportWorldSwitchError(pVM, pVCpu, rc, pCtx);
3431 return rc;
3432 }
3433
3434 /* Handle the #VMEXIT. */
3435 HMSVM_EXITCODE_STAM_COUNTER_INC(SvmTransient.u64ExitCode);
3436 STAM_PROFILE_ADV_STOP_START(&pVCpu->hm.s.StatExit1, &pVCpu->hm.s.StatExit2, x);
3437 VBOXVMM_R0_HMSVM_VMEXIT(pVCpu, pCtx, SvmTransient.u64ExitCode, (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb);
3438 rc = hmR0SvmHandleExit(pVCpu, pCtx, &SvmTransient);
3439 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatExit2, x);
3440 if (rc != VINF_SUCCESS)
3441 break;
3442 if (cLoops > pVM->hm.s.cMaxResumeLoops)
3443 {
3444 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchMaxResumeLoops);
3445 rc = VINF_EM_RAW_INTERRUPT;
3446 break;
3447 }
3448
3449 /*
3450 * Did the RIP change, if so, consider it a single step.
3451 * Otherwise, make sure one of the TFs gets set.
3452 */
3453 if ( pCtx->rip != uRipStart
3454 || pCtx->cs.Sel != uCsStart)
3455 {
3456 rc = VINF_EM_DBG_STEPPED;
3457 break;
3458 }
3459 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_GUEST_DEBUG;
3460 }
3461
3462 /*
3463 * Clear the X86_EFL_TF if necessary.
3464 */
3465 if (pVCpu->hm.s.fClearTrapFlag)
3466 {
3467 pVCpu->hm.s.fClearTrapFlag = false;
3468 pCtx->eflags.Bits.u1TF = 0;
3469 }
3470
3471 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatEntry, x);
3472 return rc;
3473}
3474
3475
3476/**
3477 * Runs the guest code using AMD-V.
3478 *
3479 * @returns Strict VBox status code.
3480 * @param pVM The cross context VM structure.
3481 * @param pVCpu The cross context virtual CPU structure.
3482 * @param pCtx Pointer to the guest-CPU context.
3483 */
3484VMMR0DECL(VBOXSTRICTRC) SVMR0RunGuestCode(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
3485{
3486 Assert(VMMRZCallRing3IsEnabled(pVCpu));
3487 HMSVM_ASSERT_PREEMPT_SAFE();
3488 VMMRZCallRing3SetNotification(pVCpu, hmR0SvmCallRing3Callback, pCtx);
3489
3490 int rc;
3491 if (!pVCpu->hm.s.fSingleInstruction)
3492 rc = hmR0SvmRunGuestCodeNormal(pVM, pVCpu, pCtx);
3493 else
3494 rc = hmR0SvmRunGuestCodeStep(pVM, pVCpu, pCtx);
3495
3496 if (rc == VERR_EM_INTERPRETER)
3497 rc = VINF_EM_RAW_EMULATE_INSTR;
3498 else if (rc == VINF_EM_RESET)
3499 rc = VINF_EM_TRIPLE_FAULT;
3500
3501 /* Prepare to return to ring-3. This will remove longjmp notifications. */
3502 hmR0SvmExitToRing3(pVM, pVCpu, pCtx, rc);
3503 Assert(!VMMRZCallRing3IsNotificationSet(pVCpu));
3504 return rc;
3505}
3506
3507
3508/**
3509 * Handles a \#VMEXIT (for all EXITCODE values except SVM_EXIT_INVALID).
3510 *
3511 * @returns VBox status code (informational status codes included).
3512 * @param pVCpu The cross context virtual CPU structure.
3513 * @param pCtx Pointer to the guest-CPU context.
3514 * @param pSvmTransient Pointer to the SVM transient structure.
3515 */
3516DECLINLINE(int) hmR0SvmHandleExit(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3517{
3518 Assert(pSvmTransient->u64ExitCode != (uint64_t)SVM_EXIT_INVALID);
3519 Assert(pSvmTransient->u64ExitCode <= SVM_EXIT_MAX);
3520
3521 /*
3522 * The ordering of the case labels is based on most-frequently-occurring #VMEXITs for most guests under
3523 * normal workloads (for some definition of "normal").
3524 */
3525 uint32_t u32ExitCode = pSvmTransient->u64ExitCode;
3526 switch (pSvmTransient->u64ExitCode)
3527 {
3528 case SVM_EXIT_NPF:
3529 return hmR0SvmExitNestedPF(pVCpu, pCtx, pSvmTransient);
3530
3531 case SVM_EXIT_IOIO:
3532 return hmR0SvmExitIOInstr(pVCpu, pCtx, pSvmTransient);
3533
3534 case SVM_EXIT_RDTSC:
3535 return hmR0SvmExitRdtsc(pVCpu, pCtx, pSvmTransient);
3536
3537 case SVM_EXIT_RDTSCP:
3538 return hmR0SvmExitRdtscp(pVCpu, pCtx, pSvmTransient);
3539
3540 case SVM_EXIT_CPUID:
3541 return hmR0SvmExitCpuid(pVCpu, pCtx, pSvmTransient);
3542
3543 case SVM_EXIT_EXCEPTION_E: /* X86_XCPT_PF */
3544 return hmR0SvmExitXcptPF(pVCpu, pCtx, pSvmTransient);
3545
3546 case SVM_EXIT_EXCEPTION_7: /* X86_XCPT_NM */
3547 return hmR0SvmExitXcptNM(pVCpu, pCtx, pSvmTransient);
3548
3549 case SVM_EXIT_EXCEPTION_6: /* X86_XCPT_UD */
3550 return hmR0SvmExitXcptUD(pVCpu, pCtx, pSvmTransient);
3551
3552 case SVM_EXIT_EXCEPTION_10: /* X86_XCPT_MF */
3553 return hmR0SvmExitXcptMF(pVCpu, pCtx, pSvmTransient);
3554
3555 case SVM_EXIT_EXCEPTION_1: /* X86_XCPT_DB */
3556 return hmR0SvmExitXcptDB(pVCpu, pCtx, pSvmTransient);
3557
3558 case SVM_EXIT_EXCEPTION_11: /* X86_XCPT_AC */
3559 return hmR0SvmExitXcptAC(pVCpu, pCtx, pSvmTransient);
3560
3561 case SVM_EXIT_EXCEPTION_3: /* X86_XCPT_BP */
3562 return hmR0SvmExitXcptBP(pVCpu, pCtx, pSvmTransient);
3563
3564 case SVM_EXIT_MONITOR:
3565 return hmR0SvmExitMonitor(pVCpu, pCtx, pSvmTransient);
3566
3567 case SVM_EXIT_MWAIT:
3568 return hmR0SvmExitMwait(pVCpu, pCtx, pSvmTransient);
3569
3570 case SVM_EXIT_HLT:
3571 return hmR0SvmExitHlt(pVCpu, pCtx, pSvmTransient);
3572
3573 case SVM_EXIT_READ_CR0:
3574 case SVM_EXIT_READ_CR3:
3575 case SVM_EXIT_READ_CR4:
3576 return hmR0SvmExitReadCRx(pVCpu, pCtx, pSvmTransient);
3577
3578 case SVM_EXIT_WRITE_CR0:
3579 case SVM_EXIT_WRITE_CR3:
3580 case SVM_EXIT_WRITE_CR4:
3581 case SVM_EXIT_WRITE_CR8:
3582 return hmR0SvmExitWriteCRx(pVCpu, pCtx, pSvmTransient);
3583
3584 case SVM_EXIT_PAUSE:
3585 return hmR0SvmExitPause(pVCpu, pCtx, pSvmTransient);
3586
3587 case SVM_EXIT_VMMCALL:
3588 return hmR0SvmExitVmmCall(pVCpu, pCtx, pSvmTransient);
3589
3590 case SVM_EXIT_VINTR:
3591 return hmR0SvmExitVIntr(pVCpu, pCtx, pSvmTransient);
3592
3593 case SVM_EXIT_INTR:
3594 case SVM_EXIT_FERR_FREEZE:
3595 case SVM_EXIT_NMI:
3596 return hmR0SvmExitIntr(pVCpu, pCtx, pSvmTransient);
3597
3598 case SVM_EXIT_MSR:
3599 return hmR0SvmExitMsr(pVCpu, pCtx, pSvmTransient);
3600
3601 case SVM_EXIT_INVLPG:
3602 return hmR0SvmExitInvlpg(pVCpu, pCtx, pSvmTransient);
3603
3604 case SVM_EXIT_WBINVD:
3605 return hmR0SvmExitWbinvd(pVCpu, pCtx, pSvmTransient);
3606
3607 case SVM_EXIT_INVD:
3608 return hmR0SvmExitInvd(pVCpu, pCtx, pSvmTransient);
3609
3610 case SVM_EXIT_RDPMC:
3611 return hmR0SvmExitRdpmc(pVCpu, pCtx, pSvmTransient);
3612
3613 default:
3614 {
3615 switch (pSvmTransient->u64ExitCode)
3616 {
3617 case SVM_EXIT_READ_DR0: case SVM_EXIT_READ_DR1: case SVM_EXIT_READ_DR2: case SVM_EXIT_READ_DR3:
3618 case SVM_EXIT_READ_DR6: case SVM_EXIT_READ_DR7: case SVM_EXIT_READ_DR8: case SVM_EXIT_READ_DR9:
3619 case SVM_EXIT_READ_DR10: case SVM_EXIT_READ_DR11: case SVM_EXIT_READ_DR12: case SVM_EXIT_READ_DR13:
3620 case SVM_EXIT_READ_DR14: case SVM_EXIT_READ_DR15:
3621 return hmR0SvmExitReadDRx(pVCpu, pCtx, pSvmTransient);
3622
3623 case SVM_EXIT_WRITE_DR0: case SVM_EXIT_WRITE_DR1: case SVM_EXIT_WRITE_DR2: case SVM_EXIT_WRITE_DR3:
3624 case SVM_EXIT_WRITE_DR6: case SVM_EXIT_WRITE_DR7: case SVM_EXIT_WRITE_DR8: case SVM_EXIT_WRITE_DR9:
3625 case SVM_EXIT_WRITE_DR10: case SVM_EXIT_WRITE_DR11: case SVM_EXIT_WRITE_DR12: case SVM_EXIT_WRITE_DR13:
3626 case SVM_EXIT_WRITE_DR14: case SVM_EXIT_WRITE_DR15:
3627 return hmR0SvmExitWriteDRx(pVCpu, pCtx, pSvmTransient);
3628
3629 case SVM_EXIT_XSETBV:
3630 return hmR0SvmExitXsetbv(pVCpu, pCtx, pSvmTransient);
3631
3632 case SVM_EXIT_TASK_SWITCH:
3633 return hmR0SvmExitTaskSwitch(pVCpu, pCtx, pSvmTransient);
3634
3635 case SVM_EXIT_IRET:
3636 return hmR0SvmExitIret(pVCpu, pCtx, pSvmTransient);
3637
3638 case SVM_EXIT_SHUTDOWN:
3639 return hmR0SvmExitShutdown(pVCpu, pCtx, pSvmTransient);
3640
3641 case SVM_EXIT_SMI:
3642 case SVM_EXIT_INIT:
3643 {
3644 /*
3645 * We don't intercept NMIs. As for INIT signals, it really shouldn't ever happen here. If it ever does,
3646 * we want to know about it so log the exit code and bail.
3647 */
3648 AssertMsgFailed(("hmR0SvmHandleExit: Unexpected exit %#RX32\n", (uint32_t)pSvmTransient->u64ExitCode));
3649 pVCpu->hm.s.u32HMError = (uint32_t)pSvmTransient->u64ExitCode;
3650 return VERR_SVM_UNEXPECTED_EXIT;
3651 }
3652
3653#ifdef VBOX_WITH_NESTED_HWVIRT
3654 case SVM_EXIT_CLGI: return hmR0SvmExitClgi(pVCpu, pCtx, pSvmTransient);
3655 case SVM_EXIT_STGI: return hmR0SvmExitStgi(pVCpu, pCtx, pSvmTransient);
3656 case SVM_EXIT_VMLOAD: return hmR0SvmExitVmload(pVCpu, pCtx, pSvmTransient);
3657 case SVM_EXIT_VMSAVE: return hmR0SvmExitVmsave(pVCpu, pCtx, pSvmTransient);
3658#else
3659 case SVM_EXIT_CLGI:
3660 case SVM_EXIT_STGI:
3661 case SVM_EXIT_VMLOAD:
3662 case SVM_EXIT_VMSAVE:
3663#endif
3664 case SVM_EXIT_INVLPGA:
3665 case SVM_EXIT_RSM:
3666 case SVM_EXIT_VMRUN:
3667 case SVM_EXIT_SKINIT:
3668 return hmR0SvmExitSetPendingXcptUD(pVCpu, pCtx, pSvmTransient);
3669
3670#ifdef HMSVM_ALWAYS_TRAP_ALL_XCPTS
3671 case SVM_EXIT_EXCEPTION_0: /* X86_XCPT_DE */
3672 /* SVM_EXIT_EXCEPTION_1: */ /* X86_XCPT_DB - Handled above. */
3673 case SVM_EXIT_EXCEPTION_2: /* X86_XCPT_NMI */
3674 /* case SVM_EXIT_EXCEPTION_3: */ /* X86_XCPT_BP - Handled above. */
3675 case SVM_EXIT_EXCEPTION_4: /* X86_XCPT_OF */
3676 case SVM_EXIT_EXCEPTION_5: /* X86_XCPT_BR */
3677 /* case SVM_EXIT_EXCEPTION_6: */ /* X86_XCPT_UD - Handled above. */
3678 /* SVM_EXIT_EXCEPTION_7: */ /* X86_XCPT_NM - Handled above. */
3679 case SVM_EXIT_EXCEPTION_8: /* X86_XCPT_DF */
3680 case SVM_EXIT_EXCEPTION_9: /* X86_XCPT_CO_SEG_OVERRUN */
3681 case SVM_EXIT_EXCEPTION_A: /* X86_XCPT_TS */
3682 case SVM_EXIT_EXCEPTION_B: /* X86_XCPT_NP */
3683 case SVM_EXIT_EXCEPTION_C: /* X86_XCPT_SS */
3684 case SVM_EXIT_EXCEPTION_D: /* X86_XCPT_GP */
3685 /* SVM_EXIT_EXCEPTION_E: */ /* X86_XCPT_PF - Handled above. */
3686 /* SVM_EXIT_EXCEPTION_10: */ /* X86_XCPT_MF - Handled above. */
3687 /* SVM_EXIT_EXCEPTION_11: */ /* X86_XCPT_AC - Handled above. */
3688 case SVM_EXIT_EXCEPTION_12: /* X86_XCPT_MC */
3689 case SVM_EXIT_EXCEPTION_13: /* X86_XCPT_XF */
3690 case SVM_EXIT_EXCEPTION_F: /* Reserved */
3691 case SVM_EXIT_EXCEPTION_14: case SVM_EXIT_EXCEPTION_15: case SVM_EXIT_EXCEPTION_16:
3692 case SVM_EXIT_EXCEPTION_17: case SVM_EXIT_EXCEPTION_18: case SVM_EXIT_EXCEPTION_19:
3693 case SVM_EXIT_EXCEPTION_1A: case SVM_EXIT_EXCEPTION_1B: case SVM_EXIT_EXCEPTION_1C:
3694 case SVM_EXIT_EXCEPTION_1D: case SVM_EXIT_EXCEPTION_1E: case SVM_EXIT_EXCEPTION_1F:
3695 {
3696 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
3697 SVMEVENT Event;
3698 Event.u = 0;
3699 Event.n.u1Valid = 1;
3700 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3701 Event.n.u8Vector = pSvmTransient->u64ExitCode - SVM_EXIT_EXCEPTION_0;
3702
3703 switch (Event.n.u8Vector)
3704 {
3705 case X86_XCPT_DE:
3706 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestDE);
3707 break;
3708
3709 case X86_XCPT_NP:
3710 Event.n.u1ErrorCodeValid = 1;
3711 Event.n.u32ErrorCode = pVmcb->ctrl.u64ExitInfo1;
3712 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestNP);
3713 break;
3714
3715 case X86_XCPT_SS:
3716 Event.n.u1ErrorCodeValid = 1;
3717 Event.n.u32ErrorCode = pVmcb->ctrl.u64ExitInfo1;
3718 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestSS);
3719 break;
3720
3721 case X86_XCPT_GP:
3722 Event.n.u1ErrorCodeValid = 1;
3723 Event.n.u32ErrorCode = pVmcb->ctrl.u64ExitInfo1;
3724 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestGP);
3725 break;
3726
3727 default:
3728 AssertMsgFailed(("hmR0SvmHandleExit: Unexpected exit caused by exception %#x\n", Event.n.u8Vector));
3729 pVCpu->hm.s.u32HMError = Event.n.u8Vector;
3730 return VERR_SVM_UNEXPECTED_XCPT_EXIT;
3731 }
3732
3733 Log4(("#Xcpt: Vector=%#x at CS:RIP=%04x:%RGv\n", Event.n.u8Vector, pCtx->cs.Sel, (RTGCPTR)pCtx->rip));
3734 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3735 return VINF_SUCCESS;
3736 }
3737#endif /* HMSVM_ALWAYS_TRAP_ALL_XCPTS */
3738
3739 default:
3740 {
3741 AssertMsgFailed(("hmR0SvmHandleExit: Unknown exit code %#x\n", u32ExitCode));
3742 pVCpu->hm.s.u32HMError = u32ExitCode;
3743 return VERR_SVM_UNKNOWN_EXIT;
3744 }
3745 }
3746 }
3747 }
3748 /* not reached */
3749}
3750
3751
3752#ifdef DEBUG
3753/* Is there some generic IPRT define for this that are not in Runtime/internal/\* ?? */
3754# define HMSVM_ASSERT_PREEMPT_CPUID_VAR() \
3755 RTCPUID const idAssertCpu = RTThreadPreemptIsEnabled(NIL_RTTHREAD) ? NIL_RTCPUID : RTMpCpuId()
3756
3757# define HMSVM_ASSERT_PREEMPT_CPUID() \
3758 do \
3759 { \
3760 RTCPUID const idAssertCpuNow = RTThreadPreemptIsEnabled(NIL_RTTHREAD) ? NIL_RTCPUID : RTMpCpuId(); \
3761 AssertMsg(idAssertCpu == idAssertCpuNow, ("SVM %#x, %#x\n", idAssertCpu, idAssertCpuNow)); \
3762 } while (0)
3763
3764# define HMSVM_VALIDATE_EXIT_HANDLER_PARAMS() \
3765 do { \
3766 AssertPtr(pVCpu); \
3767 AssertPtr(pCtx); \
3768 AssertPtr(pSvmTransient); \
3769 Assert(ASMIntAreEnabled()); \
3770 HMSVM_ASSERT_PREEMPT_SAFE(); \
3771 HMSVM_ASSERT_PREEMPT_CPUID_VAR(); \
3772 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)); \
3773 HMSVM_ASSERT_PREEMPT_SAFE(); \
3774 if (VMMR0IsLogFlushDisabled(pVCpu)) \
3775 HMSVM_ASSERT_PREEMPT_CPUID(); \
3776 } while (0)
3777#else /* Release builds */
3778# define HMSVM_VALIDATE_EXIT_HANDLER_PARAMS() do { NOREF(pVCpu); NOREF(pCtx); NOREF(pSvmTransient); } while (0)
3779#endif
3780
3781
3782/**
3783 * Worker for hmR0SvmInterpretInvlpg().
3784 *
3785 * @return VBox status code.
3786 * @param pVCpu The cross context virtual CPU structure.
3787 * @param pCpu Pointer to the disassembler state.
3788 * @param pCtx The guest CPU context.
3789 */
3790static int hmR0SvmInterpretInvlPgEx(PVMCPU pVCpu, PDISCPUSTATE pCpu, PCPUMCTX pCtx)
3791{
3792 DISQPVPARAMVAL Param1;
3793 RTGCPTR GCPtrPage;
3794
3795 int rc = DISQueryParamVal(CPUMCTX2CORE(pCtx), pCpu, &pCpu->Param1, &Param1, DISQPVWHICH_SRC);
3796 if (RT_FAILURE(rc))
3797 return VERR_EM_INTERPRETER;
3798
3799 if ( Param1.type == DISQPV_TYPE_IMMEDIATE
3800 || Param1.type == DISQPV_TYPE_ADDRESS)
3801 {
3802 if (!(Param1.flags & (DISQPV_FLAG_32 | DISQPV_FLAG_64)))
3803 return VERR_EM_INTERPRETER;
3804
3805 GCPtrPage = Param1.val.val64;
3806 VBOXSTRICTRC rc2 = EMInterpretInvlpg(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx), GCPtrPage);
3807 rc = VBOXSTRICTRC_VAL(rc2);
3808 }
3809 else
3810 {
3811 Log4(("hmR0SvmInterpretInvlPgEx invalid parameter type %#x\n", Param1.type));
3812 rc = VERR_EM_INTERPRETER;
3813 }
3814
3815 return rc;
3816}
3817
3818
3819/**
3820 * Interprets INVLPG.
3821 *
3822 * @returns VBox status code.
3823 * @retval VINF_* Scheduling instructions.
3824 * @retval VERR_EM_INTERPRETER Something we can't cope with.
3825 * @retval VERR_* Fatal errors.
3826 *
3827 * @param pVM The cross context VM structure.
3828 * @param pVCpu The cross context virtual CPU structure.
3829 * @param pCtx The guest CPU context.
3830 *
3831 * @remarks Updates the RIP if the instruction was executed successfully.
3832 */
3833static int hmR0SvmInterpretInvlpg(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
3834{
3835 /* Only allow 32 & 64 bit code. */
3836 if (CPUMGetGuestCodeBits(pVCpu) != 16)
3837 {
3838 PDISSTATE pDis = &pVCpu->hm.s.DisState;
3839 int rc = EMInterpretDisasCurrent(pVM, pVCpu, pDis, NULL /* pcbInstr */);
3840 if ( RT_SUCCESS(rc)
3841 && pDis->pCurInstr->uOpcode == OP_INVLPG)
3842 {
3843 rc = hmR0SvmInterpretInvlPgEx(pVCpu, pDis, pCtx);
3844 if (RT_SUCCESS(rc))
3845 pCtx->rip += pDis->cbInstr;
3846 return rc;
3847 }
3848 else
3849 Log4(("hmR0SvmInterpretInvlpg: EMInterpretDisasCurrent returned %Rrc uOpCode=%#x\n", rc, pDis->pCurInstr->uOpcode));
3850 }
3851 return VERR_EM_INTERPRETER;
3852}
3853
3854
3855/**
3856 * Sets an invalid-opcode (\#UD) exception as pending-for-injection into the VM.
3857 *
3858 * @param pVCpu The cross context virtual CPU structure.
3859 */
3860DECLINLINE(void) hmR0SvmSetPendingXcptUD(PVMCPU pVCpu)
3861{
3862 SVMEVENT Event;
3863 Event.u = 0;
3864 Event.n.u1Valid = 1;
3865 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3866 Event.n.u8Vector = X86_XCPT_UD;
3867 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3868}
3869
3870
3871/**
3872 * Sets a debug (\#DB) exception as pending-for-injection into the VM.
3873 *
3874 * @param pVCpu The cross context virtual CPU structure.
3875 */
3876DECLINLINE(void) hmR0SvmSetPendingXcptDB(PVMCPU pVCpu)
3877{
3878 SVMEVENT Event;
3879 Event.u = 0;
3880 Event.n.u1Valid = 1;
3881 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3882 Event.n.u8Vector = X86_XCPT_DB;
3883 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3884}
3885
3886
3887/**
3888 * Sets a page fault (\#PF) exception as pending-for-injection into the VM.
3889 *
3890 * @param pVCpu The cross context virtual CPU structure.
3891 * @param pCtx Pointer to the guest-CPU context.
3892 * @param u32ErrCode The error-code for the page-fault.
3893 * @param uFaultAddress The page fault address (CR2).
3894 *
3895 * @remarks This updates the guest CR2 with @a uFaultAddress!
3896 */
3897DECLINLINE(void) hmR0SvmSetPendingXcptPF(PVMCPU pVCpu, PCPUMCTX pCtx, uint32_t u32ErrCode, RTGCUINTPTR uFaultAddress)
3898{
3899 SVMEVENT Event;
3900 Event.u = 0;
3901 Event.n.u1Valid = 1;
3902 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3903 Event.n.u8Vector = X86_XCPT_PF;
3904 Event.n.u1ErrorCodeValid = 1;
3905 Event.n.u32ErrorCode = u32ErrCode;
3906
3907 /* Update CR2 of the guest. */
3908 if (pCtx->cr2 != uFaultAddress)
3909 {
3910 pCtx->cr2 = uFaultAddress;
3911 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR2);
3912 }
3913
3914 hmR0SvmSetPendingEvent(pVCpu, &Event, uFaultAddress);
3915}
3916
3917
3918/**
3919 * Sets a device-not-available (\#NM) exception as pending-for-injection into
3920 * the VM.
3921 *
3922 * @param pVCpu The cross context virtual CPU structure.
3923 */
3924DECLINLINE(void) hmR0SvmSetPendingXcptNM(PVMCPU pVCpu)
3925{
3926 SVMEVENT Event;
3927 Event.u = 0;
3928 Event.n.u1Valid = 1;
3929 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3930 Event.n.u8Vector = X86_XCPT_NM;
3931 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3932}
3933
3934
3935/**
3936 * Sets a math-fault (\#MF) exception as pending-for-injection into the VM.
3937 *
3938 * @param pVCpu The cross context virtual CPU structure.
3939 */
3940DECLINLINE(void) hmR0SvmSetPendingXcptMF(PVMCPU pVCpu)
3941{
3942 SVMEVENT Event;
3943 Event.u = 0;
3944 Event.n.u1Valid = 1;
3945 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3946 Event.n.u8Vector = X86_XCPT_MF;
3947 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3948}
3949
3950
3951/**
3952 * Sets a double fault (\#DF) exception as pending-for-injection into the VM.
3953 *
3954 * @param pVCpu The cross context virtual CPU structure.
3955 */
3956DECLINLINE(void) hmR0SvmSetPendingXcptDF(PVMCPU pVCpu)
3957{
3958 SVMEVENT Event;
3959 Event.u = 0;
3960 Event.n.u1Valid = 1;
3961 Event.n.u3Type = SVM_EVENT_EXCEPTION;
3962 Event.n.u8Vector = X86_XCPT_DF;
3963 Event.n.u1ErrorCodeValid = 1;
3964 Event.n.u32ErrorCode = 0;
3965 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
3966}
3967
3968
3969/**
3970 * Emulates a simple MOV TPR (CR8) instruction, used for TPR patching on 32-bit
3971 * guests. This simply looks up the patch record at EIP and does the required.
3972 *
3973 * This VMMCALL is used a fallback mechanism when mov to/from cr8 isn't exactly
3974 * like how we want it to be (e.g. not followed by shr 4 as is usually done for
3975 * TPR). See hmR3ReplaceTprInstr() for the details.
3976 *
3977 * @returns VBox status code.
3978 * @retval VINF_SUCCESS if the access was handled successfully.
3979 * @retval VERR_NOT_FOUND if no patch record for this RIP could be found.
3980 * @retval VERR_SVM_UNEXPECTED_PATCH_TYPE if the found patch type is invalid.
3981 *
3982 * @param pVM The cross context VM structure.
3983 * @param pVCpu The cross context virtual CPU structure.
3984 * @param pCtx Pointer to the guest-CPU context.
3985 */
3986static int hmR0SvmEmulateMovTpr(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
3987{
3988 Log4(("Emulated VMMCall TPR access replacement at RIP=%RGv\n", pCtx->rip));
3989
3990 /*
3991 * We do this in a loop as we increment the RIP after a successful emulation
3992 * and the new RIP may be a patched instruction which needs emulation as well.
3993 */
3994 bool fPatchFound = false;
3995 for (;;)
3996 {
3997 bool fPending;
3998 uint8_t u8Tpr;
3999
4000 PHMTPRPATCH pPatch = (PHMTPRPATCH)RTAvloU32Get(&pVM->hm.s.PatchTree, (AVLOU32KEY)pCtx->eip);
4001 if (!pPatch)
4002 break;
4003
4004 fPatchFound = true;
4005 switch (pPatch->enmType)
4006 {
4007 case HMTPRINSTR_READ:
4008 {
4009 int rc = APICGetTpr(pVCpu, &u8Tpr, &fPending, NULL /* pu8PendingIrq */);
4010 AssertRC(rc);
4011
4012 rc = DISWriteReg32(CPUMCTX2CORE(pCtx), pPatch->uDstOperand, u8Tpr);
4013 AssertRC(rc);
4014 pCtx->rip += pPatch->cbOp;
4015 break;
4016 }
4017
4018 case HMTPRINSTR_WRITE_REG:
4019 case HMTPRINSTR_WRITE_IMM:
4020 {
4021 if (pPatch->enmType == HMTPRINSTR_WRITE_REG)
4022 {
4023 uint32_t u32Val;
4024 int rc = DISFetchReg32(CPUMCTX2CORE(pCtx), pPatch->uSrcOperand, &u32Val);
4025 AssertRC(rc);
4026 u8Tpr = u32Val;
4027 }
4028 else
4029 u8Tpr = (uint8_t)pPatch->uSrcOperand;
4030
4031 int rc2 = APICSetTpr(pVCpu, u8Tpr);
4032 AssertRC(rc2);
4033 HMCPU_CF_SET(pVCpu, HM_CHANGED_SVM_GUEST_APIC_STATE);
4034
4035 pCtx->rip += pPatch->cbOp;
4036 break;
4037 }
4038
4039 default:
4040 AssertMsgFailed(("Unexpected patch type %d\n", pPatch->enmType));
4041 pVCpu->hm.s.u32HMError = pPatch->enmType;
4042 return VERR_SVM_UNEXPECTED_PATCH_TYPE;
4043 }
4044 }
4045
4046 if (fPatchFound)
4047 return VINF_SUCCESS;
4048 return VERR_NOT_FOUND;
4049}
4050
4051
4052/**
4053 * Determines if an exception is a contributory exception.
4054 *
4055 * Contributory exceptions are ones which can cause double-faults unless the
4056 * original exception was a benign exception. Page-fault is intentionally not
4057 * included here as it's a conditional contributory exception.
4058 *
4059 * @returns true if the exception is contributory, false otherwise.
4060 * @param uVector The exception vector.
4061 */
4062DECLINLINE(bool) hmR0SvmIsContributoryXcpt(const uint32_t uVector)
4063{
4064 switch (uVector)
4065 {
4066 case X86_XCPT_GP:
4067 case X86_XCPT_SS:
4068 case X86_XCPT_NP:
4069 case X86_XCPT_TS:
4070 case X86_XCPT_DE:
4071 return true;
4072 default:
4073 break;
4074 }
4075 return false;
4076}
4077
4078
4079/**
4080 * Handle a condition that occurred while delivering an event through the guest
4081 * IDT.
4082 *
4083 * @returns VBox status code (informational error codes included).
4084 * @retval VINF_SUCCESS if we should continue handling the \#VMEXIT.
4085 * @retval VINF_HM_DOUBLE_FAULT if a \#DF condition was detected and we ought to
4086 * continue execution of the guest which will delivery the \#DF.
4087 * @retval VINF_EM_RESET if we detected a triple-fault condition.
4088 * @retval VERR_EM_GUEST_CPU_HANG if we detected a guest CPU hang.
4089 *
4090 * @param pVCpu The cross context virtual CPU structure.
4091 * @param pCtx Pointer to the guest-CPU context.
4092 * @param pSvmTransient Pointer to the SVM transient structure.
4093 *
4094 * @remarks No-long-jump zone!!!
4095 */
4096static int hmR0SvmCheckExitDueToEventDelivery(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4097{
4098 int rc = VINF_SUCCESS;
4099 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
4100
4101 Log4(("EXITINTINFO: Pending vectoring event %#RX64 Valid=%RTbool ErrValid=%RTbool Err=%#RX32 Type=%u Vector=%u\n",
4102 pVmcb->ctrl.ExitIntInfo.u, !!pVmcb->ctrl.ExitIntInfo.n.u1Valid, !!pVmcb->ctrl.ExitIntInfo.n.u1ErrorCodeValid,
4103 pVmcb->ctrl.ExitIntInfo.n.u32ErrorCode, pVmcb->ctrl.ExitIntInfo.n.u3Type, pVmcb->ctrl.ExitIntInfo.n.u8Vector));
4104
4105 /* See AMD spec. 15.7.3 "EXITINFO Pseudo-Code". The EXITINTINFO (if valid) contains the prior exception (IDT vector)
4106 * that was trying to be delivered to the guest which caused a #VMEXIT which was intercepted (Exit vector). */
4107 if (pVmcb->ctrl.ExitIntInfo.n.u1Valid)
4108 {
4109 uint8_t uIdtVector = pVmcb->ctrl.ExitIntInfo.n.u8Vector;
4110
4111 typedef enum
4112 {
4113 SVMREFLECTXCPT_XCPT, /* Reflect the exception to the guest or for further evaluation by VMM. */
4114 SVMREFLECTXCPT_DF, /* Reflect the exception as a double-fault to the guest. */
4115 SVMREFLECTXCPT_TF, /* Indicate a triple faulted state to the VMM. */
4116 SVMREFLECTXCPT_HANG, /* Indicate bad VM trying to deadlock the CPU. */
4117 SVMREFLECTXCPT_NONE /* Nothing to reflect. */
4118 } SVMREFLECTXCPT;
4119
4120 SVMREFLECTXCPT enmReflect = SVMREFLECTXCPT_NONE;
4121 bool fReflectingNmi = false;
4122 if (pVmcb->ctrl.ExitIntInfo.n.u3Type == SVM_EVENT_EXCEPTION)
4123 {
4124 if (pSvmTransient->u64ExitCode - SVM_EXIT_EXCEPTION_0 <= SVM_EXIT_EXCEPTION_1F)
4125 {
4126 uint8_t uExitVector = (uint8_t)(pSvmTransient->u64ExitCode - SVM_EXIT_EXCEPTION_0);
4127
4128#ifdef VBOX_STRICT
4129 if ( hmR0SvmIsContributoryXcpt(uIdtVector)
4130 && uExitVector == X86_XCPT_PF)
4131 {
4132 Log4(("IDT: Contributory #PF idCpu=%u uCR2=%#RX64\n", pVCpu->idCpu, pCtx->cr2));
4133 }
4134#endif
4135
4136 if ( uIdtVector == X86_XCPT_BP
4137 || uIdtVector == X86_XCPT_OF)
4138 {
4139 /* Ignore INT3/INTO, just re-execute. See @bugref{8357}. */
4140 }
4141 else if ( uExitVector == X86_XCPT_PF
4142 && uIdtVector == X86_XCPT_PF)
4143 {
4144 pSvmTransient->fVectoringDoublePF = true;
4145 Log4(("IDT: Vectoring double #PF uCR2=%#RX64\n", pCtx->cr2));
4146 }
4147 else if ( uExitVector == X86_XCPT_AC
4148 && uIdtVector == X86_XCPT_AC)
4149 {
4150 enmReflect = SVMREFLECTXCPT_HANG;
4151 Log4(("IDT: Nested #AC - Bad guest\n"));
4152 }
4153 else if ( (pVmcb->ctrl.u32InterceptException & HMSVM_CONTRIBUTORY_XCPT_MASK)
4154 && hmR0SvmIsContributoryXcpt(uExitVector)
4155 && ( hmR0SvmIsContributoryXcpt(uIdtVector)
4156 || uIdtVector == X86_XCPT_PF))
4157 {
4158 enmReflect = SVMREFLECTXCPT_DF;
4159 Log4(("IDT: Pending vectoring #DF %#RX64 uIdtVector=%#x uExitVector=%#x\n", pVCpu->hm.s.Event.u64IntInfo,
4160 uIdtVector, uExitVector));
4161 }
4162 else if (uIdtVector == X86_XCPT_DF)
4163 {
4164 enmReflect = SVMREFLECTXCPT_TF;
4165 Log4(("IDT: Pending vectoring triple-fault %#RX64 uIdtVector=%#x uExitVector=%#x\n",
4166 pVCpu->hm.s.Event.u64IntInfo, uIdtVector, uExitVector));
4167 }
4168 else
4169 enmReflect = SVMREFLECTXCPT_XCPT;
4170 }
4171 else
4172 {
4173 /*
4174 * If event delivery caused an #VMEXIT that is not an exception (e.g. #NPF) then reflect the original
4175 * exception to the guest after handling the #VMEXIT.
4176 */
4177 enmReflect = SVMREFLECTXCPT_XCPT;
4178 }
4179 }
4180 else if ( pVmcb->ctrl.ExitIntInfo.n.u3Type == SVM_EVENT_EXTERNAL_IRQ
4181 || pVmcb->ctrl.ExitIntInfo.n.u3Type == SVM_EVENT_NMI)
4182 {
4183 enmReflect = SVMREFLECTXCPT_XCPT;
4184 fReflectingNmi = RT_BOOL(pVmcb->ctrl.ExitIntInfo.n.u3Type == SVM_EVENT_NMI);
4185
4186 if (pSvmTransient->u64ExitCode - SVM_EXIT_EXCEPTION_0 <= SVM_EXIT_EXCEPTION_1F)
4187 {
4188 uint8_t uExitVector = (uint8_t)(pSvmTransient->u64ExitCode - SVM_EXIT_EXCEPTION_0);
4189 if (uExitVector == X86_XCPT_PF)
4190 {
4191 pSvmTransient->fVectoringPF = true;
4192 Log4(("IDT: Vectoring #PF due to Ext-Int/NMI. uCR2=%#RX64\n", pCtx->cr2));
4193 }
4194 }
4195 }
4196 /* else: Ignore software interrupts (INT n) as they reoccur when restarting the instruction. */
4197
4198 switch (enmReflect)
4199 {
4200 case SVMREFLECTXCPT_XCPT:
4201 {
4202 /* If we are re-injecting the NMI, clear NMI blocking. */
4203 if (fReflectingNmi)
4204 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_BLOCK_NMIS);
4205
4206 Assert(pVmcb->ctrl.ExitIntInfo.n.u3Type != SVM_EVENT_SOFTWARE_INT);
4207 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectPendingReflect);
4208 hmR0SvmSetPendingEvent(pVCpu, &pVmcb->ctrl.ExitIntInfo, 0 /* GCPtrFaultAddress */);
4209
4210 /* If uExitVector is #PF, CR2 value will be updated from the VMCB if it's a guest #PF. See hmR0SvmExitXcptPF(). */
4211 Log4(("IDT: Pending vectoring event %#RX64 ErrValid=%RTbool Err=%#RX32\n", pVmcb->ctrl.ExitIntInfo.u,
4212 !!pVmcb->ctrl.ExitIntInfo.n.u1ErrorCodeValid, pVmcb->ctrl.ExitIntInfo.n.u32ErrorCode));
4213 break;
4214 }
4215
4216 case SVMREFLECTXCPT_DF:
4217 {
4218 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectPendingReflect);
4219 hmR0SvmSetPendingXcptDF(pVCpu);
4220 rc = VINF_HM_DOUBLE_FAULT;
4221 break;
4222 }
4223
4224 case SVMREFLECTXCPT_TF:
4225 {
4226 rc = VINF_EM_RESET;
4227 break;
4228 }
4229
4230 case SVMREFLECTXCPT_HANG:
4231 {
4232 rc = VERR_EM_GUEST_CPU_HANG;
4233 break;
4234 }
4235
4236 default:
4237 Assert(rc == VINF_SUCCESS);
4238 break;
4239 }
4240 }
4241 Assert(rc == VINF_SUCCESS || rc == VINF_HM_DOUBLE_FAULT || rc == VINF_EM_RESET || rc == VERR_EM_GUEST_CPU_HANG);
4242 NOREF(pCtx);
4243 return rc;
4244}
4245
4246/**
4247 * Updates interrupt shadow for the current RIP.
4248 */
4249#define HMSVM_UPDATE_INTR_SHADOW(pVCpu, pCtx) \
4250 do { \
4251 /* Update interrupt shadow. */ \
4252 if ( VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS) \
4253 && pCtx->rip != EMGetInhibitInterruptsPC(pVCpu)) \
4254 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS); \
4255 } while (0)
4256
4257/**
4258 * Advances the guest RIP making use of the CPU's NRIP_SAVE feature if
4259 * supported, otherwise advances the RIP by the number of bytes specified in
4260 * @a cb.
4261 *
4262 * @param pVCpu The cross context virtual CPU structure.
4263 * @param pCtx Pointer to the guest-CPU context.
4264 * @param cb RIP increment value in bytes.
4265 *
4266 * @remarks Use this function only from \#VMEXIT's where the NRIP value is valid
4267 * when NRIP_SAVE is supported by the CPU, otherwise use
4268 * hmR0SvmAdvanceRipDumb!
4269 */
4270DECLINLINE(void) hmR0SvmAdvanceRipHwAssist(PVMCPU pVCpu, PCPUMCTX pCtx, uint32_t cb)
4271{
4272 if (pVCpu->CTX_SUFF(pVM)->hm.s.svm.u32Features & AMD_CPUID_SVM_FEATURE_EDX_NRIP_SAVE)
4273 {
4274 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
4275 Assert(pVmcb->ctrl.u64NextRIP);
4276 Assert(pVmcb->ctrl.u64NextRIP - pCtx->rip == cb);
4277 pCtx->rip = pVmcb->ctrl.u64NextRIP;
4278 }
4279 else
4280 pCtx->rip += cb;
4281
4282 HMSVM_UPDATE_INTR_SHADOW(pVCpu, pCtx);
4283}
4284
4285
4286/**
4287 * Advances the guest RIP by the number of bytes specified in @a cb. This does
4288 * not make use of any hardware features to determine the instruction length.
4289 *
4290 * @param pVCpu The cross context virtual CPU structure.
4291 * @param pCtx Pointer to the guest-CPU context.
4292 * @param cb RIP increment value in bytes.
4293 */
4294DECLINLINE(void) hmR0SvmAdvanceRipDumb(PVMCPU pVCpu, PCPUMCTX pCtx, uint32_t cb)
4295{
4296 pCtx->rip += cb;
4297 HMSVM_UPDATE_INTR_SHADOW(pVCpu, pCtx);
4298}
4299#undef HMSVM_UPDATE_INTR_SHADOW
4300
4301
4302/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
4303/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- #VMEXIT handlers -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */
4304/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
4305
4306/** @name \#VMEXIT handlers.
4307 * @{
4308 */
4309
4310/**
4311 * \#VMEXIT handler for external interrupts, NMIs, FPU assertion freeze and INIT
4312 * signals (SVM_EXIT_INTR, SVM_EXIT_NMI, SVM_EXIT_FERR_FREEZE, SVM_EXIT_INIT).
4313 */
4314HMSVM_EXIT_DECL hmR0SvmExitIntr(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4315{
4316 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4317
4318 if (pSvmTransient->u64ExitCode == SVM_EXIT_NMI)
4319 STAM_REL_COUNTER_INC(&pVCpu->hm.s.StatExitHostNmiInGC);
4320 else if (pSvmTransient->u64ExitCode == SVM_EXIT_INTR)
4321 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitExtInt);
4322
4323 /*
4324 * AMD-V has no preemption timer and the generic periodic preemption timer has no way to signal -before- the timer
4325 * fires if the current interrupt is our own timer or a some other host interrupt. We also cannot examine what
4326 * interrupt it is until the host actually take the interrupt.
4327 *
4328 * Going back to executing guest code here unconditionally causes random scheduling problems (observed on an
4329 * AMD Phenom 9850 Quad-Core on Windows 64-bit host).
4330 */
4331 return VINF_EM_RAW_INTERRUPT;
4332}
4333
4334
4335/**
4336 * \#VMEXIT handler for WBINVD (SVM_EXIT_WBINVD). Conditional \#VMEXIT.
4337 */
4338HMSVM_EXIT_DECL hmR0SvmExitWbinvd(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4339{
4340 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4341
4342 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 2);
4343 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitWbinvd);
4344 int rc = VINF_SUCCESS;
4345 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4346 return rc;
4347}
4348
4349
4350/**
4351 * \#VMEXIT handler for INVD (SVM_EXIT_INVD). Unconditional \#VMEXIT.
4352 */
4353HMSVM_EXIT_DECL hmR0SvmExitInvd(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4354{
4355 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4356
4357 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 2);
4358 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitInvd);
4359 int rc = VINF_SUCCESS;
4360 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4361 return rc;
4362}
4363
4364
4365/**
4366 * \#VMEXIT handler for INVD (SVM_EXIT_CPUID). Conditional \#VMEXIT.
4367 */
4368HMSVM_EXIT_DECL hmR0SvmExitCpuid(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4369{
4370 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4371 PVM pVM = pVCpu->CTX_SUFF(pVM);
4372 int rc = EMInterpretCpuId(pVM, pVCpu, CPUMCTX2CORE(pCtx));
4373 if (RT_LIKELY(rc == VINF_SUCCESS))
4374 {
4375 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 2);
4376 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4377 }
4378 else
4379 {
4380 AssertMsgFailed(("hmR0SvmExitCpuid: EMInterpretCpuId failed with %Rrc\n", rc));
4381 rc = VERR_EM_INTERPRETER;
4382 }
4383 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCpuid);
4384 return rc;
4385}
4386
4387
4388/**
4389 * \#VMEXIT handler for RDTSC (SVM_EXIT_RDTSC). Conditional \#VMEXIT.
4390 */
4391HMSVM_EXIT_DECL hmR0SvmExitRdtsc(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4392{
4393 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4394 PVM pVM = pVCpu->CTX_SUFF(pVM);
4395 int rc = EMInterpretRdtsc(pVM, pVCpu, CPUMCTX2CORE(pCtx));
4396 if (RT_LIKELY(rc == VINF_SUCCESS))
4397 {
4398 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 2);
4399 pSvmTransient->fUpdateTscOffsetting = true;
4400
4401 /* Single step check. */
4402 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4403 }
4404 else
4405 {
4406 AssertMsgFailed(("hmR0SvmExitRdtsc: EMInterpretRdtsc failed with %Rrc\n", rc));
4407 rc = VERR_EM_INTERPRETER;
4408 }
4409 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdtsc);
4410 return rc;
4411}
4412
4413
4414/**
4415 * \#VMEXIT handler for RDTSCP (SVM_EXIT_RDTSCP). Conditional \#VMEXIT.
4416 */
4417HMSVM_EXIT_DECL hmR0SvmExitRdtscp(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4418{
4419 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4420 int rc = EMInterpretRdtscp(pVCpu->CTX_SUFF(pVM), pVCpu, pCtx);
4421 if (RT_LIKELY(rc == VINF_SUCCESS))
4422 {
4423 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 3);
4424 pSvmTransient->fUpdateTscOffsetting = true;
4425 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4426 }
4427 else
4428 {
4429 AssertMsgFailed(("hmR0SvmExitRdtsc: EMInterpretRdtscp failed with %Rrc\n", rc));
4430 rc = VERR_EM_INTERPRETER;
4431 }
4432 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdtscp);
4433 return rc;
4434}
4435
4436
4437/**
4438 * \#VMEXIT handler for RDPMC (SVM_EXIT_RDPMC). Conditional \#VMEXIT.
4439 */
4440HMSVM_EXIT_DECL hmR0SvmExitRdpmc(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4441{
4442 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4443 int rc = EMInterpretRdpmc(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx));
4444 if (RT_LIKELY(rc == VINF_SUCCESS))
4445 {
4446 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 2);
4447 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4448 }
4449 else
4450 {
4451 AssertMsgFailed(("hmR0SvmExitRdpmc: EMInterpretRdpmc failed with %Rrc\n", rc));
4452 rc = VERR_EM_INTERPRETER;
4453 }
4454 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdpmc);
4455 return rc;
4456}
4457
4458
4459/**
4460 * \#VMEXIT handler for INVLPG (SVM_EXIT_INVLPG). Conditional \#VMEXIT.
4461 */
4462HMSVM_EXIT_DECL hmR0SvmExitInvlpg(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4463{
4464 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4465 PVM pVM = pVCpu->CTX_SUFF(pVM);
4466 Assert(!pVM->hm.s.fNestedPaging);
4467
4468 /** @todo Decode Assist. */
4469 int rc = hmR0SvmInterpretInvlpg(pVM, pVCpu, pCtx); /* Updates RIP if successful. */
4470 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitInvlpg);
4471 Assert(rc == VINF_SUCCESS || rc == VERR_EM_INTERPRETER);
4472 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4473 return rc;
4474}
4475
4476
4477/**
4478 * \#VMEXIT handler for HLT (SVM_EXIT_HLT). Conditional \#VMEXIT.
4479 */
4480HMSVM_EXIT_DECL hmR0SvmExitHlt(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4481{
4482 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4483
4484 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 1);
4485 int rc = EMShouldContinueAfterHalt(pVCpu, pCtx) ? VINF_SUCCESS : VINF_EM_HALT;
4486 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4487 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitHlt);
4488 if (rc != VINF_SUCCESS)
4489 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchHltToR3);
4490 return rc;
4491}
4492
4493
4494/**
4495 * \#VMEXIT handler for MONITOR (SVM_EXIT_MONITOR). Conditional \#VMEXIT.
4496 */
4497HMSVM_EXIT_DECL hmR0SvmExitMonitor(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4498{
4499 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4500 int rc = EMInterpretMonitor(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx));
4501 if (RT_LIKELY(rc == VINF_SUCCESS))
4502 {
4503 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 3);
4504 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4505 }
4506 else
4507 {
4508 AssertMsg(rc == VERR_EM_INTERPRETER, ("hmR0SvmExitMonitor: EMInterpretMonitor failed with %Rrc\n", rc));
4509 rc = VERR_EM_INTERPRETER;
4510 }
4511 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitMonitor);
4512 return rc;
4513}
4514
4515
4516/**
4517 * \#VMEXIT handler for MWAIT (SVM_EXIT_MWAIT). Conditional \#VMEXIT.
4518 */
4519HMSVM_EXIT_DECL hmR0SvmExitMwait(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4520{
4521 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4522 VBOXSTRICTRC rc2 = EMInterpretMWait(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx));
4523 int rc = VBOXSTRICTRC_VAL(rc2);
4524 if ( rc == VINF_EM_HALT
4525 || rc == VINF_SUCCESS)
4526 {
4527 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 3);
4528
4529 if ( rc == VINF_EM_HALT
4530 && EMMonitorWaitShouldContinue(pVCpu, pCtx))
4531 {
4532 rc = VINF_SUCCESS;
4533 }
4534 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4535 }
4536 else
4537 {
4538 AssertMsg(rc == VERR_EM_INTERPRETER, ("hmR0SvmExitMwait: EMInterpretMWait failed with %Rrc\n", rc));
4539 rc = VERR_EM_INTERPRETER;
4540 }
4541 AssertMsg(rc == VINF_SUCCESS || rc == VINF_EM_HALT || rc == VERR_EM_INTERPRETER,
4542 ("hmR0SvmExitMwait: EMInterpretMWait failed rc=%Rrc\n", rc));
4543 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitMwait);
4544 return rc;
4545}
4546
4547
4548/**
4549 * \#VMEXIT handler for shutdown (triple-fault) (SVM_EXIT_SHUTDOWN). Conditional
4550 * \#VMEXIT.
4551 */
4552HMSVM_EXIT_DECL hmR0SvmExitShutdown(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4553{
4554 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4555 return VINF_EM_RESET;
4556}
4557
4558
4559/**
4560 * \#VMEXIT handler for CRx reads (SVM_EXIT_READ_CR*). Conditional \#VMEXIT.
4561 */
4562HMSVM_EXIT_DECL hmR0SvmExitReadCRx(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4563{
4564 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4565
4566 Log4(("hmR0SvmExitReadCRx: CS:RIP=%04x:%#RX64\n", pCtx->cs.Sel, pCtx->rip));
4567
4568 /** @todo Decode Assist. */
4569 VBOXSTRICTRC rc2 = EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0 /* pvFault */);
4570 int rc = VBOXSTRICTRC_VAL(rc2);
4571 AssertMsg(rc == VINF_SUCCESS || rc == VERR_EM_INTERPRETER || rc == VINF_PGM_CHANGE_MODE || rc == VINF_PGM_SYNC_CR3,
4572 ("hmR0SvmExitReadCRx: EMInterpretInstruction failed rc=%Rrc\n", rc));
4573 Assert((pSvmTransient->u64ExitCode - SVM_EXIT_READ_CR0) <= 15);
4574 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCRxRead[pSvmTransient->u64ExitCode - SVM_EXIT_READ_CR0]);
4575 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4576 return rc;
4577}
4578
4579
4580/**
4581 * \#VMEXIT handler for CRx writes (SVM_EXIT_WRITE_CR*). Conditional \#VMEXIT.
4582 */
4583HMSVM_EXIT_DECL hmR0SvmExitWriteCRx(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4584{
4585 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4586
4587 /** @todo Decode Assist. */
4588 VBOXSTRICTRC rcStrict = IEMExecOneBypassEx(pVCpu, CPUMCTX2CORE(pCtx), NULL);
4589 if (RT_UNLIKELY( rcStrict == VERR_IEM_ASPECT_NOT_IMPLEMENTED
4590 || rcStrict == VERR_IEM_INSTR_NOT_IMPLEMENTED))
4591 rcStrict = VERR_EM_INTERPRETER;
4592 if (rcStrict == VINF_SUCCESS)
4593 {
4594 /* RIP has been updated by EMInterpretInstruction(). */
4595 Assert((pSvmTransient->u64ExitCode - SVM_EXIT_WRITE_CR0) <= 15);
4596 switch (pSvmTransient->u64ExitCode - SVM_EXIT_WRITE_CR0)
4597 {
4598 case 0: /* CR0. */
4599 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR0);
4600 break;
4601
4602 case 3: /* CR3. */
4603 Assert(!pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging);
4604 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR3);
4605 break;
4606
4607 case 4: /* CR4. */
4608 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR4);
4609 break;
4610
4611 case 8: /* CR8 (TPR). */
4612 HMCPU_CF_SET(pVCpu, HM_CHANGED_SVM_GUEST_APIC_STATE);
4613 break;
4614
4615 default:
4616 AssertMsgFailed(("hmR0SvmExitWriteCRx: Invalid/Unexpected Write-CRx exit. u64ExitCode=%#RX64 %#x\n",
4617 pSvmTransient->u64ExitCode, pSvmTransient->u64ExitCode - SVM_EXIT_WRITE_CR0));
4618 break;
4619 }
4620 HMSVM_CHECK_SINGLE_STEP(pVCpu, rcStrict);
4621 }
4622 else
4623 Assert(rcStrict == VERR_EM_INTERPRETER || rcStrict == VINF_PGM_CHANGE_MODE || rcStrict == VINF_PGM_SYNC_CR3);
4624 return VBOXSTRICTRC_TODO(rcStrict);
4625}
4626
4627
4628/**
4629 * \#VMEXIT handler for instructions that result in a \#UD exception delivered
4630 * to the guest.
4631 */
4632HMSVM_EXIT_DECL hmR0SvmExitSetPendingXcptUD(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4633{
4634 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4635 hmR0SvmSetPendingXcptUD(pVCpu);
4636 return VINF_SUCCESS;
4637}
4638
4639
4640/**
4641 * \#VMEXIT handler for MSR read and writes (SVM_EXIT_MSR). Conditional
4642 * \#VMEXIT.
4643 */
4644HMSVM_EXIT_DECL hmR0SvmExitMsr(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4645{
4646 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4647 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
4648 PVM pVM = pVCpu->CTX_SUFF(pVM);
4649
4650 int rc;
4651 if (pVmcb->ctrl.u64ExitInfo1 == SVM_EXIT1_MSR_WRITE)
4652 {
4653 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitWrmsr);
4654
4655 /* Handle TPR patching; intercepted LSTAR write. */
4656 if ( pVM->hm.s.fTPRPatchingActive
4657 && pCtx->ecx == MSR_K8_LSTAR)
4658 {
4659 if ((pCtx->eax & 0xff) != pSvmTransient->u8GuestTpr)
4660 {
4661 /* Our patch code uses LSTAR for TPR caching for 32-bit guests. */
4662 int rc2 = APICSetTpr(pVCpu, pCtx->eax & 0xff);
4663 AssertRC(rc2);
4664 HMCPU_CF_SET(pVCpu, HM_CHANGED_SVM_GUEST_APIC_STATE);
4665 }
4666 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 2);
4667 rc = VINF_SUCCESS;
4668 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4669 return rc;
4670 }
4671
4672 if (pVM->hm.s.svm.u32Features & AMD_CPUID_SVM_FEATURE_EDX_NRIP_SAVE)
4673 {
4674 rc = EMInterpretWrmsr(pVM, pVCpu, CPUMCTX2CORE(pCtx));
4675 if (RT_LIKELY(rc == VINF_SUCCESS))
4676 {
4677 pCtx->rip = pVmcb->ctrl.u64NextRIP;
4678 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4679 }
4680 else
4681 AssertMsg( rc == VERR_EM_INTERPRETER
4682 || rc == VINF_CPUM_R3_MSR_WRITE, ("hmR0SvmExitMsr: EMInterpretWrmsr failed rc=%Rrc\n", rc));
4683 }
4684 else
4685 {
4686 rc = VBOXSTRICTRC_TODO(EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0 /* pvFault */));
4687 if (RT_LIKELY(rc == VINF_SUCCESS))
4688 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc); /* RIP updated by EMInterpretInstruction(). */
4689 else
4690 AssertMsg( rc == VERR_EM_INTERPRETER
4691 || rc == VINF_CPUM_R3_MSR_WRITE, ("hmR0SvmExitMsr: WrMsr. EMInterpretInstruction failed rc=%Rrc\n", rc));
4692 }
4693
4694 if (rc == VINF_SUCCESS)
4695 {
4696 /* If this is an X2APIC WRMSR access, update the APIC state as well. */
4697 if ( pCtx->ecx >= MSR_IA32_X2APIC_START
4698 && pCtx->ecx <= MSR_IA32_X2APIC_END)
4699 {
4700 /*
4701 * We've already saved the APIC related guest-state (TPR) in hmR0SvmPostRunGuest(). When full APIC register
4702 * virtualization is implemented we'll have to make sure APIC state is saved from the VMCB before
4703 * EMInterpretWrmsr() changes it.
4704 */
4705 HMCPU_CF_SET(pVCpu, HM_CHANGED_SVM_GUEST_APIC_STATE);
4706 }
4707 else if (pCtx->ecx == MSR_K6_EFER)
4708 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_EFER_MSR);
4709 else if (pCtx->ecx == MSR_IA32_TSC)
4710 pSvmTransient->fUpdateTscOffsetting = true;
4711 }
4712 }
4713 else
4714 {
4715 /* MSR Read access. */
4716 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdmsr);
4717 Assert(pVmcb->ctrl.u64ExitInfo1 == SVM_EXIT1_MSR_READ);
4718
4719 if (pVM->hm.s.svm.u32Features & AMD_CPUID_SVM_FEATURE_EDX_NRIP_SAVE)
4720 {
4721 rc = EMInterpretRdmsr(pVM, pVCpu, CPUMCTX2CORE(pCtx));
4722 if (RT_LIKELY(rc == VINF_SUCCESS))
4723 {
4724 pCtx->rip = pVmcb->ctrl.u64NextRIP;
4725 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4726 }
4727 else
4728 AssertMsg( rc == VERR_EM_INTERPRETER
4729 || rc == VINF_CPUM_R3_MSR_READ, ("hmR0SvmExitMsr: EMInterpretRdmsr failed rc=%Rrc\n", rc));
4730 }
4731 else
4732 {
4733 rc = VBOXSTRICTRC_TODO(EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0));
4734 if (RT_UNLIKELY(rc != VINF_SUCCESS))
4735 {
4736 AssertMsg( rc == VERR_EM_INTERPRETER
4737 || rc == VINF_CPUM_R3_MSR_READ, ("hmR0SvmExitMsr: RdMsr. EMInterpretInstruction failed rc=%Rrc\n", rc));
4738 }
4739 /* RIP updated by EMInterpretInstruction(). */
4740 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4741 }
4742 }
4743
4744 /* RIP has been updated by EMInterpret[Rd|Wr]msr(). */
4745 return rc;
4746}
4747
4748
4749/**
4750 * \#VMEXIT handler for DRx read (SVM_EXIT_READ_DRx). Conditional \#VMEXIT.
4751 */
4752HMSVM_EXIT_DECL hmR0SvmExitReadDRx(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4753{
4754 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4755 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitDRxRead);
4756
4757 /* We should -not- get this #VMEXIT if the guest's debug registers were active. */
4758 if (pSvmTransient->fWasGuestDebugStateActive)
4759 {
4760 AssertMsgFailed(("hmR0SvmHandleExit: Unexpected exit %#RX32\n", (uint32_t)pSvmTransient->u64ExitCode));
4761 pVCpu->hm.s.u32HMError = (uint32_t)pSvmTransient->u64ExitCode;
4762 return VERR_SVM_UNEXPECTED_EXIT;
4763 }
4764
4765 /*
4766 * Lazy DR0-3 loading.
4767 */
4768 if (!pSvmTransient->fWasHyperDebugStateActive)
4769 {
4770 Assert(!DBGFIsStepping(pVCpu)); Assert(!pVCpu->hm.s.fSingleInstruction);
4771 Log5(("hmR0SvmExitReadDRx: Lazy loading guest debug registers\n"));
4772
4773 /* Don't intercept DRx read and writes. */
4774 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
4775 pVmcb->ctrl.u16InterceptRdDRx = 0;
4776 pVmcb->ctrl.u16InterceptWrDRx = 0;
4777 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
4778
4779 /* We're playing with the host CPU state here, make sure we don't preempt or longjmp. */
4780 VMMRZCallRing3Disable(pVCpu);
4781 HM_DISABLE_PREEMPT();
4782
4783 /* Save the host & load the guest debug state, restart execution of the MOV DRx instruction. */
4784 CPUMR0LoadGuestDebugState(pVCpu, false /* include DR6 */);
4785 Assert(CPUMIsGuestDebugStateActive(pVCpu) || HC_ARCH_BITS == 32);
4786
4787 HM_RESTORE_PREEMPT();
4788 VMMRZCallRing3Enable(pVCpu);
4789
4790 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxContextSwitch);
4791 return VINF_SUCCESS;
4792 }
4793
4794 /*
4795 * Interpret the read/writing of DRx.
4796 */
4797 /** @todo Decode assist. */
4798 VBOXSTRICTRC rc = EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0 /* pvFault */);
4799 Log5(("hmR0SvmExitReadDRx: Emulated DRx access: rc=%Rrc\n", VBOXSTRICTRC_VAL(rc)));
4800 if (RT_LIKELY(rc == VINF_SUCCESS))
4801 {
4802 /* Not necessary for read accesses but whatever doesn't hurt for now, will be fixed with decode assist. */
4803 /** @todo CPUM should set this flag! */
4804 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_DEBUG);
4805 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
4806 }
4807 else
4808 Assert(rc == VERR_EM_INTERPRETER);
4809 return VBOXSTRICTRC_TODO(rc);
4810}
4811
4812
4813/**
4814 * \#VMEXIT handler for DRx write (SVM_EXIT_WRITE_DRx). Conditional \#VMEXIT.
4815 */
4816HMSVM_EXIT_DECL hmR0SvmExitWriteDRx(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4817{
4818 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4819 /* For now it's the same since we interpret the instruction anyway. Will change when using of Decode Assist is implemented. */
4820 int rc = hmR0SvmExitReadDRx(pVCpu, pCtx, pSvmTransient);
4821 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitDRxWrite);
4822 STAM_COUNTER_DEC(&pVCpu->hm.s.StatExitDRxRead);
4823 return rc;
4824}
4825
4826
4827/**
4828 * \#VMEXIT handler for XCRx write (SVM_EXIT_XSETBV). Conditional \#VMEXIT.
4829 */
4830HMSVM_EXIT_DECL hmR0SvmExitXsetbv(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4831{
4832 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4833
4834 /** @todo decode assists... */
4835 VBOXSTRICTRC rcStrict = IEMExecOne(pVCpu);
4836 if (rcStrict == VINF_IEM_RAISED_XCPT)
4837 HMCPU_CF_SET(pVCpu, HM_CHANGED_ALL_GUEST);
4838
4839 pVCpu->hm.s.fLoadSaveGuestXcr0 = (pCtx->cr4 & X86_CR4_OSXSAVE) && pCtx->aXcr[0] != ASMGetXcr0();
4840 Log4(("hmR0SvmExitXsetbv: New XCR0=%#RX64 fLoadSaveGuestXcr0=%d (cr4=%RX64) rcStrict=%Rrc\n",
4841 pCtx->aXcr[0], pVCpu->hm.s.fLoadSaveGuestXcr0, pCtx->cr4, VBOXSTRICTRC_VAL(rcStrict)));
4842
4843 HMSVM_CHECK_SINGLE_STEP(pVCpu, rcStrict);
4844 return VBOXSTRICTRC_TODO(rcStrict);
4845}
4846
4847
4848/**
4849 * \#VMEXIT handler for I/O instructions (SVM_EXIT_IOIO). Conditional \#VMEXIT.
4850 */
4851HMSVM_EXIT_DECL hmR0SvmExitIOInstr(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
4852{
4853 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
4854
4855 /* I/O operation lookup arrays. */
4856 static uint32_t const s_aIOSize[8] = { 0, 1, 2, 0, 4, 0, 0, 0 }; /* Size of the I/O accesses in bytes. */
4857 static uint32_t const s_aIOOpAnd[8] = { 0, 0xff, 0xffff, 0, 0xffffffff, 0, 0, 0 }; /* AND masks for saving
4858 the result (in AL/AX/EAX). */
4859 Log4(("hmR0SvmExitIOInstr: CS:RIP=%04x:%#RX64\n", pCtx->cs.Sel, pCtx->rip));
4860
4861 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
4862 PVM pVM = pVCpu->CTX_SUFF(pVM);
4863
4864 /* Refer AMD spec. 15.10.2 "IN and OUT Behaviour" and Figure 15-2. "EXITINFO1 for IOIO Intercept" for the format. */
4865 SVMIOIOEXIT IoExitInfo;
4866 IoExitInfo.u = (uint32_t)pVmcb->ctrl.u64ExitInfo1;
4867 uint32_t uIOWidth = (IoExitInfo.u >> 4) & 0x7;
4868 uint32_t cbValue = s_aIOSize[uIOWidth];
4869 uint32_t uAndVal = s_aIOOpAnd[uIOWidth];
4870
4871 if (RT_UNLIKELY(!cbValue))
4872 {
4873 AssertMsgFailed(("hmR0SvmExitIOInstr: Invalid IO operation. uIOWidth=%u\n", uIOWidth));
4874 return VERR_EM_INTERPRETER;
4875 }
4876
4877 VBOXSTRICTRC rcStrict;
4878 bool fUpdateRipAlready = false;
4879 if (IoExitInfo.n.u1STR)
4880 {
4881#ifdef VBOX_WITH_2ND_IEM_STEP
4882 /* INS/OUTS - I/O String instruction. */
4883 /** @todo Huh? why can't we use the segment prefix information given by AMD-V
4884 * in EXITINFO1? Investigate once this thing is up and running. */
4885 Log4(("CS:RIP=%04x:%08RX64 %#06x/%u %c str\n", pCtx->cs.Sel, pCtx->rip, IoExitInfo.n.u16Port, cbValue,
4886 IoExitInfo.n.u1Type == SVM_IOIO_WRITE ? 'w' : 'r'));
4887 AssertReturn(pCtx->dx == IoExitInfo.n.u16Port, VERR_SVM_IPE_2);
4888 static IEMMODE const s_aenmAddrMode[8] =
4889 {
4890 (IEMMODE)-1, IEMMODE_16BIT, IEMMODE_32BIT, (IEMMODE)-1, IEMMODE_64BIT, (IEMMODE)-1, (IEMMODE)-1, (IEMMODE)-1
4891 };
4892 IEMMODE enmAddrMode = s_aenmAddrMode[(IoExitInfo.u >> 7) & 0x7];
4893 if (enmAddrMode != (IEMMODE)-1)
4894 {
4895 uint64_t cbInstr = pVmcb->ctrl.u64ExitInfo2 - pCtx->rip;
4896 if (cbInstr <= 15 && cbInstr >= 1)
4897 {
4898 Assert(cbInstr >= 1U + IoExitInfo.n.u1REP);
4899 if (IoExitInfo.n.u1Type == SVM_IOIO_WRITE)
4900 {
4901 /* Don't know exactly how to detect whether u3SEG is valid, currently
4902 only enabling it for Bulldozer and later with NRIP. OS/2 broke on
4903 2384 Opterons when only checking NRIP. */
4904 if ( (pVM->hm.s.svm.u32Features & AMD_CPUID_SVM_FEATURE_EDX_NRIP_SAVE)
4905 && pVM->cpum.ro.GuestFeatures.enmMicroarch >= kCpumMicroarch_AMD_15h_First)
4906 {
4907 AssertMsg(IoExitInfo.n.u3SEG == X86_SREG_DS || cbInstr > 1U + IoExitInfo.n.u1REP,
4908 ("u32Seg=%d cbInstr=%d u1REP=%d", IoExitInfo.n.u3SEG, cbInstr, IoExitInfo.n.u1REP));
4909 rcStrict = IEMExecStringIoWrite(pVCpu, cbValue, enmAddrMode, IoExitInfo.n.u1REP, (uint8_t)cbInstr,
4910 IoExitInfo.n.u3SEG, true /*fIoChecked*/);
4911 }
4912 else if (cbInstr == 1U + IoExitInfo.n.u1REP)
4913 rcStrict = IEMExecStringIoWrite(pVCpu, cbValue, enmAddrMode, IoExitInfo.n.u1REP, (uint8_t)cbInstr,
4914 X86_SREG_DS, true /*fIoChecked*/);
4915 else
4916 rcStrict = IEMExecOne(pVCpu);
4917 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOStringWrite);
4918 }
4919 else
4920 {
4921 AssertMsg(IoExitInfo.n.u3SEG == X86_SREG_ES /*=0*/, ("%#x\n", IoExitInfo.n.u3SEG));
4922 rcStrict = IEMExecStringIoRead(pVCpu, cbValue, enmAddrMode, IoExitInfo.n.u1REP, (uint8_t)cbInstr,
4923 true /*fIoChecked*/);
4924 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOStringRead);
4925 }
4926 }
4927 else
4928 {
4929 AssertMsgFailed(("rip=%RX64 nrip=%#RX64 cbInstr=%#RX64\n", pCtx->rip, pVmcb->ctrl.u64ExitInfo2, cbInstr));
4930 rcStrict = IEMExecOne(pVCpu);
4931 }
4932 }
4933 else
4934 {
4935 AssertMsgFailed(("IoExitInfo=%RX64\n", IoExitInfo.u));
4936 rcStrict = IEMExecOne(pVCpu);
4937 }
4938 fUpdateRipAlready = true;
4939
4940#else
4941 /* INS/OUTS - I/O String instruction. */
4942 PDISCPUSTATE pDis = &pVCpu->hm.s.DisState;
4943
4944 /** @todo Huh? why can't we use the segment prefix information given by AMD-V
4945 * in EXITINFO1? Investigate once this thing is up and running. */
4946
4947 rcStrict = EMInterpretDisasCurrent(pVM, pVCpu, pDis, NULL);
4948 if (rcStrict == VINF_SUCCESS)
4949 {
4950 if (IoExitInfo.n.u1Type == SVM_IOIO_WRITE)
4951 {
4952 rcStrict = IOMInterpretOUTSEx(pVM, pVCpu, CPUMCTX2CORE(pCtx), IoExitInfo.n.u16Port, pDis->fPrefix,
4953 (DISCPUMODE)pDis->uAddrMode, cbValue);
4954 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOStringWrite);
4955 }
4956 else
4957 {
4958 rcStrict = IOMInterpretINSEx(pVM, pVCpu, CPUMCTX2CORE(pCtx), IoExitInfo.n.u16Port, pDis->fPrefix,
4959 (DISCPUMODE)pDis->uAddrMode, cbValue);
4960 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOStringRead);
4961 }
4962 }
4963 else
4964 rcStrict = VINF_EM_RAW_EMULATE_INSTR;
4965#endif
4966 }
4967 else
4968 {
4969 /* IN/OUT - I/O instruction. */
4970 Assert(!IoExitInfo.n.u1REP);
4971
4972 if (IoExitInfo.n.u1Type == SVM_IOIO_WRITE)
4973 {
4974 rcStrict = IOMIOPortWrite(pVM, pVCpu, IoExitInfo.n.u16Port, pCtx->eax & uAndVal, cbValue);
4975 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOWrite);
4976 }
4977 else
4978 {
4979 uint32_t u32Val = 0;
4980 rcStrict = IOMIOPortRead(pVM, pVCpu, IoExitInfo.n.u16Port, &u32Val, cbValue);
4981 if (IOM_SUCCESS(rcStrict))
4982 {
4983 /* Save result of I/O IN instr. in AL/AX/EAX. */
4984 /** @todo r=bird: 32-bit op size should clear high bits of rax! */
4985 pCtx->eax = (pCtx->eax & ~uAndVal) | (u32Val & uAndVal);
4986 }
4987 else if (rcStrict == VINF_IOM_R3_IOPORT_READ)
4988 HMR0SavePendingIOPortRead(pVCpu, pCtx->rip, pVmcb->ctrl.u64ExitInfo2, IoExitInfo.n.u16Port, uAndVal, cbValue);
4989
4990 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIORead);
4991 }
4992 }
4993
4994 if (IOM_SUCCESS(rcStrict))
4995 {
4996 /* AMD-V saves the RIP of the instruction following the IO instruction in EXITINFO2. */
4997 if (!fUpdateRipAlready)
4998 pCtx->rip = pVmcb->ctrl.u64ExitInfo2;
4999
5000 /*
5001 * If any I/O breakpoints are armed, we need to check if one triggered
5002 * and take appropriate action.
5003 * Note that the I/O breakpoint type is undefined if CR4.DE is 0.
5004 */
5005 /** @todo Optimize away the DBGFBpIsHwIoArmed call by having DBGF tell the
5006 * execution engines about whether hyper BPs and such are pending. */
5007 uint32_t const uDr7 = pCtx->dr[7];
5008 if (RT_UNLIKELY( ( (uDr7 & X86_DR7_ENABLED_MASK)
5009 && X86_DR7_ANY_RW_IO(uDr7)
5010 && (pCtx->cr4 & X86_CR4_DE))
5011 || DBGFBpIsHwIoArmed(pVM)))
5012 {
5013 /* We're playing with the host CPU state here, make sure we don't preempt or longjmp. */
5014 VMMRZCallRing3Disable(pVCpu);
5015 HM_DISABLE_PREEMPT();
5016
5017 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxIoCheck);
5018 CPUMR0DebugStateMaybeSaveGuest(pVCpu, false /*fDr6*/);
5019
5020 VBOXSTRICTRC rcStrict2 = DBGFBpCheckIo(pVM, pVCpu, pCtx, IoExitInfo.n.u16Port, cbValue);
5021 if (rcStrict2 == VINF_EM_RAW_GUEST_TRAP)
5022 {
5023 /* Raise #DB. */
5024 pVmcb->guest.u64DR6 = pCtx->dr[6];
5025 pVmcb->guest.u64DR7 = pCtx->dr[7];
5026 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_DRX;
5027 hmR0SvmSetPendingXcptDB(pVCpu);
5028 }
5029 /* rcStrict is VINF_SUCCESS, VINF_IOM_R3_IOPORT_COMMIT_WRITE, or in [VINF_EM_FIRST..VINF_EM_LAST],
5030 however we can ditch VINF_IOM_R3_IOPORT_COMMIT_WRITE as it has VMCPU_FF_IOM as backup. */
5031 else if ( rcStrict2 != VINF_SUCCESS
5032 && (rcStrict == VINF_SUCCESS || rcStrict2 < rcStrict))
5033 rcStrict = rcStrict2;
5034 AssertCompile(VINF_EM_LAST < VINF_IOM_R3_IOPORT_COMMIT_WRITE);
5035
5036 HM_RESTORE_PREEMPT();
5037 VMMRZCallRing3Enable(pVCpu);
5038 }
5039
5040 HMSVM_CHECK_SINGLE_STEP(pVCpu, rcStrict);
5041 }
5042
5043#ifdef VBOX_STRICT
5044 if (rcStrict == VINF_IOM_R3_IOPORT_READ)
5045 Assert(IoExitInfo.n.u1Type == SVM_IOIO_READ);
5046 else if (rcStrict == VINF_IOM_R3_IOPORT_WRITE || rcStrict == VINF_IOM_R3_IOPORT_COMMIT_WRITE)
5047 Assert(IoExitInfo.n.u1Type == SVM_IOIO_WRITE);
5048 else
5049 {
5050 /** @todo r=bird: This is missing a bunch of VINF_EM_FIRST..VINF_EM_LAST
5051 * statuses, that the VMM device and some others may return. See
5052 * IOM_SUCCESS() for guidance. */
5053 AssertMsg( RT_FAILURE(rcStrict)
5054 || rcStrict == VINF_SUCCESS
5055 || rcStrict == VINF_EM_RAW_EMULATE_INSTR
5056 || rcStrict == VINF_EM_DBG_BREAKPOINT
5057 || rcStrict == VINF_EM_RAW_GUEST_TRAP
5058 || rcStrict == VINF_EM_RAW_TO_R3
5059 || rcStrict == VINF_TRPM_XCPT_DISPATCHED, ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
5060 }
5061#endif
5062 return VBOXSTRICTRC_TODO(rcStrict);
5063}
5064
5065
5066/**
5067 * \#VMEXIT handler for Nested Page-faults (SVM_EXIT_NPF). Conditional \#VMEXIT.
5068 */
5069HMSVM_EXIT_DECL hmR0SvmExitNestedPF(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
5070{
5071 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
5072 PVM pVM = pVCpu->CTX_SUFF(pVM);
5073 Assert(pVM->hm.s.fNestedPaging);
5074
5075 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
5076
5077 /* See AMD spec. 15.25.6 "Nested versus Guest Page Faults, Fault Ordering" for VMCB details for #NPF. */
5078 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
5079 uint32_t u32ErrCode = pVmcb->ctrl.u64ExitInfo1;
5080 RTGCPHYS GCPhysFaultAddr = pVmcb->ctrl.u64ExitInfo2;
5081
5082 Log4(("#NPF at CS:RIP=%04x:%#RX64 faultaddr=%RGp errcode=%#x \n", pCtx->cs.Sel, pCtx->rip, GCPhysFaultAddr, u32ErrCode));
5083
5084#ifdef VBOX_HM_WITH_GUEST_PATCHING
5085 /* TPR patching for 32-bit guests, using the reserved bit in the page tables for MMIO regions. */
5086 if ( pVM->hm.s.fTprPatchingAllowed
5087 && (GCPhysFaultAddr & PAGE_OFFSET_MASK) == XAPIC_OFF_TPR
5088 && ( !(u32ErrCode & X86_TRAP_PF_P) /* Not present */
5089 || (u32ErrCode & (X86_TRAP_PF_P | X86_TRAP_PF_RSVD)) == (X86_TRAP_PF_P | X86_TRAP_PF_RSVD)) /* MMIO page. */
5090 && !CPUMIsGuestInLongModeEx(pCtx)
5091 && !CPUMGetGuestCPL(pVCpu)
5092 && pVM->hm.s.cPatches < RT_ELEMENTS(pVM->hm.s.aPatches))
5093 {
5094 RTGCPHYS GCPhysApicBase = APICGetBaseMsrNoCheck(pVCpu);
5095 GCPhysApicBase &= PAGE_BASE_GC_MASK;
5096
5097 if (GCPhysFaultAddr == GCPhysApicBase + XAPIC_OFF_TPR)
5098 {
5099 /* Only attempt to patch the instruction once. */
5100 PHMTPRPATCH pPatch = (PHMTPRPATCH)RTAvloU32Get(&pVM->hm.s.PatchTree, (AVLOU32KEY)pCtx->eip);
5101 if (!pPatch)
5102 return VINF_EM_HM_PATCH_TPR_INSTR;
5103 }
5104 }
5105#endif
5106
5107 /*
5108 * Determine the nested paging mode.
5109 */
5110 PGMMODE enmNestedPagingMode;
5111#if HC_ARCH_BITS == 32
5112 if (CPUMIsGuestInLongModeEx(pCtx))
5113 enmNestedPagingMode = PGMMODE_AMD64_NX;
5114 else
5115#endif
5116 enmNestedPagingMode = PGMGetHostMode(pVM);
5117
5118 /*
5119 * MMIO optimization using the reserved (RSVD) bit in the guest page tables for MMIO pages.
5120 */
5121 int rc;
5122 Assert((u32ErrCode & (X86_TRAP_PF_RSVD | X86_TRAP_PF_P)) != X86_TRAP_PF_RSVD);
5123 if ((u32ErrCode & (X86_TRAP_PF_RSVD | X86_TRAP_PF_P)) == (X86_TRAP_PF_RSVD | X86_TRAP_PF_P))
5124 {
5125 /* If event delivery causes an MMIO #NPF, go back to instruction emulation as
5126 otherwise injecting the original pending event would most likely cause the same MMIO #NPF. */
5127 if (RT_UNLIKELY(pVCpu->hm.s.Event.fPending))
5128 return VERR_EM_INTERPRETER;
5129
5130 VBOXSTRICTRC rc2 = PGMR0Trap0eHandlerNPMisconfig(pVM, pVCpu, enmNestedPagingMode, CPUMCTX2CORE(pCtx), GCPhysFaultAddr,
5131 u32ErrCode);
5132 rc = VBOXSTRICTRC_VAL(rc2);
5133
5134 /*
5135 * If we succeed, resume guest execution.
5136 * If we fail in interpreting the instruction because we couldn't get the guest physical address
5137 * of the page containing the instruction via the guest's page tables (we would invalidate the guest page
5138 * in the host TLB), resume execution which would cause a guest page fault to let the guest handle this
5139 * weird case. See @bugref{6043}.
5140 */
5141 if ( rc == VINF_SUCCESS
5142 || rc == VERR_PAGE_TABLE_NOT_PRESENT
5143 || rc == VERR_PAGE_NOT_PRESENT)
5144 {
5145 /* Successfully handled MMIO operation. */
5146 HMCPU_CF_SET(pVCpu, HM_CHANGED_SVM_GUEST_APIC_STATE);
5147 rc = VINF_SUCCESS;
5148 }
5149 return rc;
5150 }
5151
5152 TRPMAssertXcptPF(pVCpu, GCPhysFaultAddr, u32ErrCode);
5153 rc = PGMR0Trap0eHandlerNestedPaging(pVM, pVCpu, enmNestedPagingMode, u32ErrCode, CPUMCTX2CORE(pCtx), GCPhysFaultAddr);
5154 TRPMResetTrap(pVCpu);
5155
5156 Log4(("#NPF: PGMR0Trap0eHandlerNestedPaging returned %Rrc CS:RIP=%04x:%#RX64\n", rc, pCtx->cs.Sel, pCtx->rip));
5157
5158 /*
5159 * Same case as PGMR0Trap0eHandlerNPMisconfig(). See comment above, @bugref{6043}.
5160 */
5161 if ( rc == VINF_SUCCESS
5162 || rc == VERR_PAGE_TABLE_NOT_PRESENT
5163 || rc == VERR_PAGE_NOT_PRESENT)
5164 {
5165 /* We've successfully synced our shadow page tables. */
5166 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowPF);
5167 rc = VINF_SUCCESS;
5168 }
5169
5170 return rc;
5171}
5172
5173
5174/**
5175 * \#VMEXIT handler for virtual interrupt (SVM_EXIT_VINTR). Conditional
5176 * \#VMEXIT.
5177 */
5178HMSVM_EXIT_DECL hmR0SvmExitVIntr(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
5179{
5180 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
5181
5182 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
5183 pVmcb->ctrl.IntCtrl.n.u1VIrqValid = 0; /* No virtual interrupts pending, we'll inject the current one/NMI before reentry. */
5184 pVmcb->ctrl.IntCtrl.n.u8VIrqVector = 0;
5185
5186 /* Indicate that we no longer need to #VMEXIT when the guest is ready to receive interrupts/NMIs, it is now ready. */
5187 pVmcb->ctrl.u64InterceptCtrl &= ~SVM_CTRL_INTERCEPT_VINTR;
5188 pVmcb->ctrl.u64VmcbCleanBits &= ~(HMSVM_VMCB_CLEAN_INTERCEPTS | HMSVM_VMCB_CLEAN_TPR);
5189
5190 /* Deliver the pending interrupt/NMI via hmR0SvmEvaluatePendingEvent() and resume guest execution. */
5191 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIntWindow);
5192 return VINF_SUCCESS;
5193}
5194
5195
5196/**
5197 * \#VMEXIT handler for task switches (SVM_EXIT_TASK_SWITCH). Conditional
5198 * \#VMEXIT.
5199 */
5200HMSVM_EXIT_DECL hmR0SvmExitTaskSwitch(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
5201{
5202 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
5203
5204 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
5205
5206#ifndef HMSVM_ALWAYS_TRAP_TASK_SWITCH
5207 Assert(!pVCpu->CTX_SUFF(pVM)->hm.s.fNestedPaging);
5208#endif
5209
5210 /* Check if this task-switch occurred while delivering an event through the guest IDT. */
5211 if (pVCpu->hm.s.Event.fPending) /* Can happen with exceptions/NMI. See @bugref{8411}. */
5212 {
5213 /*
5214 * AMD-V provides us with the exception which caused the TS; we collect
5215 * the information in the call to hmR0SvmCheckExitDueToEventDelivery.
5216 */
5217 Log4(("hmR0SvmExitTaskSwitch: TS occurred during event delivery.\n"));
5218 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitTaskSwitch);
5219 return VINF_EM_RAW_INJECT_TRPM_EVENT;
5220 }
5221
5222 /** @todo Emulate task switch someday, currently just going back to ring-3 for
5223 * emulation. */
5224 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitTaskSwitch);
5225 return VERR_EM_INTERPRETER;
5226}
5227
5228
5229/**
5230 * \#VMEXIT handler for VMMCALL (SVM_EXIT_VMMCALL). Conditional \#VMEXIT.
5231 */
5232HMSVM_EXIT_DECL hmR0SvmExitVmmCall(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
5233{
5234 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
5235 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitVmcall);
5236
5237 /* First check if this is a patched VMMCALL for mov TPR */
5238 int rc = hmR0SvmEmulateMovTpr(pVCpu->CTX_SUFF(pVM), pVCpu, pCtx);
5239 if (rc == VINF_SUCCESS)
5240 {
5241 HMSVM_CHECK_SINGLE_STEP(pVCpu, rc);
5242 return VINF_SUCCESS;
5243 }
5244
5245 if (rc == VERR_NOT_FOUND)
5246 {
5247 if (pVCpu->hm.s.fHypercallsEnabled)
5248 {
5249 VBOXSTRICTRC rcStrict = GIMHypercall(pVCpu, pCtx);
5250 if (RT_SUCCESS(VBOXSTRICTRC_VAL(rcStrict)))
5251 {
5252 if (rcStrict == VINF_SUCCESS)
5253 hmR0SvmAdvanceRipHwAssist(pVCpu, pCtx, 3 /* cbInstr */);
5254 else
5255 Assert( rcStrict == VINF_GIM_HYPERCALL_CONTINUING
5256 || rcStrict == VINF_GIM_R3_HYPERCALL);
5257
5258 /* If the hypercall changes anything other than guest's general-purpose registers,
5259 we would need to reload the guest changed bits here before VM-entry. */
5260 }
5261 rc = VBOXSTRICTRC_VAL(rcStrict);
5262 }
5263 else
5264 Log4(("hmR0SvmExitVmmCall: Hypercalls not enabled\n"));
5265 }
5266
5267 /* If hypercalls are disabled or the hypercall failed for some reason, raise #UD and continue. */
5268 if (RT_FAILURE(rc))
5269 {
5270 hmR0SvmSetPendingXcptUD(pVCpu);
5271 rc = VINF_SUCCESS;
5272 }
5273
5274 return rc;
5275}
5276
5277
5278/**
5279 * \#VMEXIT handler for VMMCALL (SVM_EXIT_VMMCALL). Conditional \#VMEXIT.
5280 */
5281HMSVM_EXIT_DECL hmR0SvmExitPause(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
5282{
5283 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
5284 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitPause);
5285 return VINF_EM_RAW_INTERRUPT;
5286}
5287
5288
5289/**
5290 * \#VMEXIT handler for IRET (SVM_EXIT_IRET). Conditional \#VMEXIT.
5291 */
5292HMSVM_EXIT_DECL hmR0SvmExitIret(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
5293{
5294 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
5295
5296 /* Clear NMI blocking. */
5297 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_BLOCK_NMIS);
5298
5299 /* Indicate that we no longer need to #VMEXIT when the guest is ready to receive NMIs, it is now ready. */
5300 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
5301 hmR0SvmClearIretIntercept(pVmcb);
5302
5303 /* Deliver the pending NMI via hmR0SvmEvaluatePendingEvent() and resume guest execution. */
5304 return VINF_SUCCESS;
5305}
5306
5307
5308/**
5309 * \#VMEXIT handler for page-fault exceptions (SVM_EXIT_EXCEPTION_E).
5310 * Conditional \#VMEXIT.
5311 */
5312HMSVM_EXIT_DECL hmR0SvmExitXcptPF(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
5313{
5314 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
5315
5316 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
5317
5318 /* See AMD spec. 15.12.15 "#PF (Page Fault)". */
5319 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
5320 uint32_t u32ErrCode = pVmcb->ctrl.u64ExitInfo1;
5321 RTGCUINTPTR uFaultAddress = pVmcb->ctrl.u64ExitInfo2;
5322 PVM pVM = pVCpu->CTX_SUFF(pVM);
5323
5324#if defined(HMSVM_ALWAYS_TRAP_ALL_XCPTS) || defined(HMSVM_ALWAYS_TRAP_PF)
5325 if (pVM->hm.s.fNestedPaging)
5326 {
5327 pVCpu->hm.s.Event.fPending = false; /* In case it's a contributory or vectoring #PF. */
5328 if (!pSvmTransient->fVectoringDoublePF)
5329 {
5330 /* A genuine guest #PF, reflect it to the guest. */
5331 hmR0SvmSetPendingXcptPF(pVCpu, pCtx, u32ErrCode, uFaultAddress);
5332 Log4(("#PF: Guest page fault at %04X:%RGv FaultAddr=%RGv ErrCode=%#x\n", pCtx->cs.Sel, (RTGCPTR)pCtx->rip,
5333 uFaultAddress, u32ErrCode));
5334 }
5335 else
5336 {
5337 /* A guest page-fault occurred during delivery of a page-fault. Inject #DF. */
5338 hmR0SvmSetPendingXcptDF(pVCpu);
5339 Log4(("Pending #DF due to vectoring #PF. NP\n"));
5340 }
5341 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestPF);
5342 return VINF_SUCCESS;
5343 }
5344#endif
5345
5346 Assert(!pVM->hm.s.fNestedPaging);
5347
5348#ifdef VBOX_HM_WITH_GUEST_PATCHING
5349 /* Shortcut for APIC TPR reads and writes; only applicable to 32-bit guests. */
5350 if ( pVM->hm.s.fTprPatchingAllowed
5351 && (uFaultAddress & 0xfff) == XAPIC_OFF_TPR
5352 && !(u32ErrCode & X86_TRAP_PF_P) /* Not present. */
5353 && !CPUMIsGuestInLongModeEx(pCtx)
5354 && !CPUMGetGuestCPL(pVCpu)
5355 && pVM->hm.s.cPatches < RT_ELEMENTS(pVM->hm.s.aPatches))
5356 {
5357 RTGCPHYS GCPhysApicBase;
5358 GCPhysApicBase = APICGetBaseMsrNoCheck(pVCpu);
5359 GCPhysApicBase &= PAGE_BASE_GC_MASK;
5360
5361 /* Check if the page at the fault-address is the APIC base. */
5362 RTGCPHYS GCPhysPage;
5363 int rc2 = PGMGstGetPage(pVCpu, (RTGCPTR)uFaultAddress, NULL /* pfFlags */, &GCPhysPage);
5364 if ( rc2 == VINF_SUCCESS
5365 && GCPhysPage == GCPhysApicBase)
5366 {
5367 /* Only attempt to patch the instruction once. */
5368 PHMTPRPATCH pPatch = (PHMTPRPATCH)RTAvloU32Get(&pVM->hm.s.PatchTree, (AVLOU32KEY)pCtx->eip);
5369 if (!pPatch)
5370 return VINF_EM_HM_PATCH_TPR_INSTR;
5371 }
5372 }
5373#endif
5374
5375 Log4(("#PF: uFaultAddress=%#RX64 CS:RIP=%#04x:%#RX64 u32ErrCode %#RX32 cr3=%#RX64\n", uFaultAddress, pCtx->cs.Sel,
5376 pCtx->rip, u32ErrCode, pCtx->cr3));
5377
5378 /* If it's a vectoring #PF, emulate injecting the original event injection as PGMTrap0eHandler() is incapable
5379 of differentiating between instruction emulation and event injection that caused a #PF. See @bugref{6607}. */
5380 if (pSvmTransient->fVectoringPF)
5381 {
5382 Assert(pVCpu->hm.s.Event.fPending);
5383 return VINF_EM_RAW_INJECT_TRPM_EVENT;
5384 }
5385
5386 TRPMAssertXcptPF(pVCpu, uFaultAddress, u32ErrCode);
5387 int rc = PGMTrap0eHandler(pVCpu, u32ErrCode, CPUMCTX2CORE(pCtx), (RTGCPTR)uFaultAddress);
5388
5389 Log4(("#PF rc=%Rrc\n", rc));
5390
5391 if (rc == VINF_SUCCESS)
5392 {
5393 /* Successfully synced shadow pages tables or emulated an MMIO instruction. */
5394 TRPMResetTrap(pVCpu);
5395 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowPF);
5396 HMCPU_CF_SET(pVCpu, HM_CHANGED_ALL_GUEST);
5397 return rc;
5398 }
5399 else if (rc == VINF_EM_RAW_GUEST_TRAP)
5400 {
5401 pVCpu->hm.s.Event.fPending = false; /* In case it's a contributory or vectoring #PF. */
5402
5403 if (!pSvmTransient->fVectoringDoublePF)
5404 {
5405 /* It's a guest page fault and needs to be reflected to the guest. */
5406 u32ErrCode = TRPMGetErrorCode(pVCpu); /* The error code might have been changed. */
5407 TRPMResetTrap(pVCpu);
5408 hmR0SvmSetPendingXcptPF(pVCpu, pCtx, u32ErrCode, uFaultAddress);
5409 }
5410 else
5411 {
5412 /* A guest page-fault occurred during delivery of a page-fault. Inject #DF. */
5413 TRPMResetTrap(pVCpu);
5414 hmR0SvmSetPendingXcptDF(pVCpu);
5415 Log4(("#PF: Pending #DF due to vectoring #PF\n"));
5416 }
5417
5418 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestPF);
5419 return VINF_SUCCESS;
5420 }
5421
5422 TRPMResetTrap(pVCpu);
5423 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowPFEM);
5424 return rc;
5425}
5426
5427
5428/**
5429 * \#VMEXIT handler for device-not-available exceptions (SVM_EXIT_EXCEPTION_7).
5430 * Conditional \#VMEXIT.
5431 */
5432HMSVM_EXIT_DECL hmR0SvmExitXcptNM(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
5433{
5434 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
5435
5436 /* Paranoia; Ensure we cannot be called as a result of event delivery. */
5437 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb; NOREF(pVmcb);
5438 Assert(!pVmcb->ctrl.ExitIntInfo.n.u1Valid);
5439
5440 /* We're playing with the host CPU state here, make sure we don't preempt or longjmp. */
5441 VMMRZCallRing3Disable(pVCpu);
5442 HM_DISABLE_PREEMPT();
5443
5444 int rc;
5445 /* If the guest FPU was active at the time of the #NM exit, then it's a guest fault. */
5446 if (pSvmTransient->fWasGuestFPUStateActive)
5447 {
5448 rc = VINF_EM_RAW_GUEST_TRAP;
5449 Assert(CPUMIsGuestFPUStateActive(pVCpu) || HMCPU_CF_IS_PENDING(pVCpu, HM_CHANGED_GUEST_CR0));
5450 }
5451 else
5452 {
5453#ifndef HMSVM_ALWAYS_TRAP_ALL_XCPTS
5454 Assert(!pSvmTransient->fWasGuestFPUStateActive);
5455#endif
5456 rc = CPUMR0Trap07Handler(pVCpu->CTX_SUFF(pVM), pVCpu); /* (No need to set HM_CHANGED_HOST_CONTEXT for SVM.) */
5457 Assert( rc == VINF_EM_RAW_GUEST_TRAP
5458 || ((rc == VINF_SUCCESS || rc == VINF_CPUM_HOST_CR0_MODIFIED) && CPUMIsGuestFPUStateActive(pVCpu)));
5459 }
5460
5461 HM_RESTORE_PREEMPT();
5462 VMMRZCallRing3Enable(pVCpu);
5463
5464 if (rc == VINF_SUCCESS || rc == VINF_CPUM_HOST_CR0_MODIFIED)
5465 {
5466 /* Guest FPU state was activated, we'll want to change CR0 FPU intercepts before the next VM-reentry. */
5467 HMCPU_CF_SET(pVCpu, HM_CHANGED_GUEST_CR0);
5468 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowNM);
5469 pVCpu->hm.s.fPreloadGuestFpu = true;
5470 }
5471 else
5472 {
5473 /* Forward #NM to the guest. */
5474 Assert(rc == VINF_EM_RAW_GUEST_TRAP);
5475 hmR0SvmSetPendingXcptNM(pVCpu);
5476 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestNM);
5477 }
5478 return VINF_SUCCESS;
5479}
5480
5481
5482/**
5483 * \#VMEXIT handler for undefined opcode (SVM_EXIT_EXCEPTION_6).
5484 * Conditional \#VMEXIT.
5485 */
5486HMSVM_EXIT_DECL hmR0SvmExitXcptUD(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
5487{
5488 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
5489
5490 /* Paranoia; Ensure we cannot be called as a result of event delivery. */
5491 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb; NOREF(pVmcb);
5492 Assert(!pVmcb->ctrl.ExitIntInfo.n.u1Valid);
5493
5494 int rc = VERR_SVM_UNEXPECTED_XCPT_EXIT;
5495 if (pVCpu->hm.s.fGIMTrapXcptUD)
5496 {
5497 uint8_t cbInstr = 0;
5498 VBOXSTRICTRC rcStrict = GIMXcptUD(pVCpu, pCtx, NULL /* pDis */, &cbInstr);
5499 if (rcStrict == VINF_SUCCESS)
5500 {
5501 /* #UD #VMEXIT does not have valid NRIP information, manually advance RIP. See @bugref{7270#c170}. */
5502 hmR0SvmAdvanceRipDumb(pVCpu, pCtx, cbInstr);
5503 rc = VINF_SUCCESS;
5504 }
5505 else if (rcStrict == VINF_GIM_HYPERCALL_CONTINUING)
5506 rc = VINF_SUCCESS;
5507 else if (rcStrict == VINF_GIM_R3_HYPERCALL)
5508 rc = VINF_GIM_R3_HYPERCALL;
5509 else
5510 Assert(RT_FAILURE(VBOXSTRICTRC_VAL(rcStrict)));
5511 }
5512
5513 /* If the GIM #UD exception handler didn't succeed for some reason or wasn't needed, raise #UD. */
5514 if (RT_FAILURE(rc))
5515 {
5516 hmR0SvmSetPendingXcptUD(pVCpu);
5517 rc = VINF_SUCCESS;
5518 }
5519
5520 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestUD);
5521 return rc;
5522}
5523
5524
5525/**
5526 * \#VMEXIT handler for math-fault exceptions (SVM_EXIT_EXCEPTION_10).
5527 * Conditional \#VMEXIT.
5528 */
5529HMSVM_EXIT_DECL hmR0SvmExitXcptMF(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
5530{
5531 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
5532
5533 /* Paranoia; Ensure we cannot be called as a result of event delivery. */
5534 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb; NOREF(pVmcb);
5535 Assert(!pVmcb->ctrl.ExitIntInfo.n.u1Valid);
5536
5537 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestMF);
5538
5539 if (!(pCtx->cr0 & X86_CR0_NE))
5540 {
5541 PVM pVM = pVCpu->CTX_SUFF(pVM);
5542 PDISSTATE pDis = &pVCpu->hm.s.DisState;
5543 unsigned cbOp;
5544 int rc = EMInterpretDisasCurrent(pVM, pVCpu, pDis, &cbOp);
5545 if (RT_SUCCESS(rc))
5546 {
5547 /* Convert a #MF into a FERR -> IRQ 13. See @bugref{6117}. */
5548 rc = PDMIsaSetIrq(pVCpu->CTX_SUFF(pVM), 13, 1, 0 /* uTagSrc */);
5549 if (RT_SUCCESS(rc))
5550 pCtx->rip += cbOp;
5551 }
5552 else
5553 Log4(("hmR0SvmExitXcptMF: EMInterpretDisasCurrent returned %Rrc uOpCode=%#x\n", rc, pDis->pCurInstr->uOpcode));
5554 return rc;
5555 }
5556
5557 hmR0SvmSetPendingXcptMF(pVCpu);
5558 return VINF_SUCCESS;
5559}
5560
5561
5562/**
5563 * \#VMEXIT handler for debug exceptions (SVM_EXIT_EXCEPTION_1). Conditional
5564 * \#VMEXIT.
5565 */
5566HMSVM_EXIT_DECL hmR0SvmExitXcptDB(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
5567{
5568 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
5569
5570 /* If this #DB is the result of delivering an event, go back to the interpreter. */
5571 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
5572 if (RT_UNLIKELY(pVCpu->hm.s.Event.fPending))
5573 {
5574 STAM_COUNTER_INC(&pVCpu->hm.s.StatInjectPendingInterpret);
5575 return VERR_EM_INTERPRETER;
5576 }
5577
5578 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitGuestDB);
5579
5580 /* This can be a fault-type #DB (instruction breakpoint) or a trap-type #DB (data breakpoint). However, for both cases
5581 DR6 and DR7 are updated to what the exception handler expects. See AMD spec. 15.12.2 "#DB (Debug)". */
5582 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
5583 PVM pVM = pVCpu->CTX_SUFF(pVM);
5584 int rc = DBGFRZTrap01Handler(pVM, pVCpu, CPUMCTX2CORE(pCtx), pVmcb->guest.u64DR6, pVCpu->hm.s.fSingleInstruction);
5585 if (rc == VINF_EM_RAW_GUEST_TRAP)
5586 {
5587 Log5(("hmR0SvmExitXcptDB: DR6=%#RX64 -> guest trap\n", pVmcb->guest.u64DR6));
5588 if (CPUMIsHyperDebugStateActive(pVCpu))
5589 CPUMSetGuestDR6(pVCpu, CPUMGetGuestDR6(pVCpu) | pVmcb->guest.u64DR6);
5590
5591 /* Reflect the exception back to the guest. */
5592 hmR0SvmSetPendingXcptDB(pVCpu);
5593 rc = VINF_SUCCESS;
5594 }
5595
5596 /*
5597 * Update DR6.
5598 */
5599 if (CPUMIsHyperDebugStateActive(pVCpu))
5600 {
5601 Log5(("hmR0SvmExitXcptDB: DR6=%#RX64 -> %Rrc\n", pVmcb->guest.u64DR6, rc));
5602 pVmcb->guest.u64DR6 = X86_DR6_INIT_VAL;
5603 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_DRX;
5604 }
5605 else
5606 {
5607 AssertMsg(rc == VINF_SUCCESS, ("rc=%Rrc\n", rc));
5608 Assert(!pVCpu->hm.s.fSingleInstruction && !DBGFIsStepping(pVCpu));
5609 }
5610
5611 return rc;
5612}
5613
5614
5615/**
5616 * \#VMEXIT handler for alignment check exceptions (SVM_EXIT_EXCEPTION_11).
5617 * Conditional \#VMEXIT.
5618 */
5619HMSVM_EXIT_DECL hmR0SvmExitXcptAC(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
5620{
5621 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
5622
5623 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
5624
5625 SVMEVENT Event;
5626 Event.u = 0;
5627 Event.n.u1Valid = 1;
5628 Event.n.u3Type = SVM_EVENT_EXCEPTION;
5629 Event.n.u8Vector = X86_XCPT_AC;
5630 Event.n.u1ErrorCodeValid = 1;
5631 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
5632 return VINF_SUCCESS;
5633}
5634
5635
5636/**
5637 * \#VMEXIT handler for breakpoint exceptions (SVM_EXIT_EXCEPTION_3).
5638 * Conditional \#VMEXIT.
5639 */
5640HMSVM_EXIT_DECL hmR0SvmExitXcptBP(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
5641{
5642 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
5643
5644 HMSVM_CHECK_EXIT_DUE_TO_EVENT_DELIVERY();
5645
5646 int rc = DBGFRZTrap03Handler(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx));
5647 if (rc == VINF_EM_RAW_GUEST_TRAP)
5648 {
5649 SVMEVENT Event;
5650 Event.u = 0;
5651 Event.n.u1Valid = 1;
5652 Event.n.u3Type = SVM_EVENT_EXCEPTION;
5653 Event.n.u8Vector = X86_XCPT_BP;
5654 Event.n.u1ErrorCodeValid = 0;
5655 hmR0SvmSetPendingEvent(pVCpu, &Event, 0 /* GCPtrFaultAddress */);
5656 }
5657
5658 Assert(rc == VINF_SUCCESS || rc == VINF_EM_RAW_GUEST_TRAP || rc == VINF_EM_DBG_BREAKPOINT);
5659 return rc;
5660}
5661
5662
5663#ifdef VBOX_WITH_NESTED_HWVIRT
5664/**
5665 * \#VMEXIT handler for CLGI (SVM_EXIT_CLGI). Conditional \#VMEXIT.
5666 */
5667HMSVM_EXIT_DECL hmR0SvmExitClgi(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
5668{
5669 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
5670 /** @todo Stat. */
5671 /* STAM_COUNTER_INC(&pVCpu->hm.s.StatExitClgi); */
5672 VBOXSTRICTRC rcStrict = IEMExecDecodedClgi(pVCpu, 3);
5673 return VBOXSTRICTRC_VAL(rcStrict);
5674}
5675
5676
5677/**
5678 * \#VMEXIT handler for STGI (SVM_EXIT_STGI). Conditional \#VMEXIT.
5679 */
5680HMSVM_EXIT_DECL hmR0SvmExitStgi(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
5681{
5682 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
5683 /** @todo Stat. */
5684 /* STAM_COUNTER_INC(&pVCpu->hm.s.StatExitStgi); */
5685 VBOXSTRICTRC rcStrict = IEMExecDecodedStgi(pVCpu, 3);
5686 return VBOXSTRICTRC_VAL(rcStrict);
5687}
5688
5689
5690/**
5691 * \#VMEXIT handler for VMLOAD (SVM_EXIT_VMLOAD). Conditional \#VMEXIT.
5692 */
5693HMSVM_EXIT_DECL hmR0SvmExitVmload(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
5694{
5695 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
5696 /** @todo Stat. */
5697 /* STAM_COUNTER_INC(&pVCpu->hm.s.StatExitVmload); */
5698 VBOXSTRICTRC rcStrict = IEMExecDecodedVmload(pVCpu, 3);
5699 return VBOXSTRICTRC_VAL(rcStrict);
5700}
5701
5702
5703/**
5704 * \#VMEXIT handler for VMSAVE (SVM_EXIT_VMSAVE). Conditional \#VMEXIT.
5705 */
5706HMSVM_EXIT_DECL hmR0SvmExitVmsave(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
5707{
5708 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
5709 /** @todo Stat. */
5710 /* STAM_COUNTER_INC(&pVCpu->hm.s.StatExitVmsave); */
5711 VBOXSTRICTRC rcStrict = IEMExecDecodedVmsave(pVCpu, 3);
5712 return VBOXSTRICTRC_VAL(rcStrict);
5713}
5714#endif /* VBOX_WITH_NESTED_HWVIRT */
5715
5716
5717/** @} */
5718
Note: See TracBrowser for help on using the repository browser.

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