VirtualBox

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

Last change on this file since 46596 was 46594, checked in by vboxsync, 12 years ago

VMM/HMSVMR0: AMD-V bits.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 138.9 KB
Line 
1/* $Id: HMSVMR0.cpp 46594 2013-06-17 14:35:56Z vboxsync $ */
2/** @file
3 * HM SVM (AMD-V) - Host Context Ring-0.
4 */
5
6/*
7 * Copyright (C) 2013 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* Header Files *
20*******************************************************************************/
21
22#ifdef DEBUG_ramshankar
23# define HMSVM_ALWAYS_TRAP_ALL_XCPTS
24# define HMSVM_ALWAYS_TRAP_PF
25#endif
26
27
28/*******************************************************************************
29* Defined Constants And Macros *
30*******************************************************************************/
31#ifdef VBOX_WITH_STATISTICS
32# define HMSVM_EXITCODE_STAM_COUNTER_INC(u64ExitCode) do { \
33 if ((u64ExitCode) == SVM_EXIT_NPF) \
34 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitReasonNpf); \
35 else \
36 STAM_COUNTER_INC(&pVCpu->hm.s.paStatExitReasonR0[(u64ExitCode) & MASK_EXITREASON_STAT]); \
37 } while (0)
38#else
39# define HMSVM_EXITCODE_STAM_COUNTER_INC(u64ExitCode) do { } while (0)
40#endif
41
42/** If we decide to use a function table approach this can be useful to
43 * switch to a "static DECLCALLBACK(int)". */
44#define HMSVM_EXIT_DECL static int
45
46/** @name Segment attribute conversion between CPU and AMD-V VMCB format.
47 *
48 * The CPU format of the segment attribute is described in X86DESCATTRBITS
49 * which is 16-bits (i.e. includes 4 bits of the segment limit).
50 *
51 * The AMD-V VMCB format the segment attribute is compact 12-bits (strictly
52 * only the attribute bits and nothing else). Upper 4-bits are unused.
53 *
54 * @{ */
55#define HMSVM_CPU_2_VMCB_SEG_ATTR(a) (a & 0xff) | ((a & 0xf000) >> 4)
56#define HMSVM_VMCB_2_CPU_SEG_ATTR(a) (a & 0xff) | ((a & 0x0f00) << 4)
57/** @} */
58
59/** @name Macros for loading, storing segment registers to/from the VMCB.
60 * @{ */
61#define HMSVM_LOAD_SEG_REG(REG, reg) \
62 do \
63 { \
64 Assert(pCtx->reg.fFlags & CPUMSELREG_FLAGS_VALID); \
65 Assert(pCtx->reg.ValidSel == pCtx->reg.Sel); \
66 pVmcb->guest.REG.u16Sel = pCtx->reg.Sel; \
67 pVmcb->guest.REG.u32Limit = pCtx->reg.u32Limit; \
68 pVmcb->guest.REG.u64Base = pCtx->reg.u64Base; \
69 pVmcb->guest.REG.u16Attr = HMSVM_CPU_2_VMCB_SEG_ATTR(pCtx->reg.Attr.u); \
70 } while (0)
71
72#define HMSVM_SAVE_SEG_REG(REG, reg) \
73 do \
74 { \
75 pCtx->reg.Sel = pVmcb->guest.REG.u16Sel; \
76 pCtx->reg.ValidSel = pVmcb->guest.REG.u16Sel; \
77 pCtx->reg.fFlags = CPUMSELREG_FLAGS_VALID; \
78 pCtx->reg.u32Limit = pVmcb->guest.REG.u32Limit; \
79 pCtx->reg.u64Base = pVmcb->guest.REG.u64Base; \
80 pCtx->reg.Attr.u = HMSVM_VMCB_2_CPU_SEG_ATTR(pVmcb->guest.REG.u16Attr); \
81 } while (0)
82/** @} */
83
84/** @name VMCB Clean Bits.
85 *
86 * These flags are used for VMCB-state caching. A set VMCB Clean Bit indicates
87 * AMD-V doesn't need to reload the corresponding value(s) from the VMCB in
88 * memory.
89 *
90 * @{ */
91/** All intercepts vectors, TSC offset, PAUSE filter counter. */
92#define HMSVM_VMCB_CLEAN_INTERCEPTS RT_BIT(0)
93/** I/O permission bitmap, MSR permission bitmap. */
94#define HMSVM_VMCB_CLEAN_IOPM_MSRPM RT_BIT(1)
95/** ASID. */
96#define HMSVM_VMCB_CLEAN_ASID RT_BIT(2)
97/** TRP: V_TPR, V_IRQ, V_INTR_PRIO, V_IGN_TPR, V_INTR_MASKING,
98V_INTR_VECTOR. */
99#define HMSVM_VMCB_CLEAN_TPR RT_BIT(3)
100/** Nested Paging: Nested CR3 (nCR3), PAT. */
101#define HMSVM_VMCB_CLEAN_NP RT_BIT(4)
102/** Control registers (CR0, CR3, CR4, EFER). */
103#define HMSVM_VMCB_CLEAN_CRX_EFER RT_BIT(5)
104/** Debug registers (DR6, DR7). */
105#define HMSVM_VMCB_CLEAN_DRX RT_BIT(6)
106/** GDT, IDT limit and base. */
107#define HMSVM_VMCB_CLEAN_DT RT_BIT(7)
108/** Segment register: CS, SS, DS, ES limit and base. */
109#define HMSVM_VMCB_CLEAN_SEG RT_BIT(8)
110/** CR2.*/
111#define HMSVM_VMCB_CLEAN_CR2 RT_BIT(9)
112/** Last-branch record (DbgCtlMsr, br_from, br_to, lastint_from, lastint_to) */
113#define HMSVM_VMCB_CLEAN_LBR RT_BIT(10)
114/** AVIC (AVIC APIC_BAR; AVIC APIC_BACKING_PAGE, AVIC
115PHYSICAL_TABLE and AVIC LOGICAL_TABLE Pointers). */
116#define HMSVM_VMCB_CLEAN_AVIC RT_BIT(11)
117/** Mask of all valid VMCB Clean bits. */
118#define HMSVM_VMCB_CLEAN_ALL ( HMSVM_VMCB_CLEAN_INTERCEPTS
119 | HMSVM_VMCB_CLEAN_IOPM_MSRPM
120 | HMSVM_VMCB_CLEAN_ASID
121 | HMSVM_VMCB_CLEAN_TPR
122 | HMSVM_VMCB_CLEAN_NP
123 | HMSVM_VMCB_CLEAN_CRX
124 | HMSVM_VMCB_CLEAN_DRX
125 | HMSVM_VMCB_CLEAN_DT
126 | HMSVM_VMCB_CLEAN_SEG
127 | HMSVM_VMCB_CLEAN_CR2
128 | HMSVM_VMCB_CLEAN_LBR
129 | HMSVM_VMCB_CLEAN_AVIC)
130/** @} */
131
132/** @name SVM transient.
133 *
134 * A state structure for holding miscellaneous information across AMD-V
135 * VMRUN/#VMEXIT operation, restored after the transition.
136 *
137 * @{ */
138typedef struct SVMTRANSIENT
139{
140 /** The host's rflags/eflags. */
141 RTCCUINTREG uEFlags;
142#if HC_ARCH_BITS == 32
143 uint32_t u32Alignment0;
144#endif
145
146 /** The #VMEXIT exit code (the EXITCODE field in the VMCB). */
147 uint64_t u64ExitCode;
148 /** The guest's TPR value used for TPR shadowing. */
149 uint8_t u8GuestTpr;
150} SVMTRANSIENT, *PSVMTRANSIENT;
151/** @} */
152
153
154/**
155 * MSRPM (MSR permission bitmap) read permissions (for guest RDMSR).
156 */
157typedef enum SVMMSREXITREAD
158{
159 /** Reading this MSR causes a VM-exit. */
160 SVMMSREXIT_INTERCEPT_READ = 0xb,
161 /** Reading this MSR does not cause a VM-exit. */
162 SVMMSREXIT_PASSTHRU_READ
163} SVMMSREXITREAD;
164
165/**
166 * MSRPM (MSR permission bitmap) write permissions (for guest WRMSR).
167 */
168typedef enum SVMMSREXITWRITE
169{
170 /** Writing to this MSR causes a VM-exit. */
171 SVMMSREXIT_INTERCEPT_WRITE = 0xd,
172 /** Writing to this MSR does not cause a VM-exit. */
173 SVMMSREXIT_PASSTHRU_WRITE
174} SVMMSREXITWRITE;
175
176
177/*******************************************************************************
178* Internal Functions *
179*******************************************************************************/
180static void hmR0SvmSetMsrPermission(PVMCPU pVCpu, unsigned uMsr, SVMMSREXITREAD enmRead, SVMMSREXITWRITE enmWrite);
181
182DECLINLINE(int) hmR0SvmHandleExit(PVMCPU pVCpu, PCPUMCTX pMixedCtx, PSVMTRANSIENT pSvmTransient);
183
184
185/*******************************************************************************
186* Global Variables *
187*******************************************************************************/
188/** Ring-0 memory object for the IO bitmap. */
189RTR0MEMOBJ g_hMemObjIOBitmap = NIL_RTR0MEMOBJ;
190/** Physical address of the IO bitmap. */
191RTHCPHYS g_HCPhysIOBitmap = 0;
192/** Virtual address of the IO bitmap. */
193R0PTRTYPE(void *) g_pvIOBitmap = NULL;
194
195
196/**
197 * Sets up and activates AMD-V on the current CPU.
198 *
199 * @returns VBox status code.
200 * @param pCpu Pointer to the CPU info struct.
201 * @param pVM Pointer to the VM (can be NULL after a resume!).
202 * @param pvCpuPage Pointer to the global CPU page.
203 * @param HCPhysCpuPage Physical address of the global CPU page.
204 */
205VMMR0DECL(int) SVMR0EnableCpu(PHMGLOBLCPUINFO pCpu, PVM pVM, void *pvCpuPage, RTHCPHYS HCPhysCpuPage, bool fEnabledByHost)
206{
207 AssertReturn(!fEnabledByHost, VERR_INVALID_PARAMETER);
208 AssertReturn( HCPhysCpuPage
209 && HCPhysCpuPage != NIL_RTHCPHYS, VERR_INVALID_PARAMETER);
210 AssertReturn(pvCpuPage, VERR_INVALID_PARAMETER);
211
212 /*
213 * We must turn on AMD-V and setup the host state physical address, as those MSRs are per CPU.
214 */
215 uint64_t u64HostEfer = ASMRdMsr(MSR_K6_EFER);
216 if (u64HostEfer & MSR_K6_EFER_SVME)
217 {
218 /* If the VBOX_HWVIRTEX_IGNORE_SVM_IN_USE is active, then we blindly use AMD-V. */
219 if ( pVM
220 && pVM->hm.s.svm.fIgnoreInUseError)
221 {
222 pCpu->fIgnoreAMDVInUseError = true;
223 }
224
225 if (!pCpu->fIgnoreAMDVInUseError)
226 return VERR_SVM_IN_USE;
227 }
228
229 /* Turn on AMD-V in the EFER MSR. */
230 ASMWrMsr(MSR_K6_EFER, u64HostEfer | MSR_K6_EFER_SVME);
231
232 /* Write the physical page address where the CPU will store the host state while executing the VM. */
233 ASMWrMsr(MSR_K8_VM_HSAVE_PA, HCPhysCpuPage);
234
235 /*
236 * Theoretically, other hypervisors may have used ASIDs, ideally we should flush all non-zero ASIDs
237 * when enabling SVM. AMD doesn't have an SVM instruction to flush all ASIDs (flushing is done
238 * upon VMRUN). Therefore, just set the fFlushAsidBeforeUse flag which instructs hmR0SvmSetupTLB()
239 * to flush the TLB with before using a new ASID.
240 */
241 pCpu->fFlushAsidBeforeUse = true;
242
243 /*
244 * Ensure each VCPU scheduled on this CPU gets a new VPID on resume. See @bugref{6255}.
245 */
246 ++pCpu->cTlbFlushes;
247
248 return VINF_SUCCESS;
249}
250
251
252/**
253 * Deactivates AMD-V on the current CPU.
254 *
255 * @returns VBox status code.
256 * @param pCpu Pointer to the CPU info struct.
257 * @param pvCpuPage Pointer to the global CPU page.
258 * @param HCPhysCpuPage Physical address of the global CPU page.
259 */
260VMMR0DECL(int) SVMR0DisableCpu(PHMGLOBLCPUINFO pCpu, void *pvCpuPage, RTHCPHYS HCPhysCpuPage)
261{
262 AssertReturn( HCPhysCpuPage
263 && HCPhysCpuPage != NIL_RTHCPHYS, VERR_INVALID_PARAMETER);
264 AssertReturn(pvCpuPage, VERR_INVALID_PARAMETER);
265 NOREF(pCpu);
266
267 /* Turn off AMD-V in the EFER MSR if AMD-V is active. */
268 uint64_t u64HostEfer = ASMRdMsr(MSR_K6_EFER);
269 if (u64HostEfer & MSR_K6_EFER_SVME)
270 {
271 ASMWrMsr(MSR_K6_EFER, u64HostEfer & ~MSR_K6_EFER_SVME);
272
273 /* Invalidate host state physical address. */
274 ASMWrMsr(MSR_K8_VM_HSAVE_PA, 0);
275 }
276
277 return VINF_SUCCESS;
278}
279
280
281/**
282 * Does global AMD-V initialization (called during module initialization).
283 *
284 * @returns VBox status code.
285 */
286VMMR0DECL(int) SVMR0GlobalInit(void)
287{
288 /*
289 * Allocate 12 KB for the IO bitmap. Since this is non-optional and we always intercept all IO accesses, it's done
290 * once globally here instead of per-VM.
291 */
292 int rc = RTR0MemObjAllocCont(&g_hMemObjIOBitmap, 3 << PAGE_SHIFT, false /* fExecutable */);
293 if (RT_FAILURE(rc))
294 return rc;
295
296 g_pvIOBitmap = RTR0MemObjAddress(g_hMemObjIOBitmap);
297 g_HCPhysIOBitmap = RTR0MemObjGetPagePhysAddr(g_hMemObjIOBitmap, 0 /* iPage */);
298
299 /* Set all bits to intercept all IO accesses. */
300 ASMMemFill32(pVM->hm.s.svm.pvIOBitmap, 3 << PAGE_SHIFT, UINT32_C(0xffffffff));
301}
302
303
304/**
305 * Does global VT-x termination (called during module termination).
306 */
307VMMR0DECL(void) SVMR0GlobalTerm(void)
308{
309 if (g_hMemObjIOBitmap != NIL_RTR0MEMOBJ)
310 {
311 RTR0MemObjFree(pVM->hm.s.svm.hMemObjIOBitmap, false /* fFreeMappings */);
312 g_pvIOBitmap = NULL;
313 g_HCPhysIOBitmap = 0;
314 g_hMemObjIOBitmap = NIL_RTR0MEMOBJ;
315 }
316}
317
318
319/**
320 * Frees any allocated per-VCPU structures for a VM.
321 *
322 * @param pVM Pointer to the VM.
323 */
324DECLINLINE(void) hmR0SvmFreeStructs(PVM pVM)
325{
326 for (uint32_t i = 0; i < pVM->cCpus; i++)
327 {
328 PVMCPU pVCpu = &pVM->aCpus[i];
329 AssertPtr(pVCpu);
330
331 if (pVCpu->hm.s.svm.hMemObjVmcbHost != NIL_RTR0MEMOBJ)
332 {
333 RTR0MemObjFree(pVCpu->hm.s.svm.hMemObjVmcbHost, false);
334 pVCpu->hm.s.svm.pvVmcbHost = 0;
335 pVCpu->hm.s.svm.HCPhysVmcbHost = 0;
336 pVCpu->hm.s.svm.hMemObjVmcbHost = NIL_RTR0MEMOBJ;
337 }
338
339 if (pVCpu->hm.s.svm.hMemObjVmcb != NIL_RTR0MEMOBJ)
340 {
341 RTR0MemObjFree(pVCpu->hm.s.svm.hMemObjVmcb, false);
342 pVCpu->hm.s.svm.pvVmcb = 0;
343 pVCpu->hm.s.svm.HCPhysVmcb = 0;
344 pVCpu->hm.s.svm.hMemObjVmcb = NIL_RTR0MEMOBJ;
345 }
346
347 if (pVCpu->hm.s.svm.hMemObjMsrBitmap != NIL_RTR0MEMOBJ)
348 {
349 RTR0MemObjFree(pVCpu->hm.s.svm.hMemObjMsrBitmap, false);
350 pVCpu->hm.s.svm.pvMsrBitmap = 0;
351 pVCpu->hm.s.svm.HCPhysMsrBitmap = 0;
352 pVCpu->hm.s.svm.hMemObjMsrBitmap = NIL_RTR0MEMOBJ;
353 }
354 }
355}
356
357
358/**
359 * Does per-VM AMD-V initialization.
360 *
361 * @returns VBox status code.
362 * @param pVM Pointer to the VM.
363 */
364VMMR0DECL(int) SVMR0InitVM(PVM pVM)
365{
366 int rc = VERR_INTERNAL_ERROR_5;
367
368 /*
369 * Check for an AMD CPU erratum which requires us to flush the TLB before every world-switch.
370 */
371 uint32_t u32Family;
372 uint32_t u32Model;
373 uint32_t u32Stepping;
374 if (HMAmdIsSubjectToErratum170(&u32Family, &u32Model, &u32Stepping))
375 {
376 Log4(("SVMR0InitVM: AMD cpu with erratum 170 family %#x model %#x stepping %#x\n", u32Family, u32Model, u32Stepping));
377 pVM->hm.s.svm.fAlwaysFlushTLB = true;
378 }
379
380 /*
381 * Initialize the R0 memory objects up-front so we can properly cleanup on allocation failures.
382 */
383 for (VMCPUID i = 0; i < pVM->cCpus; i++)
384 {
385 PVMCPU pVCpu = &pVM->aCpus[i];
386 pVCpu->hm.s.svm.hMemObjVmcbHost = NIL_RTR0MEMOBJ;
387 pVCpu->hm.s.svm.hMemObjVmcb = NIL_RTR0MEMOBJ;
388 pVCpu->hm.s.svm.hMemObjMsrBitmap = NIL_RTR0MEMOBJ;
389 }
390
391 for (VMCPUID i = 0; i < pVM->cCpus; i++)
392 {
393 /*
394 * Allocate one page for the host-context VM control block (VMCB). This is used for additional host-state (such as
395 * FS, GS, Kernel GS Base, etc.) apart from the host-state save area specified in MSR_K8_VM_HSAVE_PA.
396 */
397 rc = RTR0MemObjAllocCont(&pVCpu->hm.s.svm.hMemObjVmcbHost, 1 << PAGE_SHIFT, false /* fExecutable */);
398 if (RT_FAILURE(rc))
399 goto failure_cleanup;
400
401 pVCpu->hm.s.svm.pvVmcbHost = RTR0MemObjAddress(pVCpu->hm.s.svm.hMemObjVmcbHost);
402 pVCpu->hm.s.svm.HCPhysVmcbHost = RTR0MemObjGetPagePhysAddr(pVCpu->hm.s.svm.hMemObjVmcbHost, 0 /* iPage */);
403 Assert(pVCpu->hm.s.svm.HCPhysVmcbHost < _4G);
404 ASMMemZeroPage(pVCpu->hm.s.svm.pvVmcbHost);
405
406 /*
407 * Allocate one page for the guest-state VMCB.
408 */
409 rc = RTR0MemObjAllocCont(&pVCpu->hm.s.svm.hMemObjVmcb, 1 << PAGE_SHIFT, false /* fExecutable */);
410 if (RT_FAILURE(rc))
411 goto failure_cleanup;
412
413 pVCpu->hm.s.svm.pvVmcb = RTR0MemObjAddress(pVCpu->hm.s.svm.hMemObjVmcb);
414 pVCpu->hm.s.svm.HCPhysVmcb = RTR0MemObjGetPagePhysAddr(pVCpu->hm.s.svm.hMemObjVmcb, 0 /* iPage */);
415 Assert(pVCpu->hm.s.svm.HCPhysVmcb < _4G);
416 ASMMemZeroPage(pVCpu->hm.s.svm.pvVmcb);
417
418 /*
419 * Allocate two pages (8 KB) for the MSR permission bitmap. There doesn't seem to be a way to convince
420 * SVM to not require one.
421 */
422 rc = RTR0MemObjAllocCont(&pVCpu->hm.s.svm.hMemObjMsrBitmap, 2 << PAGE_SHIFT, false /* fExecutable */);
423 if (RT_FAILURE(rc))
424 failure_cleanup;
425
426 pVCpu->hm.s.svm.pvMsrBitmap = RTR0MemObjAddress(pVCpu->hm.s.svm.hMemObjMsrBitmap);
427 pVCpu->hm.s.svm.HCPhysMsrBitmap = RTR0MemObjGetPagePhysAddr(pVCpu->hm.s.svm.hMemObjMsrBitmap, 0 /* iPage */);
428 /* Set all bits to intercept all MSR accesses (changed later on). */
429 ASMMemFill32(pVCpu->hm.s.svm.pvMsrBitmap, 2 << PAGE_SHIFT, 0xffffffff);
430 }
431
432 return VINF_SUCCESS;
433
434failure_cleanup:
435 hmR0SvmFreeVMStructs(pVM);
436 return rc;
437}
438
439
440/**
441 * Does per-VM AMD-V termination.
442 *
443 * @returns VBox status code.
444 * @param pVM Pointer to the VM.
445 */
446VMMR0DECL(int) SVMR0TermVM(PVM pVM)
447{
448 hmR0SvmFreeVMStructs(pVM);
449 return VINF_SUCCESS;
450}
451
452
453/**
454 * Sets the permission bits for the specified MSR in the MSRPM.
455 *
456 * @param pVCpu Pointer to the VMCPU.
457 * @param uMsr The MSR for which the access permissions are being set.
458 * @param enmRead MSR read permissions.
459 * @param enmWrite MSR write permissions.
460 */
461static void hmR0SvmSetMsrPermission(PVMCPU pVCpu, uint32_t uMsr, SVMMSREXITREAD enmRead, SVMMSREXITWRITE enmWrite)
462{
463 unsigned ulBit;
464 uint8_t *pbMsrBitmap = (uint8_t *)pVCpu->hm.s.svm.pvMsrBitmap;
465
466 /*
467 * Layout:
468 * Byte offset MSR range
469 * 0x000 - 0x7ff 0x00000000 - 0x00001fff
470 * 0x800 - 0xfff 0xc0000000 - 0xc0001fff
471 * 0x1000 - 0x17ff 0xc0010000 - 0xc0011fff
472 * 0x1800 - 0x1fff Reserved
473 */
474 if (uMsr <= 0x00001FFF)
475 {
476 /* Pentium-compatible MSRs. */
477 ulBit = uMsr * 2;
478 }
479 else if ( uMsr >= 0xC0000000
480 && uMsr <= 0xC0001FFF)
481 {
482 /* AMD Sixth Generation x86 Processor MSRs. */
483 ulBit = (uMsr - 0xC0000000) * 2;
484 pbMsrBitmap += 0x800;
485 }
486 else if ( uMsr >= 0xC0010000
487 && uMsr <= 0xC0011FFF)
488 {
489 /* AMD Seventh and Eighth Generation Processor MSRs. */
490 ulBit = (uMsr - 0xC0001000) * 2;
491 pbMsrBitmap += 0x1000;
492 }
493 else
494 {
495 AssertFailed();
496 return;
497 }
498
499 Assert(ulBit < 0x3fff /* 16 * 1024 - 1 */);
500 if (enmRead == SVMMSREXIT_INTERCEPT_READ)
501 ASMBitSet(pbMsrBitmap, ulBit);
502 else
503 ASMBitClear(pbMsrBitmap, ulBit);
504
505 if (enmWrite == SVMMSREXIT_INTERCEPT_WRITE)
506 ASMBitSet(pbMsrBitmap, ulBit + 1);
507 else
508 ASMBitClear(pbMsrBitmap, ulBit + 1);
509
510 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_IOPM_MSRPM;
511}
512
513
514/**
515 * Sets up AMD-V for the specified VM.
516 * This function is only called once per-VM during initalization.
517 *
518 * @returns VBox status code.
519 * @param pVM Pointer to the VM.
520 */
521VMMR0DECL(int) SVMR0SetupVM(PVM pVM)
522{
523 int rc = VINF_SUCCESS;
524
525 AssertReturn(pVM, VERR_INVALID_PARAMETER);
526 Assert(pVM->hm.s.svm.fSupported);
527
528 for (VMCPUID i = 0; i < pVM->cCpus; i++)
529 {
530 PVMCPU pVCpu = &pVM->aCpus[i];
531 PSVMVMCB pVmcb = (PSVMVMCB)pVM->aCpus[i].hm.s.svm.pvVmcb;
532
533 AssertMsgReturn(pVmcb, ("Invalid pVmcb\n"), VERR_SVM_INVALID_PVMCB);
534
535 /* Trap exceptions unconditionally (debug purposes). */
536#ifdef HMSVM_ALWAYS_TRAP_PF
537 pVmcb->ctrl.u32InterceptException |= RT_BIT(X86_XCPT_PF);
538#endif
539#ifdef HMSVM_ALWAYS_TRAP_ALL_XCPTS
540 pVmcb->ctrl.u32InterceptException |= RT_BIT(X86_XCPT_BP)
541 | RT_BIT(X86_XCPT_DB)
542 | RT_BIT(X86_XCPT_DE)
543 | RT_BIT(X86_XCPT_NM)
544 | RT_BIT(X86_XCPT_UD)
545 | RT_BIT(X86_XCPT_NP)
546 | RT_BIT(X86_XCPT_SS)
547 | RT_BIT(X86_XCPT_GP)
548 | RT_BIT(X86_XCPT_PF)
549 | RT_BIT(X86_XCPT_MF);
550#endif
551
552 /* Set up unconditional intercepts and conditions. */
553 pVmcb->ctrl.u32InterceptCtrl1 = SVM_CTRL1_INTERCEPT_INTR /* External interrupt causes a VM-exit. */
554 | SVM_CTRL1_INTERCEPT_VINTR /* When guest enables interrupts cause a VM-exit. */
555 | SVM_CTRL1_INTERCEPT_NMI /* Non-Maskable Interrupts causes a VM-exit. */
556 | SVM_CTRL1_INTERCEPT_SMI /* System Management Interrupt cause a VM-exit. */
557 | SVM_CTRL1_INTERCEPT_INIT /* INIT signal causes a VM-exit. */
558 | SVM_CTRL1_INTERCEPT_RDPMC /* RDPMC causes a VM-exit. */
559 | SVM_CTRL1_INTERCEPT_CPUID /* CPUID causes a VM-exit. */
560 | SVM_CTRL1_INTERCEPT_RSM /* RSM causes a VM-exit. */
561 | SVM_CTRL1_INTERCEPT_HLT /* HLT causes a VM-exit. */
562 | SVM_CTRL1_INTERCEPT_INOUT_BITMAP /* Use the IOPM to cause IOIO VM-exits. */
563 | SVM_CTRL1_INTERCEPT_MSR_SHADOW /* MSR access not covered by MSRPM causes a VM-exit.*/
564 | SVM_CTRL1_INTERCEPT_INVLPGA /* INVLPGA causes a VM-exit. */
565 | SVM_CTRL1_INTERCEPT_SHUTDOWN /* Shutdown events causes a VM-exit. */
566 | SVM_CTRL1_INTERCEPT_FERR_FREEZE; /* Intercept "freezing" during legacy FPU handling. */
567
568 pVmcb->ctrl.u32InterceptCtrl2 = SVM_CTRL2_INTERCEPT_VMRUN /* VMRUN causes a VM-exit. */
569 | SVM_CTRL2_INTERCEPT_VMMCALL /* VMMCALL causes a VM-exit. */
570 | SVM_CTRL2_INTERCEPT_VMLOAD /* VMLOAD causes a VM-exit. */
571 | SVM_CTRL2_INTERCEPT_VMSAVE /* VMSAVE causes a VM-exit. */
572 | SVM_CTRL2_INTERCEPT_STGI /* STGI causes a VM-exit. */
573 | SVM_CTRL2_INTERCEPT_CLGI /* CLGI causes a VM-exit. */
574 | SVM_CTRL2_INTERCEPT_SKINIT /* SKINIT causes a VM-exit. */
575 | SVM_CTRL2_INTERCEPT_WBINVD /* WBINVD causes a VM-exit. */
576 | SVM_CTRL2_INTERCEPT_MONITOR /* MONITOR causes a VM-exit. */
577 | SVM_CTRL2_INTERCEPT_MWAIT; /* MWAIT causes a VM-exit. */
578
579 /* CR0, CR4 reads must be intercepted, our shadow values are not necessarily the same as the guest's. */
580 pVmcb->ctrl.u16InterceptRdCRx = RT_BIT(0) | RT_BIT(4);
581
582 /* CR0, CR4 writes must be intercepted for the same reasons as above. */
583 pVmcb->ctrl.u16InterceptWrCRx = RT_BIT(0) | RT_BIT(4);
584
585 /* Intercept all DRx reads and writes by default. Changed later on. */
586 pVmcb->ctrl.u16InterceptRdDRx = 0xffff;
587 pVmcb->ctrl.u16InterceptWrDRx = 0xffff;
588
589 /* Virtualize masking of INTR interrupts. (reads/writes from/to CR8 go to the V_TPR register) */
590 pVmcb->ctrl.IntCtrl.n.u1VIrqMasking = 1;
591
592 /* Ignore the priority in the TPR; we take into account the guest TPR anyway while delivering interrupts. */
593 pVmcb->ctrl.IntCtrl.n.u1IgnoreTPR = 1;
594
595 /* Set IO and MSR bitmap permission bitmap physical addresses. */
596 pVmcb->ctrl.u64IOPMPhysAddr = g_HCPhysIOBitmap;
597 pVmcb->ctrl.u64MSRPMPhysAddr = pVCpu->hm.s.svm.HCPhysMsrBitmap;
598
599 /* No LBR virtualization. */
600 pVmcb->ctrl.u64LBRVirt = 0;
601
602 /* Initially set all VMCB clean bits to 0 indicating that everything should be loaded from memory. */
603 pVmcb->ctrl.u64VmcbCleanBits = 0;
604
605 /* The guest ASID MBNZ, set it to 1. The host uses 0. */
606 pVmcb->ctrl.TLBCtrl.n.u32ASID = 1;
607
608 /*
609 * Setup the PAT MSR (applicable for Nested Paging only).
610 * The default value should be 0x0007040600070406ULL, but we want to treat all guest memory as WB,
611 * so choose type 6 for all PAT slots.
612 */
613 pVmcb->guest.u64GPAT = UINT64_C(0x0006060606060606);
614
615 /* Without Nested Paging, we need additionally intercepts. */
616 if (!pVM->hm.s.fNestedPaging)
617 {
618 /* CR3 reads/writes must be intercepted; our shadow values differ from the guest values. */
619 pVmcb->ctrl.u16InterceptRdCRx |= RT_BIT(3);
620 pVmcb->ctrl.u16InterceptWrCRx |= RT_BIT(3);
621
622 /* Intercept INVLPG and task switches (may change CR3, EFLAGS, LDT). */
623 pVmcb->ctrl.u32InterceptCtrl1 |= SVM_CTRL1_INTERCEPT_INVLPG
624 | SVM_CTRL1_INTERCEPT_TASK_SWITCH;
625
626 /* Page faults must be intercepted to implement shadow paging. */
627 pVmcb->ctrl.u32InterceptException |= RT_BIT(X86_XCPT_PF);
628 }
629
630 /*
631 * The following MSRs are saved/restored automatically during the world-switch.
632 * Don't intercept guest read/write accesses to these MSRs.
633 */
634 hmR0SvmSetMsrPermission(pVCpu, MSR_K8_LSTAR, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
635 hmR0SvmSetMsrPermission(pVCpu, MSR_K8_CSTAR, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
636 hmR0SvmSetMsrPermission(pVCpu, MSR_K6_STAR, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
637 hmR0SvmSetMsrPermission(pVCpu, MSR_K8_SF_MASK, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
638 hmR0SvmSetMsrPermission(pVCpu, MSR_K8_FS_BASE, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
639 hmR0SvmSetMsrPermission(pVCpu, MSR_K8_GS_BASE, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
640 hmR0SvmSetMsrPermission(pVCpu, MSR_K8_KERNEL_GS_BASE, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
641 hmR0SvmSetMsrPermission(pVCpu, MSR_IA32_SYSENTER_CS, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
642 hmR0SvmSetMsrPermission(pVCpu, MSR_IA32_SYSENTER_ESP, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
643 hmR0SvmSetMsrPermission(pVCpu, MSR_IA32_SYSENTER_EIP, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
644 }
645
646 return rc;
647}
648
649
650/**
651 * Flushes the appropriate tagged-TLB entries.
652 *
653 * @param pVM Pointer to the VM.
654 * @param pVCpu Pointer to the VMCPU.
655 */
656static void hmR0SvmFlushTaggedTlb(PVMCPU pVCpu)
657{
658 PVM pVM = pVCpu->CTX_SUFF(pVM);
659 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
660 PHMGLOBLCPUINFO pCpu = HMR0GetCurrentCpu();
661
662 /*
663 * Force a TLB flush for the first world switch if the current CPU differs from the one we ran on last.
664 * This can happen both for start & resume due to long jumps back to ring-3.
665 * If the TLB flush count changed, another VM (VCPU rather) has hit the ASID limit while flushing the TLB,
666 * so we cannot reuse the ASIDs without flushing.
667 */
668 bool fNewAsid = false;
669 if ( pVCpu->hm.s.idLastCpu != pCpu->idCpu
670 || pVCpu->hm.s.cTlbFlushes != pCpu->cTlbFlushes)
671 {
672 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlbWorldSwitch);
673 pVCpu->hm.s.fForceTLBFlush = true;
674 fNewAsid = true;
675 }
676
677 /* Set TLB flush state as checked until we return from the world switch. */
678 ASMAtomicWriteBool(&pVCpu->hm.s.fCheckedTLBFlush, true);
679
680 /* Check for explicit TLB shootdowns. */
681 if (VMCPU_FF_TEST_AND_CLEAR(pVCpu, VMCPU_FF_TLB_FLUSH))
682 {
683 pVCpu->hm.s.fForceTLBFlush = true;
684 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushTlb);
685 }
686
687 pVCpu->hm.s.idLastCpu = pCpu->idCpu;
688 pVmcb->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_NOTHING;
689
690 if (pVM->hm.s.svm.fAlwaysFlushTLB)
691 {
692 /*
693 * This is the AMD erratum 170. We need to flush the entire TLB for each world switch. Sad.
694 */
695 pCpu->uCurrentAsid = 1;
696 pVCpu->hm.s.uCurrentAsid = 1;
697 pVCpu->hm.s.cTlbFlushes = pCpu->cTlbFlushes;
698 pVmcb->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_ENTIRE;
699 }
700 else if (pVCpu->hm.s.fForceTLBFlush)
701 {
702 if (fNewAsid)
703 {
704 ++pCpu->uCurrentAsid;
705 bool fHitASIDLimit = false;
706 if (pCpu->uCurrentAsid >= pVM->hm.s.uMaxAsid)
707 {
708 pCpu->uCurrentAsid = 1; /* Wraparound at 1; host uses 0 */
709 pCpu->cTlbFlushes++; /* All VCPUs that run on this host CPU must use a new VPID. */
710 fHitASIDLimit = true;
711
712 if (pVM->hm.s.svm.u32Features & AMD_CPUID_SVM_FEATURE_EDX_FLUSH_BY_ASID)
713 {
714 pVmcb->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_SINGLE_CONTEXT;
715 pCpu->fFlushAsidBeforeUse = true;
716 }
717 else
718 {
719 pVmcb->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_ENTIRE;
720 pCpu->fFlushAsidBeforeUse = false;
721 }
722 }
723
724 if ( !fHitASIDLimit
725 && pCpu->fFlushAsidBeforeUse)
726 {
727 if (pVM->hm.s.svm.u32Features & AMD_CPUID_SVM_FEATURE_EDX_FLUSH_BY_ASID)
728 pVmcb->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_SINGLE_CONTEXT;
729 else
730 {
731 pVmcb->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_ENTIRE;
732 pCpu->fFlushAsidBeforeUse = false;
733 }
734 }
735
736 pVCpu->hm.s.uCurrentAsid = pCpu->uCurrentAsid;
737 pVCpu->hm.s.cTlbFlushes = pCpu->cTlbFlushes;
738 }
739 else
740 {
741 if (pVM->hm.s.svm.u32Features & AMD_CPUID_SVM_FEATURE_EDX_FLUSH_BY_ASID)
742 pVmcb->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_SINGLE_CONTEXT;
743 else
744 pVmcb->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_ENTIRE;
745 }
746
747 pVCpu->hm.s.fForceTLBFlush = false;
748 }
749 else
750 {
751 /** @todo We never set VMCPU_FF_TLB_SHOOTDOWN anywhere so this path should
752 * not be executed. See hmQueueInvlPage() where it is commented
753 * out. Support individual entry flushing someday. */
754 if (VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_TLB_SHOOTDOWN))
755 {
756 /* Deal with pending TLB shootdown actions which were queued when we were not executing code. */
757 STAM_COUNTER_INC(&pVCpu->hm.s.StatTlbShootdown);
758 for (uint32_t i = 0; i < pVCpu->hm.s.TlbShootdown.cPages; i++)
759 SVMR0InvlpgA(pVCpu->hm.s.TlbShootdown.aPages[i], pVmcb->ctrl.TLBCtrl.n.u32ASID);
760 }
761 }
762
763 pVCpu->hm.s.TlbShootdown.cPages = 0;
764 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_TLB_SHOOTDOWN);
765
766 /* Update VMCB with the ASID. */
767 if (pVmcb->ctrl.TLBCtrl.n.u32ASID != pVCpu->hm.s.uCurrentAsid)
768 {
769 pVmcb->ctrl.TLBCtrl.n.u32ASID = pVCpu->hm.s.uCurrentAsid;
770 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_ASID;
771 }
772
773 AssertMsg(pVCpu->hm.s.cTlbFlushes == pCpu->cTlbFlushes,
774 ("Flush count mismatch for cpu %d (%x vs %x)\n", pCpu->idCpu, pVCpu->hm.s.cTlbFlushes, pCpu->cTlbFlushes));
775 AssertMsg(pCpu->uCurrentAsid >= 1 && pCpu->uCurrentAsid < pVM->hm.s.uMaxAsid,
776 ("cpu%d uCurrentAsid = %x\n", pCpu->idCpu, pCpu->uCurrentAsid));
777 AssertMsg(pVCpu->hm.s.uCurrentAsid >= 1 && pVCpu->hm.s.uCurrentAsid < pVM->hm.s.uMaxAsid,
778 ("cpu%d VM uCurrentAsid = %x\n", pCpu->idCpu, pVCpu->hm.s.uCurrentAsid));
779
780#ifdef VBOX_WITH_STATISTICS
781 if (pVmcb->ctrl.TLBCtrl.n.u8TLBFlush == SVM_TLB_FLUSH_NOTHING)
782 STAM_COUNTER_INC(&pVCpu->hm.s.StatNoFlushTlbWorldSwitch);
783 else if ( pVmcb->ctrl.TLBCtrl.n.u8TLBFlush == SVM_TLB_FLUSH_SINGLE_CONTEXT
784 || pVmcb->ctrl.TLBCtrl.n.u8TLBFlush == SVM_TLB_FLUSH_SINGLE_CONTEXT_RETAIN_GLOBALS)
785 {
786 STAM_COUNTER_INC(&pVCpu->hm.s.StatFlushAsid);
787 }
788 else
789 Assert(pVmcb->ctrl.TLBCtrl.n.u8TLBFlush == SVM_TLB_FLUSH_ENTIRE)
790#endif
791}
792
793
794/** @name 64-bit guest on 32-bit host OS helper functions.
795 *
796 * The host CPU is still 64-bit capable but the host OS is running in 32-bit
797 * mode (code segment, paging). These wrappers/helpers perform the necessary
798 * bits for the 32->64 switcher.
799 *
800 * @{ */
801#if HC_ARCH_BITS == 32 && defined(VBOX_ENABLE_64_BITS_GUESTS) && !defined(VBOX_WITH_HYBRID_32BIT_KERNEL)
802/**
803 * Prepares for and executes VMRUN (64-bit guests on a 32-bit host).
804 *
805 * @returns VBox status code.
806 * @param HCPhysVmcbHost Physical address of host VMCB.
807 * @param HCPhysVmcb Physical address of the VMCB.
808 * @param pCtx Pointer to the guest-CPU context.
809 * @param pVM Pointer to the VM.
810 * @param pVCpu Pointer to the VMCPU.
811 */
812DECLASM(int) SVMR0VMSwitcherRun64(RTHCPHYS HCPhysVmcbHost, RTHCPHYS HCPhysVmcb, PCPUMCTX pCtx, PVM pVM, PVMCPU pVCpu)
813{
814 uint32_t aParam[4];
815 aParam[0] = (uint32_t)(HCPhysVmcbHost); /* Param 1: HCPhysVmcbHost - Lo. */
816 aParam[1] = (uint32_t)(HCPhysVmcbHost >> 32); /* Param 1: HCPhysVmcbHost - Hi. */
817 aParam[2] = (uint32_t)(HCPhysVmcb); /* Param 2: HCPhysVmcb - Lo. */
818 aParam[3] = (uint32_t)(HCPhysVmcb >> 32); /* Param 2: HCPhysVmcb - Hi. */
819
820 return SVMR0Execute64BitsHandler(pVM, pVCpu, pCtx, HM64ON32OP_SVMRCVMRun64, 4, &aParam[0]);
821}
822
823
824/**
825 * Executes the specified VMRUN handler in 64-bit mode.
826 *
827 * @returns VBox status code.
828 * @param pVM Pointer to the VM.
829 * @param pVCpu Pointer to the VMCPU.
830 * @param pCtx Pointer to the guest-CPU context.
831 * @param enmOp The operation to perform.
832 * @param cbParam Number of parameters.
833 * @param paParam Array of 32-bit parameters.
834 */
835VMMR0DECL(int) SVMR0Execute64BitsHandler(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, HM64ON32OP enmOp, uint32_t cbParam,
836 uint32_t *paParam)
837{
838 AssertReturn(pVM->hm.s.pfnHost32ToGuest64R0, VERR_HM_NO_32_TO_64_SWITCHER);
839 Assert(enmOp > HM64ON32OP_INVALID && enmOp < HM64ON32OP_END);
840
841 /* Disable interrupts. */
842 RTHCUINTREG uOldEFlags = ASMIntDisableFlags();
843
844#ifdef VBOX_WITH_VMMR0_DISABLE_LAPIC_NMI
845 RTCPUID idHostCpu = RTMpCpuId();
846 CPUMR0SetLApic(pVM, idHostCpu);
847#endif
848
849 CPUMSetHyperESP(pVCpu, VMMGetStackRC(pVCpu));
850 CPUMSetHyperEIP(pVCpu, enmOp);
851 for (int i = (int)cbParam - 1; i >= 0; i--)
852 CPUMPushHyper(pVCpu, paParam[i]);
853
854 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatWorldSwitch3264, z);
855 /* Call the switcher. */
856 int rc = pVM->hm.s.pfnHost32ToGuest64R0(pVM, RT_OFFSETOF(VM, aCpus[pVCpu->idCpu].cpum) - RT_OFFSETOF(VM, cpum));
857 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatWorldSwitch3264, z);
858
859 /* Restore interrupts. */
860 ASMSetFlags(uOldEFlags);
861 return rc;
862}
863
864#endif /* HC_ARCH_BITS == 32 && defined(VBOX_ENABLE_64_BITS_GUESTS) */
865/** @} */
866
867
868DECLINLINE(void) hmR0SvmAddXcptIntercept(uint32_t u32Xcpt)
869{
870 if (!(pVmcb->ctrl.u32InterceptException & RT_BIT(u32Xcpt))
871 {
872 pVmcb->ctrl.u32InterceptException |= RT_BIT(u32Xcpt);
873 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
874 }
875}
876
877DECLINLINE(void) hmR0SvmRemoveXcptIntercept(uint32_t u32Xcpt)
878{
879#ifndef HMSVM_ALWAYS_TRAP_ALL_XCPTS
880 if (pVmcb->ctrl.u32InterceptException & RT_BIT(u32Xcpt))
881 {
882 pVmcb->ctrl.u32InterceptException &= ~RT_BIT(u32Xcpt);
883 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
884 }
885#endif
886}
887
888
889/**
890 * Loads the guest control registers (CR0, CR2, CR3, CR4) into the VMCB.
891 *
892 * @returns VBox status code.
893 * @param pVCpu Pointer to the VMCPU.
894 * @param pVmcb Pointer to the VMCB.
895 * @param pCtx Pointer the guest-CPU context.
896 *
897 * @remarks No-long-jump zone!!!
898 */
899DECLINLINE(int) hmR0SvmLoadGuestControlRegs(PVMCPU pVCpu, PSVMVMCB pVmcb, PCPUMCTX pCtx)
900{
901 /*
902 * Guest CR0.
903 */
904 if (pVCpu->hm.s.fContextUseFlags & HM_CHANGED_GUEST_CR0)
905 {
906 uint64_t u64GuestCR0 = pCtx->cr0;
907
908 /* Always enable caching. */
909 u64GuestCR0 &= ~(X86_CR0_CD | X86_CR0_NW);
910
911 /*
912 * When Nested Paging is not available use shadow page tables and intercept #PFs (the latter done in SVMR0SetupVM()).
913 */
914 if (!pVM->hm.s.fNestedPaging)
915 {
916 u64GuestCR0 |= X86_CR0_PG; /* When Nested Paging is not available, use shadow page tables. */
917 u64GuestCR0 |= X86_CR0_WP; /* Guest CPL 0 writes to its read-only pages should cause a #PF VM-exit. */
918 }
919
920 /*
921 * Guest FPU bits.
922 */
923 bool fInterceptNM = false;
924 bool fInterceptMF = false;
925 u64GuestCR0 |= X86_CR0_NE; /* Use internal x87 FPU exceptions handling rather than external interrupts. */
926 if (CPUMIsGuestFPUStateActive(pVCpu))
927 {
928 /* Catch floating point exceptions if we need to report them to the guest in a different way. */
929 if (!(u64GuestCR0 & X86_CR0_NE))
930 {
931 Log4(("hmR0SvmLoadGuestControlRegs: Intercepting Guest CR0.MP Old-style FPU handling!!!\n"));
932 pVmcb->ctrl.u32InterceptException |= RT_BIT(X86_XCPT_MF);
933 fInterceptMF = true;
934 }
935 }
936 else
937 {
938 fInterceptNM = true; /* Guest FPU inactive, VM-exit on #NM for lazy FPU loading. */
939 u32GuestCR0 |= X86_CR0_TS /* Guest can task switch quickly and do lazy FPU syncing. */
940 | X86_CR0_MP; /* FWAIT/WAIT should not ignore CR0.TS and should generate #NM. */
941 }
942
943 /*
944 * Update the exception intercept bitmap.
945 */
946 if (fInterceptNM)
947 hmR0SvmAddXcptIntercept(X86_XCPT_NM);
948 else
949 hmR0SvmRemoveXcptIntercept(X86_XCPT_NM);
950
951 if (fInterceptMF)
952 hmR0SvmAddXcptIntercept(X86_XCPT_MF);
953 else
954 hmR0SvmRemoveXcptIntercept(X86_XCPT_MF);
955
956 pVmcb->guest.u64CR0 = u64GuestCR0;
957 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_CRX_EFER;
958 pVCpu->hm.s.fContextUseFlags &= ~HM_CHANGED_GUEST_CR0;
959 }
960
961 /*
962 * Guest CR2.
963 */
964 if (pVCpu->hm.s.fContextUseFlags & HM_CHANGED_GUEST_CR2)
965 {
966 pVmcb->guest.u64CR2 = pCtx->cr2;
967 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_CR2;
968 pVCpu->hm.s.fContextUseFlags &= ~HM_CHANGED_GUEST_CR2;
969 }
970
971 /*
972 * Guest CR3.
973 */
974 if (pVCpu->hm.s.fContextUseFlags & HM_CHANGED_GUEST_CR3)
975 {
976 if (pVM->hm.s.fNestedPaging)
977 {
978 PGMMODE enmShwPagingMode;
979#if HC_ARCH_BITS == 32
980 if (CPUMIsGuestInLongModeEx(pCtx))
981 enmShwPagingMode = PGMMODE_AMD64_NX;
982 else
983#endif
984 enmShwPagingMode = PGMGetHostMode(pVM);
985
986 pVmcb->ctrl.u64NestedPagingCR3 = PGMGetNestedCR3(pVCpu, enmShwPagingMode);
987 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_NP;
988 Assert(pVmcb->ctrl.u64NestedPagingCR3);
989 pVmcb->guest.u64CR3 = pCtx->cr3;
990 }
991 else
992 pVmcb->guest.u64CR3 = PGMGetHyperCR3(pVCpu);
993
994 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_CRX_EFER;
995 pVCpu->hm.s.fContextUseFlags &= HM_CHANGED_GUEST_CR3;
996 }
997
998 /*
999 * Guest CR4.
1000 */
1001 if (pVCpu->hm.s.fContextUseFlags & HM_CHANGED_GUEST_CR4)
1002 {
1003 uint64_t u64GuestCR4 = pCtx->cr4;
1004 if (!pVM->hm.s.fNestedPaging)
1005 {
1006 switch (pVCpu->hm.s.enmShadowMode)
1007 {
1008 case PGMMODE_REAL:
1009 case PGMMODE_PROTECTED: /* Protected mode, no paging. */
1010 AssertFailed();
1011 return VERR_PGM_UNSUPPORTED_SHADOW_PAGING_MODE;
1012
1013 case PGMMODE_32_BIT: /* 32-bit paging. */
1014 u64GuestCR4 &= ~X86_CR4_PAE;
1015 break;
1016
1017 case PGMMODE_PAE: /* PAE paging. */
1018 case PGMMODE_PAE_NX: /* PAE paging with NX enabled. */
1019 /** Must use PAE paging as we could use physical memory > 4 GB */
1020 u64GuestCR4 |= X86_CR4_PAE;
1021 break;
1022
1023 case PGMMODE_AMD64: /* 64-bit AMD paging (long mode). */
1024 case PGMMODE_AMD64_NX: /* 64-bit AMD paging (long mode) with NX enabled. */
1025#ifdef VBOX_ENABLE_64_BITS_GUESTS
1026 break;
1027#else
1028 AssertFailed();
1029 return VERR_PGM_UNSUPPORTED_SHADOW_PAGING_MODE;
1030#endif
1031
1032 default: /* shut up gcc */
1033 AssertFailed();
1034 return VERR_PGM_UNSUPPORTED_SHADOW_PAGING_MODE;
1035 }
1036 }
1037
1038 pVmcb->guest.u64CR4 = u64GuestCR4;
1039 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_CRX_EFER;
1040 pVCpu->hm.s.fContextUseFlags &= ~HM_CHANGED_GUEST_CR4;
1041 }
1042
1043 return VINF_SUCCESS;
1044}
1045
1046
1047/**
1048 * Loads the guest segment registers into the VMCB.
1049 *
1050 * @returns VBox status code.
1051 * @param pVCpu Pointer to the VMCPU.
1052 * @param pVmcb Pointer to the VMCB.
1053 * @param pCtx Pointer to the guest-CPU context.
1054 *
1055 * @remarks No-long-jump zone!!!
1056 */
1057DECLINLINE(void) hmR0SvmLoadGuestSegmentRegs(PVMCPU pVCpu, PSVMVMCB pVmcb, PCPUMCTX pCtx)
1058{
1059 /* Guest Segment registers: CS, SS, DS, ES, FS, GS. */
1060 if (pVCpu->hm.s.fContextUseFlags & HM_CHANGED_GUEST_SEGMENT_REGS)
1061 {
1062 HMSVM_LOAD_SEG_REG(CS, cs);
1063 HMSVM_LOAD_SEG_REG(SS, cs);
1064 HMSVM_LOAD_SEG_REG(DS, cs);
1065 HMSVM_LOAD_SEG_REG(ES, cs);
1066 HMSVM_LOAD_SEG_REG(FS, cs);
1067 HMSVM_LOAD_SEG_REG(GS, cs);
1068
1069 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_SEG;
1070 pVCpu->hm.s.fContextUseFlags &= ~HM_CHANGED_GUEST_SEGMENT_REGS;
1071 }
1072
1073 /* Guest TR. */
1074 if (pVCpu->hm.s.fContextUseFlags & HM_CHANGED_GUEST_TR)
1075 {
1076 HMSVM_LOAD_SEG_REG(TR, tr);
1077 pVCpu->hm.s.fContextUseFlags &= ~HM_CHANGED_GUEST_TR;
1078 }
1079
1080 /* Guest LDTR. */
1081 if (pVCpu->hm.s.fContextUseFlags & HM_CHANGED_GUEST_LDTR)
1082 {
1083 HMSVM_LOAD_SEG_REG(LDTR, ldtr);
1084 pVCpu->hm.s.fContextUseFlags &= ~HM_CHANGED_GUEST_LDTR;
1085 }
1086
1087 /* Guest GDTR. */
1088 if (pVCpu->hm.s.fContextUseFlags & HM_CHANGED_GUEST_GDTR)
1089 {
1090 pVmcb->guest.GDTR.u32Limit = pCtx->gdtr.cbGdt;
1091 pVmcb->guest.GDTR.u64Base = pCtx->gdtr.pGdt;
1092 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_DT;
1093 pVCpu->hm.s.fContextUseFlags &= ~HM_CHANGED_GUEST_GDTR;
1094 }
1095
1096 /* Guest IDTR. */
1097 if (pVCpu->hm.s.fContextUseFlags & HM_CHANGED_GUEST_IDTR)
1098 {
1099 pVmcb->guest.IDTR.u32Limit = pCtx->idtr.cbIdt;
1100 pVmcb->guest.IDTR.u64Base = pCtx->idtr.pIdt;
1101 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_DT;
1102 pVCpu->hm.s.fContextUseFlags &= ~HM_CHANGED_GUEST_IDTR;
1103 }
1104}
1105
1106
1107/**
1108 * Loads the guest MSRs into the VMCB.
1109 *
1110 * @param pVCpu Pointer to the VMCPU.
1111 * @param pVmcb Pointer to the VMCB.
1112 * @param pCtx Pointer to the guest-CPU context.
1113 *
1114 * @remarks No-long-jump zone!!!
1115 */
1116DECLINLINE(void) hmR0SvmLoadGuestMsrs(PVMCPU pVCpu, PSVMVMCB pVmcb, PCPUMCTX pCtx)
1117{
1118 /* Guest Sysenter MSRs. */
1119 pVmcb->guest.u64SysEnterCS = pCtx->SysEnter.cs;
1120 pVmcb->guest.u64SysEnterEIP = pCtx->SysEnter.eip;
1121 pVmcb->guest.u64SysEnterESP = pCtx->SysEnter.esp;
1122
1123 /*
1124 * Guest EFER MSR.
1125 * AMD-V requires guest EFER.SVME to be set. Weird. .
1126 * See AMD spec. 15.5.1 "Basic Operation" | "Canonicalization and Consistency Checks".
1127 */
1128 if (pVCpu->hm.s.fContextUseFlags & HM_CHANGED_SVM_GUEST_EFER_MSR
1129 {
1130 pVmcb->guest.u64EFER = pCtx->msrEFER | MSR_K6_EFER_SVME;
1131 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_CRX_EFER;
1132 pVCpu->hm.s.fContextUseFlags &= ~HM_CHANGED_SVM_GUEST_EFER_MSR;
1133 }
1134
1135 /* 64-bit MSRs. */
1136 if (CPUMIsGuestInLongModeEx(pCtx))
1137 {
1138 pVmcb->guest.FS.u64Base = pCtx->fs.u64Base;
1139 pVmcb->guest.GS.u64Base = pCtx->gs.u64Base;
1140 }
1141 else
1142 {
1143 /* If the guest isn't in 64-bit mode, clear MSR_K6_LME bit from guest EFER otherwise AMD-V expects amd64 shadow paging. */
1144 if (pCtx->msrEFER & MSR_K6_EFER_LME)
1145 {
1146 pVmcb->guest.u64EFER &= ~MSR_K6_EFER_LME;
1147 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_CRX_EFER;
1148 }
1149 }
1150
1151
1152 /** @todo The following are used in 64-bit only (SYSCALL/SYSRET) but they might
1153 * be writable in 32-bit mode. Clarify with AMD spec. */
1154 pVmcb->guest.u64STAR = pCtx->msrSTAR;
1155 pVmcb->guest.u64LSTAR = pCtx->msrLSTAR;
1156 pVmcb->guest.u64CSTAR = pCtx->msrCSTAR;
1157 pVmcb->guest.u64SFMASK = pCtx->msrSFMASK;
1158 pVmcb->guest.u64KernelGSBase = pCtx->msrKERNELGSBASE;
1159}
1160
1161
1162/**
1163 * Loads the guest debug registers into the VMCB.
1164 *
1165 * @param pVCpu Pointer to the VMCPU.
1166 * @param pCtx Pointer to the guest-CPU context.
1167 *
1168 * @remarks No-long-jump zone!!!
1169 * @remarks Requires EFLAGS to be up-to-date in the VMCB!
1170 */
1171DECLINLINE(void) hmR0SvmLoadGuestDebugRegs(PVMCPU pVCpu, PCPUMCTX pCtx)
1172{
1173 if (!(pVCpu->hm.s.fContextUseFlags & HM_CHANGED_GUEST_DEBUG))
1174 return;
1175
1176 /** @todo Turn these into assertions if possible. */
1177 pCtx->dr[6] |= X86_DR6_INIT_VAL; /* Set reserved bits to 1. */
1178 pCtx->dr[6] &= ~RT_BIT(12); /* MBZ. */
1179
1180 pCtx->dr[7] &= 0xffffffff; /* Upper 32 bits MBZ. */
1181 pCtx->dr[7] &= ~(RT_BIT(11) | RT_BIT(12) | RT_BIT(14) | RT_BIT(15)); /* MBZ. */
1182 pCtx->dr[7] |= 0x400; /* MB1. */
1183
1184 /* Update DR6, DR7 with the guest values. */
1185 pVmcb->guest.u64DR7 = pCtx->dr[7];
1186 pVmcb->guest.u64DR6 = pCtx->dr[6];
1187 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_DRX;
1188
1189 bool fInterceptDB = false;
1190 bool fInterceptMovDRx = false;
1191 if (DBGFIsStepping(pVCpu))
1192 {
1193 /* AMD-V doesn't have any monitor-trap flag equivalent. Instead, enable tracing in the guest and trap #DB. */
1194 pVmcb->guest.u64RFlags |= X86_EFL_TF;
1195 fInterceptDB = true;
1196 }
1197
1198 if (CPUMGetHyperDR7(pVCpu) & (X86_DR7_ENABLED_MASK | X86_DR7_GD))
1199 {
1200 if (!CPUMIsHyperDebugStateActive(pVCpu))
1201 {
1202 rc = CPUMR0LoadHyperDebugState(pVM, pVCpu, pCtx, true /* include DR6 */);
1203 AssertRC(rc);
1204
1205 /* Update DR6, DR7 with the hypervisor values. */
1206 pVmcb->guest.u64DR7 = CPUMGetHyperDR7(pVCpu);
1207 pVmcb->guest.u64DR6 = CPUMGetHyperDR6(pVCpu);
1208 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_DRX;
1209 }
1210 Assert(CPUMIsHyperDebugStateActive(pVCpu));
1211 fInterceptMovDRx = true;
1212 }
1213 else if (pCtx->dr[7] & (X86_DR7_ENABLED_MASK | X86_DR7_GD))
1214 {
1215 if (!CPUMIsGuestDebugStateActive(pVCpu))
1216 {
1217 rc = CPUMR0LoadGuestDebugState(pVM, pVCpu, pCtx, true /* include DR6 */);
1218 AssertRC(rc);
1219 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxArmed);
1220 }
1221 Assert(CPUMIsGuestDebugStateActive(pVCpu));
1222 Assert(fInterceptMovDRx == false);
1223 }
1224 else if (!CPUMIsGuestDebugStateActive(pVCpu))
1225 {
1226 /* For the first time we would need to intercept MOV DRx accesses even when the guest debug registers aren't loaded. */
1227 fInterceptMovDRx = true;
1228 }
1229
1230 if (fInterceptDB)
1231 hmR0SvmAddXcptIntercept(X86_XCPT_DB);
1232 else
1233 hmR0SvmRemoveXcptIntercept(X86_XCPT_DB);
1234
1235 if (fInterceptMovDRx)
1236 {
1237 if ( pVmcb->ctrl.u16InterceptRdDRx != 0xffff
1238 || pVmcb->ctrl.u16InterceptWrDRx != 0xffff)
1239 {
1240 pVmcb->ctrl.u16InterceptRdDRx = 0xffff;
1241 pVmcb->ctrl.u16InterceptWrDRx = 0xffff;
1242 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
1243 }
1244 }
1245 else
1246 {
1247 if ( pVmcb->ctrl.u16InterceptRdDRx
1248 || pVmcb->ctrl.u16InterceptWrDRx)
1249 {
1250 pVmcb->ctrl.u16InterceptRdDRx = 0;
1251 pVmcb->ctrl.u16InterceptWrDRx = 0;
1252 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
1253 }
1254 }
1255
1256 pVCpu->hm.s.fContextUseFlags &= ~HM_CHANGED_GUEST_DEBUG;
1257}
1258
1259
1260/**
1261 * Loads the guest APIC state (currently just the TPR).
1262 *
1263 * @returns VBox status code.
1264 * @param pVCpu Pointer to the VMCPU.
1265 * @param pVmcb Pointer to the VMCB.
1266 * @param pCtx Pointer to the guest-CPU context.
1267 */
1268DECLINLINE(int) hmR0SvmLoadGuestApicState(PVMCPU pVCpu, PSVMVMCB pVmcb, PCPUMCTX pCtx)
1269{
1270 if (!(pVCpu->hm.s.fContextUseFlags & HM_CHANGED_SVM_GUEST_APIC_STATE))
1271 return VINF_SUCCESS;
1272
1273 bool fPendingIntr;
1274 uint8_t u8Tpr;
1275 int rc = PDMApicGetTPR(pVCpu, &u8Tpr, &fPendingIntr, NULL /* pu8PendingIrq */);
1276 AssertRCReturn(rc, rc);
1277
1278 /** Assume that we need to trap all TPR accesses and thus need not check on
1279 * every #VMEXIT if we should update the TPR. */
1280 Assert(pVmcb->ctrl.IntCtrl.n.u1VIrqMasking);
1281 pVCpu->hm.s.svm.fSyncVTpr = false;
1282
1283 /* 32-bit guests uses LSTAR MSR for patching guest code which touches the TPR. */
1284 if (pVCpu->CTX_SUFF(pVM)->hm.s.fTPRPatchingActive)
1285 {
1286 pCtx->msrLSTAR = u8LastTPR;
1287
1288 /* If there are interrupts pending, intercept LSTAR writes, otherwise don't intercept reads or writes. */
1289 if (fPendingIntr)
1290 hmR0SvmSetMsrPermission(pVCpu, MSR_K8_LSTAR, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_INTERCEPT_WRITE);
1291 else
1292 {
1293 hmR0SvmSetMsrPermission(pVCpu, MSR_K8_LSTAR, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
1294 pVCpu->hm.s.svm.fSyncVTpr = true;
1295 }
1296
1297 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_IOPM_MSRPM;
1298 }
1299 else
1300 {
1301 /* Bits 3-0 of the VTPR field correspond to bits 7-4 of the TPR (which is the Task-Priority Class). */
1302 pVmcb->ctrl.IntCtrl.n.u8VTPR = (u8Tpr >> 4);
1303
1304 /* If there are interrupts pending, intercept CR8 writes to evaluate ASAP if we can deliver the interrupt to the guest. */
1305 if (fPending)
1306 pVmcb->ctrl.u16InterceptWrCRx |= RT_BIT(8);
1307 else
1308 {
1309 pVmcb->ctrl.u16InterceptWrCRx &= ~RT_BIT(8);
1310 pVCpu->hm.s.svm.fSyncVTpr = true;
1311 }
1312
1313 pVmcb->ctrl.u64VmcbCleanBits &= ~(HMSVM_VMCB_CLEAN_INTERCEPTS | HMSVM_VMCB_CLEAN_TPR);
1314 }
1315
1316 pVCpu->hm.s.fContextUseFlags &= ~HM_CHANGED_SVM_GUEST_APIC_STATE;
1317 return rc;
1318}
1319
1320
1321/**
1322 * Sets up the appropriate function to run guest code.
1323 *
1324 * @returns VBox status code.
1325 * @param pVCpu Pointer to the VMCPU.
1326 * @param pCtx Pointer to the guest-CPU context.
1327 *
1328 * @remarks No-long-jump zone!!!
1329 */
1330static int hmR0SvmSetupVMRunHandler(PVMCPU pVCpu, PCPUMCTX pCtx)
1331{
1332 if (CPUMIsGuestInLongModeEx(pCtx))
1333 {
1334#ifndef VBOX_ENABLE_64_BITS_GUESTS
1335 return VERR_PGM_UNSUPPORTED_SHADOW_PAGING_MODE;
1336#endif
1337 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.fAllow64BitGuests); /* Guaranteed by hmR3InitFinalizeR0(). */
1338#if HC_ARCH_BITS == 32 && !defined(VBOX_WITH_HYBRID_32BIT_KERNEL)
1339 /* 32-bit host. We need to switch to 64-bit before running the 64-bit guest. */
1340 pVCpu->hm.s.svm.pfnVMRun = SVMR0VMSwitcherRun64;
1341#else
1342 /* 64-bit host or hybrid host. */
1343 pVCpu->hm.s.svm.pfnVMRun = SVMR0VMRun64;
1344#endif
1345 }
1346 else
1347 {
1348 /* Guest is not in long mode, use the 32-bit handler. */
1349 pVCpu->hm.s.svm.pfnVMRun = SVMR0VMRun;
1350 }
1351 return VINF_SUCCESS;
1352}
1353
1354
1355/**
1356 * Enters the AMD-V session.
1357 *
1358 * @returns VBox status code.
1359 * @param pVM Pointer to the VM.
1360 * @param pVCpu Pointer to the VMCPU.
1361 * @param pCpu Pointer to the CPU info struct.
1362 */
1363VMMR0DECL(int) SVMR0Enter(PVM pVM, PVMCPU pVCpu, PHMGLOBLCPUINFO pCpu)
1364{
1365 AssertPtr(pVM);
1366 AssertPtr(pVCpu);
1367 Assert(pVM->hm.s.svm.fSupported);
1368 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1369 NOREF(pCpu);
1370
1371 LogFlowFunc(("pVM=%p pVCpu=%p\n", pVM, pVCpu));
1372
1373 /* Nothing to do here. */
1374 return VINF_SUCCESS;
1375}
1376
1377
1378/**
1379 * Leaves the AMD-V session.
1380 *
1381 * @returns VBox status code.
1382 * @param pVM Pointer to the VM.
1383 * @param pVCpu Pointer to the VMCPU.
1384 * @param pCtx Pointer to the guest-CPU context.
1385 */
1386VMMR0DECL(int) SVMR0Leave(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
1387{
1388 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1389 NOREF(pVM);
1390 NOREF(pVCpu);
1391 NOREF(pCtx);
1392
1393 /* Nothing to do here. Everything is taken care of in hmR0SvmLongJmpToRing3(). */
1394 return VINF_SUCCESS;
1395}
1396
1397
1398/**
1399 * Saves the host state.
1400 *
1401 * @returns VBox status code.
1402 * @param pVM Pointer to the VM.
1403 * @param pVCpu Pointer to the VMCPU.
1404 *
1405 * @remarks No-long-jump zone!!!
1406 */
1407VMMR0DECL(int) SVMR0SaveHostState(PVM pVM, PVMCPU pVCpu)
1408{
1409 NOREF(pVM);
1410 NOREF(pVCpu);
1411 /* Nothing to do here. AMD-V does this for us automatically during the world-switch. */
1412 return VINF_SUCCESS;
1413}
1414
1415
1416/**
1417 * Loads the guest state.
1418 *
1419 * @returns VBox status code.
1420 * @param pVM Pointer to the VM.
1421 * @param pVCpu Pointer to the VMCPU.
1422 * @param pCtx Pointer to the guest-CPU context.
1423 *
1424 * @remarks No-long-jump zone!!!
1425 */
1426VMMR0DECL(int) SVMR0LoadGuestState(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
1427{
1428 AssertPtr(pVM);
1429 AssertPtr(pVCpu);
1430 AssertPtr(pCtx);
1431 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1432
1433 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
1434 AssertMsgReturn(pVmcb, ("Invalid pVmcb\n"), VERR_SVM_INVALID_PVMCB);
1435
1436 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatLoadGuestState, x);
1437
1438 int rc = hmR0SvmLoadGuestControlRegs(pVCpu, pVmcb, pCtx);
1439 AssertLogRelMsgRCReturn(rc, ("hmR0SvmLoadGuestControlRegs! rc=%Rrc (pVM=%p pVCpu=%p)\n", rc, pVM, pVCpu), rc);
1440
1441 hmR0SvmLoadGuestSegmentRegs(pVCpu, pVmcb, pCtx);
1442 hmR0SvmLoadGuestMsrs(pVCpu, pVmcb, pCtx);
1443
1444 pVmcb->guest.u64RIP = pCtx->rip;
1445 pVmcb->guest.u64RSP = pCtx->rsp;
1446 pVmcb->guest.u64RFlags = pCtx->eflags.u32;
1447 pVmcb->guest.u8CPL = pCtx->ss.Attr.n.u2Dpl;
1448 pVmcb->guest.u64RAX = pCtx->rax;
1449
1450 /* hmR0SvmLoadGuestDebugRegs() must be called -after- updating guest RFLAGS as the RFLAGS may need to be changed. */
1451 hmR0SvmLoadGuestDebugRegs(pVCpu, pVmcb, pCtx);
1452
1453 rc = hmR0SvmLoadGuestApicState(pVCpu, pVmcb, pCtx);
1454 AssertLogRelMsgRCReturn(rc, ("hmR0SvmLoadGuestApicState! rc=%Rrc (pVM=%p pVCpu=%p)\n", rc, pVM, pVCpu), rc);
1455
1456 rc = hmR0SvmSetupVMRunHandler(pVCpu, pCtx);
1457 AssertLogRelMsgRCReturn(rc, ("hmR0SvmSetupVMRunHandler! rc=%Rrc (pVM=%p pVCpu=%p)\n", rc, pVM, pVCpu), rc);
1458
1459 /* Clear any unused and reserved bits. */
1460 pVCpu->hm.s.fContextUseFlags &= ~( HM_CHANGED_GUEST_SYSENTER_CS_MSR
1461 | HM_CHANGED_GUEST_SYSENTER_EIP_MSR
1462 | HM_CHANGED_GUEST_SYSENTER_ESP_MSR);
1463
1464 AssertMsg(!pVCpu->hm.s.fContextUseFlags,
1465 ("Missed updating flags while loading guest state. pVM=%p pVCpu=%p fContextUseFlags=%#RX32\n",
1466 pVM, pVCpu, pVCpu->hm.s.fContextUseFlags));
1467
1468 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatLoadGuestState, x);
1469
1470 return rc;
1471}
1472
1473
1474
1475/**
1476 * Saves the entire guest state from the VMCB into the
1477 * guest-CPU context. Currently there is no residual state left in the CPU that
1478 * is not updated in the VMCB.
1479 *
1480 * @returns VBox status code.
1481 * @param pVCpu Pointer to the VMCPU.
1482 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
1483 * out-of-sync. Make sure to update the required fields
1484 * before using them.
1485 */
1486static void hmR0SvmSaveGuestState(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
1487{
1488 Assert(VMMRZCallRing3IsEnabled(pVCpu));
1489
1490 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
1491
1492 pMixedCtx->rip = pVmcb->guest.u64RIP;
1493 pMixedCtx->rsp = pVmcb->guest.u64RSP;
1494 pMixedCtx->eflags.u32 = pVmcb->guest.u64RFlags;
1495 pMixedCtx->rax = pVmcb->guest.u64RAX;
1496
1497 /*
1498 * Guest interrupt shadow.
1499 */
1500 if (pVmcb->ctrl.u64IntShadow & SVM_INTERRUPT_SHADOW_ACTIVE)
1501 EMSetInhibitInterruptsPC(pVCpu, pMixedCtx->rip);
1502 else
1503 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
1504
1505 /*
1506 * Guest Control registers: CR2, CR3 (handled at the end) - accesses to other control registers are always intercepted.
1507 */
1508 pMixedCtx->cr2 = pVmcb->guest.u64CR2;
1509
1510 /*
1511 * Guest MSRs.
1512 */
1513 pMixedCtx->msrSTAR = pVmcb->guest.u64STAR; /* legacy syscall eip, cs & ss */
1514 pMixedCtx->msrLSTAR = pVmcb->guest.u64LSTAR; /* 64-bit mode syscall rip */
1515 pMixedCtx->msrCSTAR = pVmcb->guest.u64CSTAR; /* compatibility mode syscall rip */
1516 pMixedCtx->msrSFMASK = pVmcb->guest.u64SFMASK; /* syscall flag mask */
1517 pMixedCtx->msrKERNELGSBASE = pVmcb->guest.u64KernelGSBase; /* swapgs exchange value */
1518 pMixedCtx->SysEnter.cs = pVmcb->guest.u64SysEnterCS;
1519 pMixedCtx->SysEnter.eip = pVmcb->guest.u64SysEnterEIP;
1520 pMixedCtx->SysEnter.esp = pVmcb->guest.u64SysEnterESP;
1521
1522 /*
1523 * Guest segment registers (includes FS, GS base MSRs for 64-bit guests).
1524 */
1525 HMSVM_SAVE_SEG_REG(CS, ss);
1526 HMSVM_SAVE_SEG_REG(SS, cs);
1527 HMSVM_SAVE_SEG_REG(DS, ds);
1528 HMSVM_SAVE_SEG_REG(ES, es);
1529 HMSVM_SAVE_SEG_REG(FS, fs);
1530 HMSVM_SAVE_SEG_REG(GS, gs);
1531
1532 /*
1533 * Correct the hidden CS granularity flag. Haven't seen it being wrong in any other
1534 * register (yet).
1535 */
1536 /** @todo Verify this. */
1537 if ( !pMixedCtx->cs.Attr.n.u1Granularity
1538 && pMixedCtx->cs.Attr.n.u1Present
1539 && pMixedCtx->cs.u32Limit > UINT32_C(0xfffff))
1540 {
1541 Assert((pMixedCtx->cs.u32Limit & 0xfff) == 0xfff);
1542 pMixedCtx->cs.Attr.n.u1Granularity = 1;
1543 }
1544#ifdef VBOX_STRICT
1545# define HMSVM_ASSERT_SEL_GRANULARITY(reg) \
1546 AssertMsg( !pMixedCtx->reg.Attr.n.u1Present \
1547 || ( pMixedCtx->reg.Attr.n.u1Granularity \
1548 ? (pMixedCtx->reg.u32Limit & 0xfff) == 0xfff \
1549 : pMixedCtx->reg.u32Limit <= UINT32_C(0xfffff)), \
1550 ("Invalid Segment Attributes %#x %#x %#llx\n", pMixedCtx->reg.u32Limit,
1551 pMixedCtx->reg.Attr.u, pMixedCtx->reg.u64Base))
1552
1553 HMSVM_ASSERT_SEG_GRANULARITY(cs);
1554 HMSVM_ASSERT_SEG_GRANULARITY(ss);
1555 HMSVM_ASSERT_SEG_GRANULARITY(ds);
1556 HMSVM_ASSERT_SEG_GRANULARITY(es);
1557 HMSVM_ASSERT_SEG_GRANULARITY(fs);
1558 HMSVM_ASSERT_SEG_GRANULARITY(gs);
1559
1560# undef HMSVM_ASSERT_SEL_GRANULARITY
1561#endif
1562
1563 /*
1564 * Sync the hidden SS DPL field. AMD CPUs have a separate CPL field in the VMCB and uses that
1565 * and thus it's possible that when the CPL changes during guest execution that the SS DPL
1566 * isn't updated by AMD-V. Observed on some AMD Fusion CPUs with 64-bit guests.
1567 * See AMD spec. 15.5.1 "Basic operation".
1568 */
1569 Assert(!(pVmcb->guest.u8CPL & ~0x3));
1570 pMixedCtx->ss.Attr.n.u2Dpl = pVmcb->guest.u8CPL & 0x3;
1571
1572 /*
1573 * Guest Descriptor-Table registers.
1574 */
1575 HMSVM_SAVE_SEG_REG(TR, tr);
1576 HMSVM_SAVE_SEG_REG(LDTR, ldtr);
1577 pMixedCtx->gdtr.cbGdt = pVmcb->guest.GDTR.u32Limit;
1578 pMixedCtx->gdtr.pGdt = pVmcb->guest.GDTR.u64Base;
1579
1580 pMixedCtx->idtr.cbIdt = pVmcb->guest.IDTR.u32Limit;
1581 pMixedCtx->idtr.pIdt = pVmcb->guest.IDTR.u64Base;
1582
1583 /*
1584 * Guest Debug registers.
1585 */
1586 pMixedCtx->dr[6] = pVmcb->guest.u64DR6;
1587 pMixedCtx->dr[7] = pVmcb->guest.u64DR7;
1588
1589 /*
1590 * With Nested Paging, CR3 changes are not intercepted. Therefore, sync. it now.
1591 * This is done as the very last step of syncing the guest state, as PGMUpdateCR3() may cause longjmp's to ring-3.
1592 */
1593 if ( pVM->hm.s.fNestedPaging
1594 && pMixedCtx->cr3 != pVmcb->guest.u64CR3)
1595 {
1596 CPUMSetGuestCR3(pVCpu, pVmcb->guest.u64CR3);
1597 PGMUpdateCR3(pVCpu, pVmcb->guest.u64CR3);
1598 }
1599}
1600
1601
1602/**
1603 * Does the necessary state syncing before doing a longjmp to ring-3.
1604 *
1605 * @param pVM Pointer to the VM.
1606 * @param pVCpu Pointer to the VMCPU.
1607 * @param pCtx Pointer to the guest-CPU context.
1608 * @param rcExit The reason for exiting to ring-3. Can be
1609 * VINF_VMM_UNKNOWN_RING3_CALL.
1610 *
1611 * @remarks No-long-jmp zone!!!
1612 */
1613static void hmR0SvmLongJmpToRing3(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, int rcExit)
1614{
1615 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
1616 Assert(VMMR0IsLogFlushDisabled(pVCpu));
1617
1618 /* Restore host FPU state if necessary and resync on next R0 reentry .*/
1619 if (CPUMIsGuestFPUStateActive(pVCpu))
1620 {
1621 CPUMR0SaveGuestFPU(pVM, pVCpu, pCtx);
1622 Assert(!CPUMIsGuestFPUStateActive(pVCpu));
1623 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_GUEST_CR0;
1624 }
1625
1626 /* Restore host debug registers if necessary and resync on next R0 reentry. */
1627 if (CPUMIsGuestDebugStateActive(pVCpu))
1628 {
1629 CPUMR0SaveGuestDebugState(pVM, pVCpu, pCtx, true /* save DR6 */);
1630 Assert(!CPUMIsGuestDebugStateActive(pVCpu));
1631 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_GUEST_DEBUG;
1632 }
1633 else if (CPUMIsHyperDebugStateActive(pVCpu))
1634 {
1635 CPUMR0LoadHostDebugState(pVM, pVCpu);
1636 Assert(!CPUMIsHyperDebugStateActive(pVCpu));
1637 Assert(pVmcb->ctrl.u16InterceptRdDRx == 0xffff);
1638 Assert(pVmcb->ctrl.u16InterceptWrDRx == 0xffff);
1639 }
1640
1641 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchLongJmpToR3);
1642 VMCPU_CMPXCHG_STATE(pVCpu, VMCPUSTATE_STARTED_HM, VMCPUSTATE_STARTED_EXEC);
1643}
1644
1645
1646/**
1647 * VMMRZCallRing3() callback wrapper which saves the guest state (or restores
1648 * any remaining host state) before we longjump to ring-3 and possibly get
1649 * preempted.
1650 *
1651 * @param pVCpu Pointer to the VMCPU.
1652 * @param enmOperation The operation causing the ring-3 longjump.
1653 * @param pvUser The user argument (pointer to the possibly
1654 * out-of-date guest-CPU context).
1655 *
1656 * @remarks Must never be called with @a enmOperation ==
1657 * VMMCALLRING3_VM_R0_ASSERTION.
1658 */
1659DECLCALLBACK(void) hmR0SvmCallRing3Callback(PVMCPU pVCpu, VMMCALLRING3 enmOperation, void *pvUser)
1660{
1661 /* VMMRZCallRing3() already makes sure we never get called as a result of an longjmp due to an assertion, */
1662 Assert(pVCpu);
1663 Assert(pvUser);
1664 Assert(VMMRZCallRing3IsEnabled(pVCpu));
1665 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1666
1667 VMMRZCallRing3Disable(pVCpu);
1668 Assert(VMMR0IsLogFlushDisabled(pVCpu));
1669 Log4(("hmR0SvmCallRing3Callback->hmR0SvmLongJmpToRing3\n"));
1670 hmR0SvmLongJmpToRing3(pVCpu->CTX_SUFF(pVM), pVCpu, (PCPUMCTX)pvUser, VINF_VMM_UNKNOWN_RING3_CALL);
1671 VMMRZCallRing3Enable(pVCpu);
1672}
1673
1674
1675/**
1676 * An action requires us to go back to ring-3. This function does the necessary
1677 * steps before we can safely return to ring-3. This is not the same as longjmps
1678 * to ring-3, this is voluntary.
1679 *
1680 * @param pVM Pointer to the VM.
1681 * @param pVCpu Pointer to the VMCPU.
1682 * @param pCtx Pointer to the guest-CPU context.
1683 * @param rcExit The reason for exiting to ring-3. Can be
1684 * VINF_VMM_UNKNOWN_RING3_CALL.
1685 */
1686static void hmR0SvmExitToRing3(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, int rcExit)
1687{
1688 Assert(pVM);
1689 Assert(pVCpu);
1690 Assert(pCtx);
1691 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1692
1693 if (RT_UNLIKELY(rcExit == VERR_SVM_INVALID_GUEST_STATE))
1694 {
1695 /* We don't need to do any syncing here, we're not going to come back to execute anything again. */
1696 return;
1697 }
1698
1699 /* Please, no longjumps here (any logging shouldn't flush jump back to ring-3). NO LOGGING BEFORE THIS POINT! */
1700 VMMRZCallRing3Disable(pVCpu);
1701 Log4(("hmR0SvmExitToRing3: rcExit=%d\n", rcExit));
1702
1703 /* We need to do this only while truly exiting the "inner loop" back to ring-3 and -not- for any longjmp to ring3. */
1704 if (pVCpu->hm.s.Event.fPending)
1705 {
1706 hmR0SvmPendingEventToTrpmTrap(pVCpu);
1707 Assert(!pVCpu->hm.s.Event.fPending);
1708 }
1709
1710 /* Sync. the guest state. */
1711 hmR0SvmLongJmpToRing3(pVM, pVCpu, pCtx, rcExit);
1712 STAM_COUNTER_DEC(&pVCpu->hm.s.StatSwitchLongJmpToR3);
1713
1714 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_TO_R3);
1715 CPUMSetChangedFlags(pVCpu, CPUM_CHANGED_SYSENTER_MSR
1716 | CPUM_CHANGED_LDTR
1717 | CPUM_CHANGED_GDTR
1718 | CPUM_CHANGED_IDTR
1719 | CPUM_CHANGED_TR
1720 | CPUM_CHANGED_HIDDEN_SEL_REGS);
1721
1722 /* On our way back from ring-3 the following needs to be done. */
1723 /** @todo This can change with preemption hooks. */
1724 if (rcExit == VINF_EM_RAW_INTERRUPT)
1725 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_HOST_CONTEXT;
1726 else
1727 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_HOST_CONTEXT | HM_CHANGED_ALL_GUEST;
1728
1729 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchExitToR3);
1730 VMMRZCallRing3Enable(pVCpu);
1731}
1732
1733
1734/**
1735 * Sets up the usage of TSC offsetting for the VCPU.
1736 *
1737 * @param pVCpu Pointer to the VMCPU.
1738 *
1739 * @remarks No-long-jump zone!!!
1740 */
1741static void hmR0SvmSetupTscOffsetting(PVMCPU pVCpu)
1742{
1743 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
1744 if (TMCpuTickCanUseRealTSC(pVCpu, &pVmcb->ctrl.u64TSCOffset))
1745 {
1746 uint64_t u64CurTSC = ASMReadTSC();
1747 if (u64CurTSC + pVmcb->ctrl.u64TSCOffset > TMCpuTickGetLastSeen(pVCpu))
1748 {
1749 pVmcb->ctrl.u32InterceptCtrl1 &= ~SVM_CTRL1_INTERCEPT_RDTSC;
1750 pVmcb->ctrl.u32InterceptCtrl2 &= ~SVM_CTRL2_INTERCEPT_RDTSCP;
1751 STAM_COUNTER_INC(&pVCpu->hm.s.StatTscOffset);
1752 }
1753 else
1754 {
1755 pVmcb->ctrl.u32InterceptCtrl1 |= SVM_CTRL1_INTERCEPT_RDTSC;
1756 pVmcb->ctrl.u32InterceptCtrl2 |= SVM_CTRL2_INTERCEPT_RDTSCP;
1757 STAM_COUNTER_INC(&pVCpu->hm.s.StatTscInterceptOverFlow);
1758 }
1759 }
1760 else
1761 {
1762 pVmcb->ctrl.u32InterceptCtrl1 |= SVM_CTRL1_INTERCEPT_RDTSC;
1763 pVmcb->ctrl.u32InterceptCtrl2 |= SVM_CTRL2_INTERCEPT_RDTSCP;
1764 STAM_COUNTER_INC(&pVCpu->hm.s.StatTscIntercept);
1765 }
1766
1767 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
1768}
1769
1770
1771/**
1772 * Sets an event as a pending event to be injected into the guest.
1773 *
1774 * @param pVCpu Pointer to the VMCPU.
1775 * @param pEvent Pointer to the SVM event.
1776 * @param GCPtrFaultAddress The fault-address (CR2) in case it's a
1777 * page-fault.
1778 */
1779DECLINLINE(void) hmR0SvmSetPendingEvent(PVMCPU pVCpu, PSVMEVENT pEvent, RTGCUINTPTR GCPtrFaultAddress)
1780{
1781 Assert(!pVCpu->hm.s.Event.fPending);
1782
1783 pVCpu->hm.s.Event.u64IntrInfo = pEvent->u;
1784 pVCpu->hm.s.Event.fPending = true;
1785 pVCpu->hm.s.Event.GCPtrFaultAddress = GCPtrFaultAddress;
1786
1787#ifdef VBOX_STRICT
1788 if (GCPtrFaultAddress)
1789 {
1790 AssertMsg( pEvent->n.u8Vector == X86_XCPT_PF
1791 && pEvent->n.u3Type == SVM_EVENT_EXCEPTION,
1792 ("hmR0SvmSetPendingEvent: Setting fault-address for non-#PF. u8Vector=%#x Type=%#RX32 GCPtrFaultAddr=%#RGx\n",
1793 pEvent->n.u8Vector, (uint32_t)pEvent->n.u3Type, GCPtrFaultAddress));
1794 Assert(GCPtrFaultAddress == CPUMGetGuestCR2(pVCpu));
1795 }
1796#endif
1797
1798 Log4(("hmR0SvmSetPendingEvent: u=%#RX64 u8Vector=%#x ErrorCodeValid=%#x ErrorCode=%#RX32\n", pEvent->u,
1799 pEvent->n.u8Vector, pEvent->n.u3Type, (uint8_t)pEvent->n.u1ErrorCodeValid, pEvent->n.u32ErrorCode));
1800}
1801
1802
1803/**
1804 * Injects an event into the guest upon VMRUN by updating the relevant field
1805 * in the VMCB.
1806 *
1807 * @param pVCpu Pointer to the VMCPU.
1808 * @param pVmcb Pointer to the guest VMCB.
1809 * @param pCtx Pointer to the guest-CPU context.
1810 * @param pEvent Pointer to the event.
1811 *
1812 * @remarks No-long-jump zone!!!
1813 * @remarks Requires CR0!
1814 */
1815DECLINLINE(void) hmR0SvmInjectEventVmcb(PVMCPU pVCpu, PSVMVMCB pVmcb, PCPUMCTX pCtx, PSVMEVENT pEvent)
1816{
1817 pVmcb->ctrl.EventInject.u = pEvent->u;
1818 STAM_COUNTER_INC(&pVCpu->hm.s.paStatInjectedIrqsR0[pEvent->n.u8Vector & MASK_INJECT_IRQ_STAT]);
1819}
1820
1821
1822/**
1823 * Converts any TRPM trap into a pending SVM event. This is typically used when
1824 * entering from ring-3 (not longjmp returns).
1825 *
1826 * @param pVCpu Pointer to the VMCPU.
1827 */
1828static void hmR0SvmTrpmTrapToPendingEvent(PVMCPU pVCpu)
1829{
1830 Assert(TRPMHasTrap(pVCpu));
1831 Assert(!pVCpu->hm.s.Event.fPending);
1832
1833 uint8_t uVector;
1834 TRPMEVENT enmTrpmEvent;
1835 RTGCUINT uErrCode;
1836 RTGCUINTPTR GCPtrFaultAddress;
1837 uint8_t cbInstr;
1838
1839 int rc = TRPMQueryTrapAll(pVCpu, &uVector, &enmTrpmEvent, &uErrCode, &GCPtrFaultAddress, &cbInstr);
1840 AssertRC(rc);
1841
1842 PSVMEVENT pEvent = &pVCpu->hm.s.Event;
1843 pEvent->u = 0;
1844 pEvent->n.u1Valid = 1;
1845
1846 /* Refer AMD spec. 15.20 "Event Injection" for the format. */
1847 if (enmTrpmEvent == TRPM_TRAP)
1848 {
1849 pEvent->n.u3Type = SVM_EVENT_EXCEPTION;
1850 switch (uVector)
1851 {
1852 case X86_XCPT_PF:
1853 case X86_XCPT_DF:
1854 case X86_XCPT_TS:
1855 case X86_XCPT_NP:
1856 case X86_XCPT_SS:
1857 case X86_XCPT_GP:
1858 case X86_XCPT_AC:
1859 {
1860 pEvent->n.u32ErrorCode = uErrCode;
1861 pEvent->n.u1ErrorCodeValid = 1;
1862 break;
1863 }
1864 }
1865 }
1866 else if (enmTrpmEvent == TRPM_HARDWARE_INT)
1867 {
1868 if (uVector == X86_XCPT_NMI)
1869 pEvent->n.u3Type = SVM_EVENT_NMI;
1870 else
1871 pEvent->n.u3Type = SVM_EVENT_EXTERNAL_IRQ;
1872 }
1873 else if (enmTrpmEvent == TRPM_SOFTWARE_INT)
1874 pEvent->n.u3Type = SVM_EVENT_SOFTWARE_INT;
1875 else
1876 AssertMsgFailed(("Invalid TRPM event type %d\n", enmTrpmEvent));
1877
1878 rc = TRPMResetTrap(pVCpu);
1879 AssertRC(rc);
1880
1881 Log4(("TRPM->HM event: u=%#RX64 u8Vector=%#x uErrorCodeValid=%#x uErrorCode=%#RX32\n", pEvent->u, pEvent->n.u8Vector,
1882 pEvent->n.u1ErrorCodeValid, pEvent->n.u32ErrorCode));
1883}
1884
1885
1886/**
1887 * Converts any pending SVM event into a TRPM trap. Typically used when leaving
1888 * AMD-V to execute any instruction.
1889 *
1890 * @param pvCpu Pointer to the VMCPU.
1891 */
1892static void hmR0SvmPendingEventToTrpmTrap(PVMCPU pVCpu)
1893{
1894 Assert(pVCpu->hm.s.Event.fPending);
1895 Assert(TRPMQueryTrap(pVCpu, NULL /* pu8TrapNo */, NULL /* pEnmType */) == VERR_TRPM_NO_ACTIVE_TRAP);
1896
1897 PSVMEVENT pEvent = &pVCpu->hm.s.Event;
1898 uint8_t uVector = pEvent->n.u8Vector;
1899 uint8_t uVectorType = pEvent->n.u3Type;
1900
1901 TRPMEVENT enmTrapType;
1902 switch (uVectorType)
1903 {
1904 case SVM_EVENT_EXTERNAL_IRQ
1905 case SVM_EVENT_NMI:
1906 enmTrapType = TRPM_HARDWARE_INT;
1907 break;
1908 case SVM_EVENT_SOFTWARE_INT:
1909 enmTrapType = TRPM_SOFTWARE_INT;
1910 break;
1911 case SVM_EVENT_EXCEPTION:
1912 enmTrapType = TRPM_TRAP;
1913 break;
1914 default:
1915 AssertMsgFailed(("Invalid pending-event type %#x\n", uVectorType));
1916 enmTrapType = TRPM_32BIT_HACK;
1917 break;
1918 }
1919
1920 Log4(("HM event->TRPM: uVector=%#x enmTrapType=%d\n", uVector, uVectorType));
1921
1922 int rc = TRPMAssertTrap(pVCpu, uVector, enmTrapType);
1923 AssertRC(rc);
1924
1925 if (pEvent->n.u1ErrorCodeValid)
1926 TRPMSetErrorCode(pVCpu, pEvent->n.u32ErrorCode);
1927
1928 if ( uVectorType == SVM_EVENT_EXCEPTION
1929 && uVector == X86_XCPT_PF)
1930 {
1931 TRPMSetFaultAddress(pVCpu, pVCpu->hm.s.Event.GCPtrFaultAddress);
1932 Assert(pVCpu->hm.s.Event.GCPtrFaultAddress == CPUMGetGuestCR2(pVCpu));
1933 }
1934 else if (uVectorType == SVM_EVENT_SOFTWARE_INT)
1935 {
1936 AssertMsg( uVectorType == SVM_EVENT_SOFTWARE_INT
1937 || (uVector == X86_XCPT_BP || uVector == X86_XCPT_OF),
1938 ("Invalid vector: uVector=%#x uVectorType=%#x\n", uVector, uVectorType));
1939 TRPMSetInstrLength(pVCpu, pVCpu->hm.s.Event.cbInstr);
1940 }
1941 pVCpu->hm.s.Event.fPending = false;
1942}
1943
1944
1945/**
1946 * Gets the guest's interrupt-shadow.
1947 *
1948 * @returns The guest's interrupt-shadow.
1949 * @param pVCpu Pointer to the VMCPU.
1950 * @param pCtx Pointer to the guest-CPU context.
1951 *
1952 * @remarks No-long-jump zone!!!
1953 * @remarks Has side-effects with VMCPU_FF_INHIBIT_INTERRUPTS force-flag.
1954 */
1955DECLINLINE(uint32_t) hmR0SvmGetGuestIntrShadow(PVMCPU pVCpu, PCPUMCTX pCtx)
1956{
1957 /*
1958 * Instructions like STI and MOV SS inhibit interrupts till the next instruction completes. Check if we should
1959 * inhibit interrupts or clear any existing interrupt-inhibition.
1960 */
1961 uint32_t uIntrState = 0;
1962 if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
1963 {
1964 if (pCtx->rip != EMGetInhibitInterruptsPC(pVCpu))
1965 {
1966 /*
1967 * We can clear the inhibit force flag as even if we go back to the recompiler without executing guest code in
1968 * AMD-V, the flag's condition to be cleared is met and thus the cleared state is correct.
1969 */
1970 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
1971 }
1972 else
1973 uIntrState = SVM_INTERRUPT_SHADOW_ACTIVE;
1974 }
1975 return uIntrState;
1976}
1977
1978
1979/**
1980 * Sets the virtual interrupt intercept control in the VMCB which
1981 * instructs AMD-V to cause a #VMEXIT as soon as the guest is in a state to
1982 * receive interrupts.
1983 *
1984 * @param pVmcb Pointer to the VMCB.
1985 */
1986DECLINLINE(void) hmR0SvmSetVirtIntrIntercept(PSVMVMCB pVmcb)
1987{
1988 if (!(pVmcb->ctrl.u32InterceptCtrl1 & SVM_CTRL1_INTERCEPT_VINTR))
1989 {
1990 pVmcb->ctrl.IntCtrl.n.u1VIrqValid = 1; /* A virtual interrupt is pending. */
1991 pVmcb->ctrl.IntCtrl.n.u8VIrqVector = 0; /* Not necessary as we #VMEXIT for delivering the interrupt. */
1992 pVmcb->ctrl.u32InterceptCtrl1 |= SVM_CTRL1_INTERCEPT_VINTR;
1993 pVmcb->ctrl.u64VmcbCleanBits &= ~(HMSVM_VMCB_CLEAN_INTERCEPTS | HMSVM_VMCB_CLEAN_TPR);
1994 }
1995}
1996
1997
1998/**
1999 * Injects any pending events into the guest if the guest is in a state to
2000 * receive them.
2001 *
2002 * @param pVCpu Pointer to the VMCPU.
2003 * @param pCtx Pointer to the guest-CPU context.
2004 */
2005static void hmR0SvmInjectPendingEvent(PVMCPU pVCpu, PCPUMCTX pCtx)
2006{
2007 Assert(!TRPMHasTrap(pVCpu));
2008
2009 const bool fIntShadow = !!hmR0SvmGetGuestIntrShadow(pVCpu, pCtx);
2010 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
2011
2012 SVMEVENT Event;
2013 Event.u = 0;
2014 if (pVCpu->hm.s.Event.fPending) /* First, inject any pending HM events. */
2015 {
2016 Assert(Event.n.u1Valid);
2017 Event.u = pVCpu->hm.s.Event.u64IntrInfo;
2018 bool fInject = true;
2019 if ( fIntShadow
2020 && ( Event.n.u3Type == SVM_EVENT_EXTERNAL_IRQ
2021 || Event.n.u3Type == SVM_EVENT_NMI))
2022 {
2023 fInject = false;
2024 }
2025
2026 if (fInject)
2027 {
2028 pVCpu->hm.s.Event.fPending = false;
2029 hmR0SvmInjectEvent(pVCpu, pVmcb, pCtx, &Event);
2030 }
2031 else
2032 hmR0SvmSetVirtIntrIntercept(pVmcb);
2033 } /** @todo SMI. SMIs take priority over NMIs. */
2034 else if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INTERRUPT_NMI)) /* NMI. NMIs take priority over regular interrupts . */
2035 {
2036 if (!fIntShadow)
2037 {
2038 Log4(("Injecting NMI\n"));
2039
2040 Event.n.u1Valid = 1;
2041 Event.n.u8Vector = X86_XCPT_NMI;
2042 Event.n.u3Type = SVM_EVENT_NMI;
2043
2044 hmR0SvmInjectEvent(pVCpu, pVmcb, pCtx, &Event);
2045 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INTERRUPT_NMI);
2046 }
2047 else
2048 hmR0SvmSetVirtIntrIntercept(pVmcb);
2049 }
2050 else if (VMCPU_FF_IS_PENDING(pVCpu, (VMCPU_FF_INTERRUPT_APIC | VMCPU_FF_INTERRUPT_PIC)))
2051 {
2052 /* Check if there are guest external interrupts (PIC/APIC) pending and inject them, if the guest can receive them. */
2053 const bool fBlockInt = !(pCtx->eflags.u32 & X86_EFL_IF);
2054 if ( !fBlockInt
2055 && !fIntShadow)
2056 {
2057 uint8_t u8Interrupt;
2058 rc = PDMGetInterrupt(pVCpu, &u8Interrupt);
2059 if (RT_SUCCESS(rc))
2060 {
2061 Log4(("Injecting external interrupt u8Interrupt=%#x\n", u8Interrupt));
2062
2063 Event.n.u1Valid = 1;
2064 Event.n.u8Vector = u8Interrupt;
2065 Event.n.u3Type = SVM_EVENT_EXTERNAL_IRQ;
2066
2067 hmR0SvmInjectEvent(pVCpu, pVmcb, pCtx, &Event);
2068 STAM_COUNTER_INC(&pVCpu->hm.s.StatIntInject);
2069 }
2070 else
2071 {
2072 /** @todo Does this actually happen? If not turn it into an assertion. */
2073 Assert(!VMCPU_FF_IS_PENDING(pVCpu, (VMCPU_FF_INTERRUPT_APIC | VMCPU_FF_INTERRUPT_PIC)));
2074 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchGuestIrq);
2075 }
2076 }
2077 else
2078 hmR0SvmSetVirtIntrIntercept(pVmcb);
2079 }
2080
2081 /* Update the guest interrupt shadow in the VMCB. */
2082 pVmcb->ctrl.u64IntShadow = !!fIntShadow;
2083}
2084
2085
2086/**
2087 * Reports world-switch error and dumps some useful debug info.
2088 *
2089 * @param pVM Pointer to the VM.
2090 * @param pVCpu Pointer to the VMCPU.
2091 * @param rcVMRun The return code from VMRUN (or
2092 * VERR_SVM_INVALID_GUEST_STATE for invalid
2093 * guest-state).
2094 * @param pCtx Pointer to the guest-CPU context.
2095 */
2096static void hmR0SvmReportWorldSwitchError(PVM pVM, PVMCPU pVCpu, int rcVMRun, PCPUMCTX pCtx)
2097{
2098 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
2099 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
2100
2101 if (rcVMRun == VERR_SVM_INVALID_GUEST_STATE)
2102 {
2103 HMDumpRegs(pVM, pVCpu, pCtx);
2104#ifdef VBOX_STRICT
2105 Log4(("ctrl.u64VmcbCleanBits %#RX64\n", pVmcb->ctrl.u64VmcbCleanBits));
2106 Log4(("ctrl.u16InterceptRdCRx %#x\n", pVmcb->ctrl.u16InterceptRdCRx));
2107 Log4(("ctrl.u16InterceptWrCRx %#x\n", pVmcb->ctrl.u16InterceptWrCRx));
2108 Log4(("ctrl.u16InterceptRdDRx %#x\n", pVmcb->ctrl.u16InterceptRdDRx));
2109 Log4(("ctrl.u16InterceptWrDRx %#x\n", pVmcb->ctrl.u16InterceptWrDRx));
2110 Log4(("ctrl.u32InterceptException %#x\n", pVmcb->ctrl.u32InterceptException));
2111 Log4(("ctrl.u32InterceptCtrl1 %#x\n", pVmcb->ctrl.u32InterceptCtrl1));
2112 Log4(("ctrl.u32InterceptCtrl2 %#x\n", pVmcb->ctrl.u32InterceptCtrl2));
2113 Log4(("ctrl.u64IOPMPhysAddr %#RX64\n", pVmcb->ctrl.u64IOPMPhysAddr));
2114 Log4(("ctrl.u64MSRPMPhysAddr %#RX64\n", pVmcb->ctrl.u64MSRPMPhysAddr));
2115 Log4(("ctrl.u64TSCOffset %#RX64\n", pVmcb->ctrl.u64TSCOffset));
2116
2117 Log4(("ctrl.TLBCtrl.u32ASID %#x\n", pVmcb->ctrl.TLBCtrl.n.u32ASID));
2118 Log4(("ctrl.TLBCtrl.u8TLBFlush %#x\n", pVmcb->ctrl.TLBCtrl.n.u8TLBFlush));
2119 Log4(("ctrl.TLBCtrl.u24Reserved %#x\n", pVmcb->ctrl.TLBCtrl.n.u24Reserved));
2120
2121 Log4(("ctrl.IntCtrl.u8VTPR %#x\n", pVmcb->ctrl.IntCtrl.n.u8VTPR));
2122 Log4(("ctrl.IntCtrl.u1VIrqValid %#x\n", pVmcb->ctrl.IntCtrl.n.u1VIrqValid));
2123 Log4(("ctrl.IntCtrl.u7Reserved %#x\n", pVmcb->ctrl.IntCtrl.n.u7Reserved));
2124 Log4(("ctrl.IntCtrl.u4VIrqPriority %#x\n", pVmcb->ctrl.IntCtrl.n.u4VIrqPriority));
2125 Log4(("ctrl.IntCtrl.u1IgnoreTPR %#x\n", pVmcb->ctrl.IntCtrl.n.u1IgnoreTPR));
2126 Log4(("ctrl.IntCtrl.u3Reserved %#x\n", pVmcb->ctrl.IntCtrl.n.u3Reserved));
2127 Log4(("ctrl.IntCtrl.u1VIrqMasking %#x\n", pVmcb->ctrl.IntCtrl.n.u1VIrqMasking));
2128 Log4(("ctrl.IntCtrl.u6Reserved %#x\n", pVmcb->ctrl.IntCtrl.n.u6Reserved));
2129 Log4(("ctrl.IntCtrl.u8VIrqVector %#x\n", pVmcb->ctrl.IntCtrl.n.u8VIrqVector));
2130 Log4(("ctrl.IntCtrl.u24Reserved %#x\n", pVmcb->ctrl.IntCtrl.n.u24Reserved));
2131
2132 Log4(("ctrl.u64IntShadow %#RX64\n", pVmcb->ctrl.u64IntShadow));
2133 Log4(("ctrl.u64ExitCode %#RX64\n", pVmcb->ctrl.u64ExitCode));
2134 Log4(("ctrl.u64ExitInfo1 %#RX64\n", pVmcb->ctrl.u64ExitInfo1));
2135 Log4(("ctrl.u64ExitInfo2 %#RX64\n", pVmcb->ctrl.u64ExitInfo2));
2136 Log4(("ctrl.ExitIntInfo.u8Vector %#x\n", pVmcb->ctrl.ExitIntInfo.n.u8Vector));
2137 Log4(("ctrl.ExitIntInfo.u3Type %#x\n", pVmcb->ctrl.ExitIntInfo.n.u3Type));
2138 Log4(("ctrl.ExitIntInfo.u1ErrorCodeValid %#x\n", pVmcb->ctrl.ExitIntInfo.n.u1ErrorCodeValid));
2139 Log4(("ctrl.ExitIntInfo.u19Reserved %#x\n", pVmcb->ctrl.ExitIntInfo.n.u19Reserved));
2140 Log4(("ctrl.ExitIntInfo.u1Valid %#x\n", pVmcb->ctrl.ExitIntInfo.n.u1Valid));
2141 Log4(("ctrl.ExitIntInfo.u32ErrorCode %#x\n", pVmcb->ctrl.ExitIntInfo.n.u32ErrorCode));
2142 Log4(("ctrl.NestedPaging %#RX64\n", pVmcb->ctrl.NestedPaging.u));
2143 Log4(("ctrl.EventInject.u8Vector %#x\n", pVmcb->ctrl.EventInject.n.u8Vector));
2144 Log4(("ctrl.EventInject.u3Type %#x\n", pVmcb->ctrl.EventInject.n.u3Type));
2145 Log4(("ctrl.EventInject.u1ErrorCodeValid %#x\n", pVmcb->ctrl.EventInject.n.u1ErrorCodeValid));
2146 Log4(("ctrl.EventInject.u19Reserved %#x\n", pVmcb->ctrl.EventInject.n.u19Reserved));
2147 Log4(("ctrl.EventInject.u1Valid %#x\n", pVmcb->ctrl.EventInject.n.u1Valid));
2148 Log4(("ctrl.EventInject.u32ErrorCode %#x\n", pVmcb->ctrl.EventInject.n.u32ErrorCode));
2149
2150 Log4(("ctrl.u64NestedPagingCR3 %#RX64\n", pVmcb->ctrl.u64NestedPagingCR3));
2151 Log4(("ctrl.u64LBRVirt %#RX64\n", pVmcb->ctrl.u64LBRVirt));
2152
2153 Log4(("guest.CS.u16Sel %RTsel\n", pVmcb->guest.CS.u16Sel));
2154 Log4(("guest.CS.u16Attr %#x\n", pVmcb->guest.CS.u16Attr));
2155 Log4(("guest.CS.u32Limit %#RX32\n", pVmcb->guest.CS.u32Limit));
2156 Log4(("guest.CS.u64Base %#RX64\n", pVmcb->guest.CS.u64Base));
2157 Log4(("guest.DS.u16Sel %#RTsel\n", pVmcb->guest.DS.u16Sel));
2158 Log4(("guest.DS.u16Attr %#x\n", pVmcb->guest.DS.u16Attr));
2159 Log4(("guest.DS.u32Limit %#RX32\n", pVmcb->guest.DS.u32Limit));
2160 Log4(("guest.DS.u64Base %#RX64\n", pVmcb->guest.DS.u64Base));
2161 Log4(("guest.ES.u16Sel %RTsel\n", pVmcb->guest.ES.u16Sel));
2162 Log4(("guest.ES.u16Attr %#x\n", pVmcb->guest.ES.u16Attr));
2163 Log4(("guest.ES.u32Limit %#RX32\n", pVmcb->guest.ES.u32Limit));
2164 Log4(("guest.ES.u64Base %#RX64\n", pVmcb->guest.ES.u64Base));
2165 Log4(("guest.FS.u16Sel %RTsel\n", pVmcb->guest.FS.u16Sel));
2166 Log4(("guest.FS.u16Attr %#x\n", pVmcb->guest.FS.u16Attr));
2167 Log4(("guest.FS.u32Limit %#RX32\n", pVmcb->guest.FS.u32Limit));
2168 Log4(("guest.FS.u64Base %#RX64\n", pVmcb->guest.FS.u64Base));
2169 Log4(("guest.GS.u16Sel %RTsel\n", pVmcb->guest.GS.u16Sel));
2170 Log4(("guest.GS.u16Attr %#x\n", pVmcb->guest.GS.u16Attr));
2171 Log4(("guest.GS.u32Limit %#RX32\n", pVmcb->guest.GS.u32Limit));
2172 Log4(("guest.GS.u64Base %#RX64\n", pVmcb->guest.GS.u64Base));
2173
2174 Log4(("guest.GDTR.u32Limit %#RX32\n", pVmcb->guest.GDTR.u32Limit));
2175 Log4(("guest.GDTR.u64Base %#RX64\n", pVmcb->guest.GDTR.u64Base));
2176
2177 Log4(("guest.LDTR.u16Sel %RTsel\n", pVmcb->guest.LDTR.u16Sel));
2178 Log4(("guest.LDTR.u16Attr %#x\n", pVmcb->guest.LDTR.u16Attr));
2179 Log4(("guest.LDTR.u32Limit %#RX32\n", pVmcb->guest.LDTR.u32Limit));
2180 Log4(("guest.LDTR.u64Base %#RX64\n", pVmcb->guest.LDTR.u64Base));
2181
2182 Log4(("guest.IDTR.u32Limit %#RX32\n", pVmcb->guest.IDTR.u32Limit));
2183 Log4(("guest.IDTR.u64Base %#RX64\n", pVmcb->guest.IDTR.u64Base));
2184
2185 Log4(("guest.TR.u16Sel %RTsel\n", pVmcb->guest.TR.u16Sel));
2186 Log4(("guest.TR.u16Attr %#x\n", pVmcb->guest.TR.u16Attr));
2187 Log4(("guest.TR.u32Limit %#RX32\n", pVmcb->guest.TR.u32Limit));
2188 Log4(("guest.TR.u64Base %#RX64\n", pVmcb->guest.TR.u64Base));
2189
2190 Log4(("guest.u8CPL %#x\n", pVmcb->guest.u8CPL));
2191 Log4(("guest.u64CR0 %#RX64\n", pVmcb->guest.u64CR0));
2192 Log4(("guest.u64CR2 %#RX64\n", pVmcb->guest.u64CR2));
2193 Log4(("guest.u64CR3 %#RX64\n", pVmcb->guest.u64CR3));
2194 Log4(("guest.u64CR4 %#RX64\n", pVmcb->guest.u64CR4));
2195 Log4(("guest.u64DR6 %#RX64\n", pVmcb->guest.u64DR6));
2196 Log4(("guest.u64DR7 %#RX64\n", pVmcb->guest.u64DR7));
2197
2198 Log4(("guest.u64RIP %#RX64\n", pVmcb->guest.u64RIP));
2199 Log4(("guest.u64RSP %#RX64\n", pVmcb->guest.u64RSP));
2200 Log4(("guest.u64RAX %#RX64\n", pVmcb->guest.u64RAX));
2201 Log4(("guest.u64RFlags %#RX64\n", pVmcb->guest.u64RFlags));
2202
2203 Log4(("guest.u64SysEnterCS %#RX64\n", pVmcb->guest.u64SysEnterCS));
2204 Log4(("guest.u64SysEnterEIP %#RX64\n", pVmcb->guest.u64SysEnterEIP));
2205 Log4(("guest.u64SysEnterESP %#RX64\n", pVmcb->guest.u64SysEnterESP));
2206
2207 Log4(("guest.u64EFER %#RX64\n", pVmcb->guest.u64EFER));
2208 Log4(("guest.u64STAR %#RX64\n", pVmcb->guest.u64STAR));
2209 Log4(("guest.u64LSTAR %#RX64\n", pVmcb->guest.u64LSTAR));
2210 Log4(("guest.u64CSTAR %#RX64\n", pVmcb->guest.u64CSTAR));
2211 Log4(("guest.u64SFMASK %#RX64\n", pVmcb->guest.u64SFMASK));
2212 Log4(("guest.u64KernelGSBase %#RX64\n", pVmcb->guest.u64KernelGSBase));
2213 Log4(("guest.u64GPAT %#RX64\n", pVmcb->guest.u64GPAT));
2214 Log4(("guest.u64DBGCTL %#RX64\n", pVmcb->guest.u64DBGCTL));
2215 Log4(("guest.u64BR_FROM %#RX64\n", pVmcb->guest.u64BR_FROM));
2216 Log4(("guest.u64BR_TO %#RX64\n", pVmcb->guest.u64BR_TO));
2217 Log4(("guest.u64LASTEXCPFROM %#RX64\n", pVmcb->guest.u64LASTEXCPFROM));
2218 Log4(("guest.u64LASTEXCPTO %#RX64\n", pVmcb->guest.u64LASTEXCPTO));
2219#endif
2220 }
2221 else
2222 Log4(("hmR0SvmReportWorldSwitchError: rcVMRun=%d\n", rcVMRun));
2223}
2224
2225
2226/**
2227 * Check per-VM and per-VCPU force flag actions that require us to go back to
2228 * ring-3 for one reason or another.
2229 *
2230 * @returns VBox status code (information status code included).
2231 * @retval VINF_SUCCESS if we don't have any actions that require going back to
2232 * ring-3.
2233 * @retval VINF_PGM_SYNC_CR3 if we have pending PGM CR3 sync.
2234 * @retval VINF_EM_PENDING_REQUEST if we have pending requests (like hardware
2235 * interrupts)
2236 * @retval VINF_PGM_POOL_FLUSH_PENDING if PGM is doing a pool flush and requires
2237 * all EMTs to be in ring-3.
2238 * @retval VINF_EM_RAW_TO_R3 if there is pending DMA requests.
2239 * @retval VINF_EM_NO_MEMORY PGM is out of memory, we need to return
2240 * to the EM loop.
2241 *
2242 * @param pVM Pointer to the VM.
2243 * @param pVCpu Pointer to the VMCPU.
2244 * @param pCtx Pointer to the guest-CPU context.
2245 */
2246static int hmR0SvmCheckForceFlags(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
2247{
2248 Assert(VMMRZCallRing3IsEnabled(pVCpu));
2249
2250 if ( VM_FF_IS_PENDING(pVM, VM_FF_HM_TO_R3_MASK | VM_FF_REQUEST | VM_FF_PGM_POOL_FLUSH_PENDING | VM_FF_PDM_DMA)
2251 || VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_TO_R3_MASK | VMCPU_FF_PGM_SYNC_CR3 | VMCPU_FF_PGM_SYNC_CR3_NON_GLOBAL
2252 | VMCPU_FF_REQUEST | VMCPU_FF_HM_UPDATE_CR3))
2253 {
2254 /* Pending HM CR3 sync. No PAE PDPEs (VMCPU_FF_HM_UPDATE_PAE_PDPES) on AMD-V. */
2255 if (VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_UPDATE_CR3))
2256 {
2257 rc = PGMUpdateCR3(pVCpu, pCtx->cr3);
2258 Assert(rc == VINF_SUCCESS || rc == VINF_PGM_SYNC_CR3);
2259 Assert(!VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_UPDATE_CR3));
2260 }
2261
2262 /* Pending PGM C3 sync. */
2263 if (VMCPU_FF_IS_PENDING(pVCpu,VMCPU_FF_PGM_SYNC_CR3 | VMCPU_FF_PGM_SYNC_CR3_NON_GLOBAL))
2264 {
2265 rc = PGMSyncCR3(pVCpu, pCtx->cr0, pCtx->cr3, pCtx->cr4, VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_PGM_SYNC_CR3));
2266 if (rc != VINF_SUCCESS)
2267 {
2268 AssertRC(rc);
2269 Log4(("hmR0SvmCheckForceFlags: PGMSyncCR3 forcing us back to ring-3. rc=%d\n", rc));
2270 return rc;
2271 }
2272 }
2273
2274 /* Pending HM-to-R3 operations (critsects, timers, EMT rendezvous etc.) */
2275 /* -XXX- what was that about single stepping? */
2276 if ( VM_FF_IS_PENDING(pVM, VM_FF_HM_TO_R3_MASK)
2277 || VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_TO_R3_MASK))
2278 {
2279 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchHmToR3FF);
2280 rc = RT_UNLIKELY(VM_FF_IS_PENDING(pVM, VM_FF_PGM_NO_MEMORY)) ? VINF_EM_NO_MEMORY : VINF_EM_RAW_TO_R3;
2281 Log4(("hmR0SvmCheckForceFlags: HM_TO_R3 forcing us back to ring-3. rc=%d\n", rc));
2282 return rc;
2283 }
2284
2285 /* Pending VM request packets, such as hardware interrupts. */
2286 if ( VM_FF_IS_PENDING(pVM, VM_FF_REQUEST)
2287 || VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_REQUEST))
2288 {
2289 Log4(("hmR0SvmCheckForceFlags: Pending VM request forcing us back to ring-3\n"));
2290 return VINF_EM_PENDING_REQUEST;
2291 }
2292
2293 /* Pending PGM pool flushes. */
2294 if (VM_FF_IS_PENDING(pVM, VM_FF_PGM_POOL_FLUSH_PENDING))
2295 {
2296 Log4(("hmR0SvmCheckForceFlags: PGM pool flush pending forcing us back to ring-3\n"));
2297 return VINF_PGM_POOL_FLUSH_PENDING;
2298 }
2299
2300 /* Pending DMA requests. */
2301 if (VM_FF_IS_PENDING(pVM, VM_FF_PDM_DMA))
2302 {
2303 Log4(("hmR0SvmCheckForceFlags: Pending DMA request forcing us back to ring-3\n"));
2304 return VINF_EM_RAW_TO_R3;
2305 }
2306 }
2307
2308 /* Paranoia. */
2309 Assert(rc != VERR_EM_INTERPRETER);
2310 return VINF_SUCCESS;
2311}
2312
2313
2314/**
2315 * Does the preparations before executing guest code in AMD-V.
2316 *
2317 * This may cause longjmps to ring-3 and may even result in rescheduling to the
2318 * recompiler. We must be cautious what we do here regarding committing
2319 * guest-state information into the the VMCB assuming we assuredly execute the
2320 * guest in AMD-V. If we fall back to the recompiler after updating the VMCB and
2321 * clearing the common-state (TRPM/forceflags), we must undo those changes so
2322 * that the recompiler can (and should) use them when it resumes guest
2323 * execution. Otherwise such operations must be done when we can no longer
2324 * exit to ring-3.
2325 *
2326 * @returns VBox status code (informational status codes included).
2327 * @retval VINF_SUCCESS if we can proceed with running the guest.
2328 * @retval VINF_* scheduling changes, we have to go back to ring-3.
2329 *
2330 * @param pVCpu Pointer to the VMCPU.
2331 * @param pCtx Pointer to the guest-CPU context.
2332 * @param pSvmTransient Pointer to the SVM transient structure.
2333 */
2334DECLINE(int) hmR0SvmPreRunGuest(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
2335{
2336 /* Check force flag actions that might require us to go back to ring-3. */
2337 int rc = hmR0SvmCheckForceFlags(pVM, pVCpu, pCtx);
2338 if (rc != VINF_SUCCESS)
2339 return rc;
2340
2341#ifdef VBOX_WITH_VMMR0_DISABLE_PREEMPTION
2342 /* We disable interrupts so that we don't miss any interrupts that would flag preemption (IPI/timers etc.) */
2343 pSvmTransient->uEFlags = ASMIntDisableFlags();
2344 if (RTThreadPreemptIsPending(NIL_RTTHREAD))
2345 {
2346 ASMSetFlags(pSvmTransient->uEFlags);
2347 STAM_COUNTER_INC(&pVCpu->hm.s.StatPendingHostIrq);
2348 /* Don't use VINF_EM_RAW_INTERRUPT_HYPER as we can't assume the host does kernel preemption. Maybe some day? */
2349 return VINF_EM_RAW_INTERRUPT;
2350 }
2351 VMCPU_ASSERT_STATE(pVCpu, VMCPUSTATE_STARTED_HM);
2352 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_EXEC);
2353#endif
2354
2355 /* Convert any pending TRPM traps to HM events for injection. */
2356 /** @todo Optimization: move this before disabling interrupts, restore state
2357 * using pVmcb->ctrl.EventInject.u. */
2358 if (TRPMHasTrap(pVCpu))
2359 hmR0SvmTrpmTrapToPendingEvent(pVCpu);
2360
2361 hmR0SvmInjectPendingEvent(pVCpu, pCtx);
2362
2363 return VINF_SUCCESS;
2364}
2365
2366
2367/**
2368 * Prepares to run guest code in VT-x and we've committed to doing so. This
2369 * means there is no backing out to ring-3 or anywhere else at this
2370 * point.
2371 *
2372 * @param pVM Pointer to the VM.
2373 * @param pVCpu Pointer to the VMCPU.
2374 * @param pCtx Pointer to the guest-CPU context.
2375 * @param pSvmTransient Pointer to the SVM transient structure.
2376 *
2377 * @remarks Called with preemption disabled.
2378 * @remarks No-long-jump zone!!!
2379 */
2380DECLINLINE(void) hmR0SvmPreRunGuestCommitted(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
2381{
2382 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
2383 Assert(VMMR0IsLogFlushDisabled(pVCpu));
2384
2385#ifndef VBOX_WITH_VMMR0_DISABLE_PREEMPTION
2386 /** @todo I don't see the point of this, VMMR0EntryFast() already disables interrupts for the entire period. */
2387 pSvmTransient->uEFlags = ASMIntDisableFlags();
2388 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_EXEC);
2389#endif
2390
2391 /*
2392 * Re-enable nested paging (automatically disabled on every VM-exit). See AMD spec. 15.25.3 "Enabling Nested Paging".
2393 * We avoid changing the corresponding VMCB Clean Bit as we're not changing it to a different value since the previous run.
2394 */
2395 /** @todo The above assumption could be wrong. It's not documented what
2396 * should be done wrt to the VMCB Clean Bit, but we'll find out the
2397 * hard way. */
2398 pVmcb->ctrl.NestedPaging.n.u1NestedPaging = pVM->hm.s.fNestedPaging;
2399
2400 /* Load the guest state. */
2401 int rc = SVMR0LoadGuestState(pVM, pVCpu, pCtx);
2402 AssertRC(rc);
2403 AssertMsg(!pVCpu->hm.s.fContextUseFlags, ("fContextUseFlags =%#x\n", pVCpu->hm.s.fContextUseFlags));
2404 STAM_COUNTER_INC(&pVCpu->hm.s.StatLoadFull);
2405
2406 /*
2407 * If we're not intercepting TPR changes in the guest, save the guest TPR before the world-switch
2408 * so we can update it on the way back if the guest changed the TPR.
2409 */
2410 if (pVCpu->hm.s.svm.fSyncVTpr)
2411 {
2412 if (pVM->hm.s.fTPRPatchingActive)
2413 pSvmTransient->u8GuestTpr = pCtx->msrLSTAR;
2414 else
2415 pSvmTransient->u8GuestTpr = pVmcb->ctrl.IntCtrl.n.u8VTPR;
2416 }
2417
2418 /* Flush the appropriate tagged-TLB entries. */
2419 ASMAtomicWriteBool(&pVCpu->hm.s.fCheckedTLBFlush, true); /* Used for TLB-shootdowns, set this across the world switch. */
2420 hmR0SvmFlushTaggedTlb(pVCpu);
2421 Assert(HMR0GetCurrentCpu()->idCpu == pVCpu->hm.s.idLastCpu);
2422
2423 TMNotifyStartOfExecution(pVCpu); /* Finally, notify TM to resume its clocks as we're about
2424 to start executing. */
2425
2426 /*
2427 * Save the current Host TSC_AUX and write the guest TSC_AUX to the host, so that
2428 * RDTSCPs (that don't cause exits) reads the guest MSR. See @bugref{3324}.
2429 *
2430 * This should be done -after- any RDTSCPs for obtaining the host timestamp (TM, STAM etc).
2431 */
2432 if ( (pVM->hm.s.cpuid.u32AMDFeatureEDX & X86_CPUID_EXT_FEATURE_EDX_RDTSCP)
2433 && !(pVmcb->ctrl.u32InterceptCtrl2 & SVM_CTRL2_INTERCEPT_RDTSCP))
2434 {
2435 pVCpu->hm.s.u64HostTscAux = ASMRdMsr(MSR_K8_TSC_AUX);
2436 uint64_t u64GuestTscAux = 0;
2437 rc2 = CPUMQueryGuestMsr(pVCpu, MSR_K8_TSC_AUX, &u64GuestTscAux);
2438 AssertRC(rc2);
2439 ASMWrMsr(MSR_K8_TSC_AUX, u64GuestTscAux);
2440 }
2441}
2442
2443
2444/**
2445 * Wrapper for running the guest code in AMD-V.
2446 *
2447 * @returns VBox strict status code.
2448 * @param pVM Pointer to the VM.
2449 * @param pVCpu Pointer to the VMCPU.
2450 * @param pCtx Pointer to the guest-CPU context.
2451 *
2452 * @remarks No-long-jump zone!!!
2453 */
2454DECLINLINE(int) hmR0SvmRunGuest(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
2455{
2456 /*
2457 * 64-bit Windows uses XMM registers in the kernel as the Microsoft compiler expresses floating-point operations
2458 * using SSE instructions. Some XMM registers (XMM6-XMM15) are callee-saved and thus the need for this XMM wrapper.
2459 * Refer MSDN docs. "Configuring Programs for 64-bit / x64 Software Conventions / Register Usage" for details.
2460 */
2461#ifdef VBOX_WITH_KERNEL_USING_XMM
2462 return HMR0SVMRunWrapXMM(pVCpu->hm.s.svm.HCPhysVmcbHost, pVCpu->hm.s.svm.HCPhysVmcb, pCtx, pVM, pVCpu,
2463 pVCpu->hm.s.svm.pfnVMRun);
2464#else
2465 return pVCpu->hm.s.svm.pfnVMRun(pVCpu->hm.s.svm.HCPhysVmcbHost, pVCpu->hm.s.svm.HCPhysVmcb, pCtx, pVM, pVCpu);
2466#endif
2467}
2468
2469
2470/**
2471 * Performs some essential restoration of state after running guest code in
2472 * AMD-V.
2473 *
2474 * @param pVM Pointer to the VM.
2475 * @param pVCpu Pointer to the VMCPU.
2476 * @param pMixedCtx Pointer to the guest-CPU context. The data maybe
2477 * out-of-sync. Make sure to update the required fields
2478 * before using them.
2479 * @param pSvmTransient Pointer to the SVM transient structure.
2480 * @param rcVMRun Return code of VMRUN.
2481 *
2482 * @remarks Called with interrupts disabled.
2483 * @remarks No-long-jump zone!!! This function will however re-enable longjmps
2484 * unconditionally when it is safe to do so.
2485 */
2486DECLINLINE(void) hmR0SvmPostRunGuest(PVM pVM, PVMCPU pVCpu, PCPUMCTX pMixedCtx, PSVMTRANSIENT pSvmTransient, rcVMRun)
2487{
2488 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
2489
2490 ASMAtomicWriteBool(&pVCpu->hm.s.fCheckedTLBFlush, false); /* See HMInvalidatePageOnAllVCpus(): used for TLB-shootdowns. */
2491 ASMAtomicIncU32(&pVCpu->hm.s.cWorldSwitchExits); /* Initialized in vmR3CreateUVM(): used for TLB-shootdowns. */
2492
2493 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
2494 pVmcb->ctrl.u64VmcbCleanBits = HMSVM_VMCB_CLEAN_ALL; /* Mark the VMCB-state cache as unmodified by VMM. */
2495
2496 /* Restore host's TSC_AUX if required. */
2497 if (!(pVmcb->ctrl.u32InterceptCtrl1 & SVM_CTRL1_INTERCEPT_RDTSC))
2498 {
2499 if (pVM->hm.s.cpuid.u32AMDFeatureEDX & X86_CPUID_EXT_FEATURE_EDX_RDTSCP)
2500 ASMWrMsr(MSR_K8_TSC_AUX, pVCpu->hm.s.u64HostTscAux);
2501
2502 /** @todo Find a way to fix hardcoding a guestimate. */
2503 TMCpuTickSetLastSeen(pVCpu, ASMReadTSC() +
2504 pVmcb->ctrl.u64TSCOffset - 0x400);
2505 }
2506
2507 TMNotifyEndOfExecution(pVCpu); /* Notify TM that the guest is no longer running. */
2508 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_HM);
2509
2510 Assert(!(ASMGetFlags() & X86_EFL_IF));
2511 ASMSetFlags(pSvmTransient->uEFlags); /* Enable interrupts. */
2512
2513 VMMRZCallRing3SetNotification(pVCpu, hmR0SvmCallRing3Callback, pMixedCtx);
2514 VMMRZCallRing3Enable(pVCpu); /* It is now safe to do longjmps to ring-3!!! */
2515
2516 /* If VMRUN failed, we can bail out early. This does -not- cover SVM_EXIT_INVALID. */
2517 if (RT_UNLIKELY(rcVMRun != VINF_SUCCESS))
2518 {
2519 Log4(("VMRUN failure: rcVMRun=%Rrc\n", rcVMRun));
2520 return;
2521 }
2522
2523 pSvmTransient->u64ExitCode = pVmcb->ctrl.u64ExitCode;
2524 hmR0SvmSaveGuestState(pVCpu, pMixedCtx); /* Save the guest state from the VMCB to the guest-CPU context. */
2525
2526 if (RT_LIKELY(pSvmTransient->u64ExitCode != SVM_EXIT_INVALID))
2527 {
2528 if (pVCpu->hm.s.svm.fSyncVTpr)
2529 {
2530 /* TPR patching (for 32-bit guests) uses LSTAR MSR for holding the TPR value, otherwise uses the VTPR. */
2531 if ( pVM->hm.s.fTPRPatchingActive
2532 && (pCtx->msrLSTAR & 0xff) != pSvmTransient->u8GuestTpr)
2533 {
2534 int rc = PDMApicSetTPR(pVCpu, pCtx->msrLSTAR & 0xff);
2535 AssertRC(rc);
2536 }
2537 else if ((uint8_t)(pSvmTransient->u8GuestTpr >> 4) != pVmcb->ctrl.IntCtrl.n.u8VTPR)
2538 {
2539 int rc = PDMApicSetTPR(pVCpu, (pVmcb->ctrl.IntCtrl.n.u8VTPR << 4));
2540 AssertRC(rc);
2541 }
2542 }
2543
2544 /* -XXX- premature interruption during event injection */
2545 }
2546}
2547
2548
2549/**
2550 * Runs the guest code using AMD-V.
2551 *
2552 * @returns VBox status code.
2553 * @param pVM Pointer to the VM.
2554 * @param pVCpu Pointer to the VMCPU.
2555 * @param pCtx Pointer to the guest-CPU context.
2556 */
2557VMMR0DECL(int) SVMR0RunGuestCode(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
2558{
2559 Assert(VMMRZCallRing3IsEnabled(pVCpu));
2560 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
2561
2562 SVMTRANSIENT SvmTransient;
2563 uint32_t cLoops = 0;
2564 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
2565 int rc = VERR_INTERNAL_ERROR_5;
2566
2567 for (;; cLoops++)
2568 {
2569 Assert(!HMR0SuspendPending());
2570 AssertMsg(pVCpu->hm.s.idEnteredCpu == RTMpCpuId(),
2571 ("Illegal migration! Entered on CPU %u Current %u cLoops=%u\n", (unsigned)pVCpu->hm.s.idEnteredCpu,
2572 (unsigned)RTMpCpuId(), cLoops));
2573
2574 /* Preparatory work for running guest code, this may return to ring-3 for some last minute updates. */
2575 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatEntry, x);
2576 rc = hmR0SvmPreRunGuest(pVM, pVCpu, pCtx, &SvmTransient);
2577 if (rc != VINF_SUCCESS)
2578 break;
2579
2580 /*
2581 * No longjmps to ring-3 from this point on!!!
2582 * Asserts() will still longjmp to ring-3 (but won't return), which is intentional, better than a kernel panic.
2583 * This also disables flushing of the R0-logger instance (if any).
2584 */
2585 VMMRZCallRing3Disable(pVCpu);
2586 VMMRZCallRing3RemoveNotification(pVCpu);
2587 hmR0SvmPreRunGuestCommitted(pVM, pVCpu, pCtx, &SvmTransient);
2588
2589 rc = hmR0SvmRunGuest(pVM, pVCpu, pCtx);
2590
2591 /*
2592 * Restore any residual host-state and save any bits shared between host and guest into the guest-CPU state.
2593 * This will also re-enable longjmps to ring-3 when it has reached a safe point!!!
2594 */
2595 hmR0SvmPostRunGuest(pVM, pVCpu, pCtx, &SvmTransient, rc);
2596 if (RT_UNLIKELY( rc != VINF_SUCCESS /* Check for errors with running the VM (VMRUN). */
2597 || SvmTransient.u64ExitCode == SVM_EXIT_INVALID)) /* Check for errors due to invalid guest state. */
2598 {
2599 if (rc == VINF_SUCCESS);
2600 rc = VERR_SVM_INVALID_GUEST_STATE;
2601 hmR0SvmReportWorldSwitchError(pVM, pVCpu, rc, pCtx, &SvmTransient);
2602 return rc;
2603 }
2604
2605 /* Handle the #VMEXIT. */
2606 AssertMsg(SvmTransient.u64ExitCode != SVM_EXIT_INVALID, ("%#x\n", SvmTransient.u64ExitCode));
2607 HMSVM_EXITCODE_STAM_COUNTER_INC(SvmTransient.u64ExitCode);
2608 rc = hmR0SvmHandleExit(pVCpu, pCtx, &SvmTransient);
2609 if (rc != VINF_SUCCESS)
2610 break;
2611 else if (cLoops > pVM->hm.s.cMaxResumeLoops)
2612 {
2613 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitMaxResume);
2614 rc = VINF_EM_RAW_INTERRUPT;
2615 break;
2616 }
2617 }
2618
2619 if (rc == VERR_EM_INTERPRETER)
2620 rc = VINF_EM_RAW_EMULATE_INSTR;
2621 else if (rc == VINF_EM_RESET)
2622 rc = VINF_EM_TRIPLE_FAULT;
2623 hmR0SvmExitToRing3(pVM, pVCpu, pCtx, rc);
2624 return rc;
2625}
2626
2627
2628/**
2629 * Handles a #VMEXIT (for all EXITCODE values except SVM_EXIT_INVALID).
2630 *
2631 * @returns VBox status code (informational status codes included).
2632 * @param pVCpu Pointer to the VMCPU.
2633 * @param pCtx Pointer to the guest-CPU context.
2634 * @param pSvmTransient Pointer to the SVM transient structure.
2635 */
2636DECLINLINE(int) hmR0SvmHandleExit(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
2637{
2638 Assert(pSvmTransient->u64ExitCode > 0);
2639 Assert(pSvmTransient->u64ExitCode <= SVM_EXIT_MAX);
2640
2641 /*
2642 * The ordering of the case labels is based on most-frequently-occurring VM-exits for most guests under
2643 * normal workloads (for some definition of "normal").
2644 */
2645 uint32_t u32ExitCode = pSvmTransient->u64ExitCode;
2646 switch (pSvmTransient->u64ExitCode)
2647 {
2648 /** @todo */
2649 //SVM_EXIT_EXCEPTION_x:
2650
2651 case SVM_EXIT_NPF:
2652 return hmR0SvmExitNestedPF(pVCpu, pCtx, pSvmTransient);
2653
2654 case SVM_EXIT_IOIO:
2655 return hmR0SvmExitIOInstr(pVCpu, pCtx, pSvmTransient);
2656
2657 case SVM_EXIT_RDTSC:
2658 return hmR0SvmExitRdtsc(pVCpu, pCtx, pSvmTransient);
2659
2660 case SVM_EXIT_RDTSCP:
2661 return hmR0SvmExitRdtscp(pVCpu, pCtx, pSvmTransient);
2662
2663 case SVM_EXIT_CPUID:
2664 return hmR0SvmExitCpuid(pVCpu, pCtx, pSvmTransient);
2665
2666 case SVM_EXIT_MONITOR:
2667 return hmR0SvmExitMonitor(pVCpu, pCtx, pSvmTransient);
2668
2669 case SVM_EXIT_MWAIT:
2670 return hmR0SvmExitMwait(pVCpu, pCtx, pSvmTransient);
2671
2672 case SVM_EXIT_READ_CR0:
2673 case SVM_EXIT_READ_CR3:
2674 case SVM_EXIT_READ_CR4:
2675 return hmR0SvmExitReadCRx(pVCpu, pCtx, pSvmTransient);
2676
2677 case SVM_EXIT_WRITE_CR0:
2678 case SVM_EXIT_WRITE_CR3:
2679 case SVM_EXIT_WRITE_CR4:
2680 case SVM_EXIT_WRITE_CR8:
2681 return hmR0SvmExitWriteCRx(pVCpu, pCtx, pSvmTransient);
2682
2683 case SVM_EXIT_VINTR:
2684 return hmR0SvmExitVIntr(pVCpu, pCtx, pSvmTransient);
2685
2686 case SVM_EXIT_INTR:
2687 case SVM_EXIT_FERR_FREEZE:
2688 case SVM_EXIT_NMI:
2689 case SVM_EXIT_INIT:
2690 return hmR0SvmExitIntr(pVCpu, pCtx, pSvmTransient);
2691
2692 case SVM_EXIT_MSR:
2693 return hmR0SvmExitMsr(pVCpu, pCtx, pSvmTransient);
2694
2695 case SVM_EXIT_INVLPG:
2696 return hmR0SvmExitInvlpg(pVCpu, pCtx, pSvmTransient);
2697
2698 case SVM_EXIT_WBINVD:
2699 return hmR0SvmExitWbinvd(pVCpu, pCtx, pSvmTransient);
2700
2701 case SVM_EXIT_INVD:
2702 return hmR0SvmExitInvd(pVCpu, pCtx, pSvmTransient);
2703
2704 case SVM_EXIT_RDPMC:
2705 return hmR0SvmExitRdpmc(pVCpu, pCtx, pSvmTransient);
2706
2707 default:
2708 {
2709 case SVM_EXIT_READ_DR0: case SVM_EXIT_READ_DR1: case SVM_EXIT_READ_DR2: case SVM_EXIT_READ_DR3:
2710 case SVM_EXIT_READ_DR6: case SVM_EXIT_READ_DR7: case SVM_EXIT_READ_DR8: case SVM_EXIT_READ_DR9:
2711 case SVM_EXIT_READ_DR10: case SVM_EXIT_READ_DR11: case SVM_EXIT_READ_DR12: case SVM_EXIT_READ_DR13:
2712 case SVM_EXIT_READ_DR14: case SVM_EXIT_READ_DR15:
2713 return hmR0SvmExitReadDRx(pVCpu, pCtx, pSvmTransient);
2714
2715 case SVM_EXIT_WRITE_DR0: case SVM_EXIT_WRITE_DR1: case SVM_EXIT_WRITE_DR2: case SVM_EXIT_WRITE_DR3:
2716 case SVM_EXIT_WRITE_DR6: case SVM_EXIT_WRITE_DR7: case SVM_EXIT_WRITE_DR8: case SVM_EXIT_WRITE_DR9:
2717 case SVM_EXIT_WRITE_DR10: case SVM_EXIT_WRITE_DR11: case SVM_EXIT_WRITE_DR12: case SVM_EXIT_WRITE_DR13:
2718 case SVM_EXIT_WRITE_DR14: case SVM_EXIT_WRITE_DR15:
2719 return hmR0SvmExitWriteDRx(pVCpu, pCtx, pSvmTransient);
2720
2721 case SVM_EXIT_TASK_SWITCH:
2722 return hmR0SvmExitTaskSwitch(pVCpu, pCtx, pSvmTransient);
2723
2724 case SVM_EXIT_VMMCALL:
2725 return hmR0SvmExitVmmCall(pVCpu, pCtx, pSvmTransient);
2726
2727 case SVM_EXIT_INVLPGA:
2728 case SVM_EXIT_RSM:
2729 case SVM_EXIT_VMRUN:
2730 case SVM_EXIT_VMLOAD:
2731 case SVM_EXIT_VMSAVE:
2732 case SVM_EXIT_STGI:
2733 case SVM_EXIT_CLGI:
2734 case SVM_EXIT_SKINIT:
2735 return hmR0SvmExitSetPendingXcptUD(pVCpu, pCtx, pSvmTransient);
2736
2737 default:
2738 {
2739 AssertMsgFailed(("hmR0SvmHandleExit: Unexpected exit code %#x\n", u32ExitCode));
2740 return VERR_SVM_UNEXPECTED_EXIT;
2741 }
2742 }
2743 }
2744 return VERR_INTERNAL_ERROR_5; /* Should never happen. */
2745}
2746
2747
2748#ifdef DEBUG
2749/* Is there some generic IPRT define for this that are not in Runtime/internal/\* ?? */
2750# define HMSVM_ASSERT_PREEMPT_CPUID_VAR() \
2751 RTCPUID const idAssertCpu = RTThreadPreemptIsEnabled(NIL_RTTHREAD) ? NIL_RTCPUID : RTMpCpuId()
2752
2753# define HMSVM_ASSERT_PREEMPT_CPUID() \
2754 do \
2755 { \
2756 RTCPUID const idAssertCpuNow = RTThreadPreemptIsEnabled(NIL_RTTHREAD) ? NIL_RTCPUID : RTMpCpuId(); \
2757 AssertMsg(idAssertCpu == idAssertCpuNow, ("SVM %#x, %#x\n", idAssertCpu, idAssertCpuNow)); \
2758 } while (0)
2759
2760# define HMSVM_VALIDATE_EXIT_HANDLER_PARAMS() \
2761 do { \
2762 AssertPtr(pVCpu); \
2763 AssertPtr(pMixedCtx); \
2764 AssertPtr(pSvmTransient); \
2765 Assert(ASMIntAreEnabled()); \
2766 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD)); \
2767 HMSVM_ASSERT_PREEMPT_CPUID_VAR(); \
2768 Log4Func(("vcpu[%u] -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)); \
2769 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD)); \
2770 if (VMMR0IsLogFlushDisabled(pVCpu)) \
2771 HMSVM_ASSERT_PREEMPT_CPUID(); \
2772 HMSVM_STOP_EXIT_DISPATCH_PROF(); \
2773 } while (0)
2774#else /* Release builds */
2775# define HMSVM_VALIDATE_EXIT_HANDLER_PARAMS() do { } while(0)
2776#endif
2777
2778
2779/**
2780 * Worker for hmR0SvmInterpretInvlpg().
2781 *
2782 * @return VBox status code.
2783 * @param pVCpu Pointer to the VMCPU.
2784 * @param pCpu Pointer to the disassembler state.
2785 * @param pRegFrame Pointer to the register frame.
2786 */
2787static int hmR0SvmInterpretInvlPgEx(PVMCPU pVCpu, PDISCPUSTATE pCpu, PCPUMCTXCORE pRegFrame)
2788{
2789 DISQPVPARAMVAL Param1;
2790 RTGCPTR GCPtrPage;
2791
2792 int rc = DISQueryParamVal(pRegFrame, pCpu, &pCpu->Param1, &Param1, DISQPVWHICH_SRC);
2793 if (RT_FAILURE(rc))
2794 return VERR_EM_INTERPRETER;
2795
2796 if ( Param1.type == DISQPV_TYPE_IMMEDIATE
2797 || Param1.type == DISQPV_TYPE_ADDRESS)
2798 {
2799 if (!(Param1.flags & (DISQPV_FLAG_32 | DISQPV_FLAG_64)))
2800 return VERR_EM_INTERPRETER;
2801
2802 GCPtrPage = Param1.val.val64;
2803 rc = EMInterpretInvlpg(pVCpu->CTX_SUFF(pVM), pVCpu, pRegFrame, GCPtrPage);
2804 }
2805 else
2806 {
2807 Log4(("hmR0SvmInterpretInvlPgEx invalid parameter type %#x\n", Param1.type));
2808 rc = VERR_EM_INTERPRETER;
2809 }
2810
2811 return rc;
2812}
2813
2814
2815/**
2816 * Interprets INVLPG.
2817 *
2818 * @returns VBox status code.
2819 * @retval VINF_* Scheduling instructions.
2820 * @retval VERR_EM_INTERPRETER Something we can't cope with.
2821 * @retval VERR_* Fatal errors.
2822 *
2823 * @param pVM Pointer to the VM.
2824 * @param pRegFrame Pointer to the register frame.
2825 *
2826 * @remarks Updates the RIP if the instruction was executed successfully.
2827 */
2828static int hmR0SvmInterpretInvlpg(PVM pVM, PVMCPU pVCpu, PCPUMCTXCORE pRegFrame)
2829{
2830 /* Only allow 32 & 64 bit code. */
2831 if (CPUMGetGuestCodeBits(pVCpu) != 16)
2832 {
2833 PDISSTATE pDis = &pVCpu->hm.s.DisState;
2834 int rc = EMInterpretDisasCurrent(pVM, pVCpu, pDis, NULL /* pcbInstr */);
2835 if ( RT_SUCCESS(rc)
2836 && pDis->pCurInstr->uOpcode == OP_INVLPG)
2837 {
2838 rc = hmR0SvmInterpretInvlPgEx(pVCpu, pDis, pRegFrame);
2839 if (RT_SUCCESS(rc))
2840 pRegFrame->rip += pDis->cbInstr;
2841 return rc;
2842 }
2843 else
2844 Log4(("hmR0SvmInterpretInvlpg: EMInterpretDisasCurrent returned %Rrc uOpCode=%#x\n", rc, pDis->pCurInstr->uOpcode));
2845 }
2846 return VERR_EM_INTERPRETER;
2847}
2848
2849
2850/**
2851 * Sets an invalid-opcode (#UD) exception as pending-for-injection into the VM.
2852 *
2853 * @param pVCpu Pointer to the VMCPU.
2854 */
2855DECLINLINE(void) hmR0SvmSetPendingXcptUD(PVMCPU pVCpu)
2856{
2857 SVMEVENT Event;
2858 Event.u = 0;
2859 Event.n.u1Valid = 1;
2860 Event.n.u3Type = SVM_EVENT_EXCEPTION;
2861 Event.n.u8Vector = X86_XCPT_UD;
2862 hmR0SvmSetPendingEvent(pVCpu, &Event);
2863}
2864
2865
2866/**
2867 * Sets an debug (#DB) exception as pending-for-injection into the VM.
2868 *
2869 * @param pVCpu Pointer to the VMCPU.
2870 */
2871DECLINLINE(void) hmR0SvmSetPendingXcptDB(PVMCPU pVCpu)
2872{
2873 SVMEVENT Event;
2874 Event.u = 0;
2875 Event.n.u1Valid = 1;
2876 Event.n.u3Type = SVM_EVENT_EXCEPTION;
2877 Event.n.u8Vector = X86_XCPT_DB;
2878 hmR0SvmSetPendingEvent(pVCpu, &Event);
2879}
2880
2881
2882/**
2883 * Emulates a simple MOV TPR (CR8) instruction, used for TPR patching on 32-bit
2884 * guests. This simply looks up the patch record at EIP and does the required.
2885 *
2886 * This VMMCALL is used a fallback mechanism when mov to/from cr8 isn't exactly
2887 * like how we want it to be (e.g. not followed by shr 4 as is usually done for
2888 * TPR). See hmR3ReplaceTprInstr() for the details.
2889 *
2890 * @returns VBox status code.
2891 * @param pVM Pointer to the VM.
2892 * @param pVCpu Pointer to the VMCPU.
2893 * @param pCtx Pointer to the guest-CPU context.
2894 */
2895static int hmR0SvmEmulateMovTpr(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
2896{
2897 Log4(("Emulated VMMCall TPR access replacement at RIP=%RGv\n", pCtx->rip));
2898 for (;;)
2899 {
2900 bool fPending;
2901 uint8_t u8Tpr;
2902
2903 PHMTPRPATCH pPatch = (PHMTPRPATCH)RTAvloU32Get(&pVM->hm.s.PatchTree, (AVLOU32KEY)pCtx->eip);
2904 if (!pPatch)
2905 break;
2906
2907 switch (pPatch->enmType)
2908 {
2909 case HMTPRINSTR_READ:
2910 {
2911 int rc = PDMApicGetTPR(pVCpu, &u8Tpr, &fPending, NULL /* pu8PendingIrq */);
2912 AssertRC(rc);
2913
2914 rc = DISWriteReg32(CPUMCTX2CORE(pCtx), pPatch->uDstOperand, u8Tpr);
2915 AssertRC(rc);
2916 pCtx->rip += pPatch->cbOp;
2917 break;
2918 }
2919
2920 case HMTPRINSTR_WRITE_REG:
2921 case HMTPRINSTR_WRITE_IMM:
2922 {
2923 if (pPatch->enmType == HMTPRINSTR_WRITE_REG)
2924 {
2925 uint32_t u32Val;
2926 int rc = DISFetchReg32(CPUMCTX2CORE(pCtx), pPatch->uSrcOperand, &u32Val);
2927 AssertRC(rc);
2928 u8Tpr = u32Val;
2929 }
2930 else
2931 u8Tpr = (uint8_t)pPatch->uSrcOperand;
2932
2933 int rc2 = PDMApicSetTPR(pVCpu, u8Tpr);
2934 AssertRC(rc2);
2935 pCtx->rip += pPatch->cbOp;
2936 break;
2937 }
2938
2939 default:
2940 AssertMsgFailedReturn(("Unexpected patch type %d\n", pPatch->enmType), VERR_SVM_UNEXPECTED_PATCH_TYPE);
2941 break;
2942 }
2943 }
2944
2945 return VINF_SUCCESS;
2946}
2947
2948
2949/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
2950/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- #VMEXIT handlers -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */
2951/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
2952
2953/**
2954 * #VMEXIT handler for external interrupts, NMIs, FPU assertion freeze and INIT
2955 * signals (SVM_EXIT_INTR, SVM_EXIT_NMI, SVM_EXIT_FERR_FREEZE, SVM_EXIT_INIT).
2956 */
2957HMSVM_EXIT_DECL hmR0SvmExitIntr(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
2958{
2959 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
2960 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitExtInt);
2961 /* 32-bit Windows hosts (4 cores) has trouble with this on Intel; causes higher interrupt latency. Assuming the
2962 same for AMD-V.*/
2963#if HC_ARCH_BITS == 64 && defined(VBOX_WITH_VMMR0_DISABLE_PREEMPTION)
2964 Assert(ASMIntAreEnabled());
2965 return VINF_SUCCESS;
2966#else
2967 return VINF_EM_RAW_INTERRUPT;
2968#endif
2969}
2970
2971
2972/**
2973 * #VMEXIT handler for WBINVD (SVM_EXIT_WBINVD). Conditional #VMEXIT.
2974 */
2975HMSVM_EXIT_DECL hmR0SvmExitWbinvd(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
2976{
2977 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
2978 pCtx->rip += 2; /* Hardcoded opcode, AMD-V doesn't give us this information. */
2979 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitWbinvd);
2980 return VINF_SUCCESS;
2981}
2982
2983
2984/**
2985 * #VMEXIT handler for INVD (SVM_EXIT_INVD). Unconditional #VMEXIT.
2986 */
2987HMSVM_EXIT_DECL hmR0SvmExitInvd(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
2988{
2989 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
2990 pCtx->rip += 2; /* Hardcoded opcode, AMD-V doesn't give us this information. */
2991 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitInvd);
2992 return VINF_SUCCESS;
2993}
2994
2995
2996/**
2997 * #VMEXIT handler for INVD (SVM_EXIT_CPUID). Conditional #VMEXIT.
2998 */
2999HMSVM_EXIT_DECL hmR0SvmExitCpuid(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3000{
3001 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3002 PVM pVM = pVCpu->CTX_SUFF(pVM);
3003 int rc = EMInterpretCpuId(pVM, pVCpu, CPUMCTX2CORE(pCtx));
3004 if (RT_LIKELY(rc == VINF_SUCCESS))
3005 pCtx->rip += 2; /* Hardcoded opcode, AMD-V doesn't give us this information. */
3006 else
3007 {
3008 AssertMsgFailed(("hmR0SvmExitCpuid: EMInterpretCpuId failed with %Rrc\n", rc));
3009 rc = VERR_EM_INTERPRETER;
3010 }
3011 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCpuid);
3012 return rc;
3013}
3014
3015
3016/**
3017 * #VMEXIT handler for RDTSC (SVM_EXIT_RDTSC). Conditional #VMEXIT.
3018 */
3019HMSVM_EXIT_DECL hmR0SvmExitRdtsc(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3020{
3021 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3022 PVM pVM = pVCpu->CTX_SUFF(pVM);
3023 rc = EMInterpretRdtsc(pVM, pVCpu, CPUMCTX2CORE(pCtx));
3024 if (RT_LIKELY(rc == VINF_SUCCESS))
3025 pCtx->rip += 2; /* Hardcoded opcode, AMD-V doesn't give us this information. */
3026 else
3027 {
3028 AssertMsgFailed(("hmR0SvmExitRdtsc: EMInterpretRdtsc failed with %Rrc\n", rc));
3029 rc = VERR_EM_INTERPRETER;
3030 }
3031 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdtsc);
3032 return rc;
3033}
3034
3035
3036/**
3037 * #VMEXIT handler for RDTSCP (SVM_EXIT_RDTSCP). Conditional #VMEXIT.
3038 */
3039HMSVM_EXIT_DECL hmR0SvmExitRdtscp(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3040{
3041 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3042 int rc = EMInterpretRdtscp(pVM, pVCpu, pCtx);
3043 if (RT_LIKELY(rc == VINF_SUCCESS))
3044 pCtx->rip += 3; /* Hardcoded opcode, AMD-V doesn't give us this information. */
3045 else
3046 {
3047 AssertMsgFailed(("hmR0SvmExitRdtsc: EMInterpretRdtscp failed with %Rrc\n", rc));
3048 rc = VERR_EM_INTERPRETER;
3049 }
3050 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdtscp);
3051 return rc;
3052}
3053
3054
3055/**
3056 * #VMEXIT handler for RDPMC (SVM_EXIT_RDPMC). Conditional #VMEXIT.
3057 */
3058HMSVM_EXIT_DECL hmR0SvmExitRdpmc(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3059{
3060 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3061 int rc = EMInterpretRdpmc(pVM, pVCpu, CPUMCTX2CORE(pCtx));
3062 if (RT_LIKELY(rc == VINF_SUCCESS))
3063 pCtx->rip += 2; /* Hardcoded opcode, AMD-V doesn't give us this information. */
3064 else
3065 {
3066 AssertMsgFailed(("hmR0SvmExitRdpmc: EMInterpretRdpmc failed with %Rrc\n", rc));
3067 rc = VERR_EM_INTERPRETER;
3068 }
3069 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdpmc);
3070 return rc;
3071}
3072
3073
3074/**
3075 * #VMEXIT handler for INVLPG (SVM_EXIT_INVLPG). Conditional #VMEXIT.
3076 */
3077HMSVM_EXIT_DECL hmR0SvmExitInvlpg(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3078{
3079 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3080 Assert(!pVM->hm.s.fNestedPaging);
3081
3082 /** @todo Decode Assist. */
3083 int rc = hmR0SvmInterpretInvlpg(pVM, pVCpu, CPUMCTX2CORE(pCtx)); /* Updates RIP if successful. */
3084 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitInvlpg);
3085 Assert(rc == VINF_SUCCESS || rc == VERR_EM_INTERPRETER);
3086 return rc;
3087}
3088
3089
3090/**
3091 * #VMEXIT handler for HLT (SVM_EXIT_HLT). Conditional #VMEXIT.
3092 */
3093HMSVM_EXIT_DECL hmR0SvmExitHlt(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3094{
3095 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3096 pCtx->rip++; /* Hardcoded opcode, AMD-V doesn't give us this information. */
3097 int rc = EMShouldContinueAfterHalt(pVCpu, pCtx) ? VINF_SUCCESS : VINF_EM_HALT;
3098 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitHlt);
3099 return rc;
3100}
3101
3102
3103/**
3104 * #VMEXIT handler for MONITOR (SVM_EXIT_MONITOR). Conditional #VMEXIT.
3105 */
3106HMSVM_EXIT_DECL hmR0SvmExitMonitor(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3107{
3108 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3109 int rc = EMInterpretMonitor(pVM, pVCpu, CPUMCTX2CORE(pCtx));
3110 if (RT_LIKELY(rc == VINF_SUCCESS))
3111 pCtx->rip += 3; /* Hardcoded opcode, AMD-V doesn't give us this information. */
3112 else
3113 {
3114 AssertMsg(rc == VERR_EM_INTERPRETER, ("hmR0SvmExitMonitor: EMInterpretMonitor failed with %Rrc\n", rc));
3115 rc = VERR_EM_INTERPRETER;
3116 }
3117 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitMonitor);
3118 return rc;
3119}
3120
3121
3122/**
3123 * #VMEXIT handler for MWAIT (SVM_EXIT_MWAIT). Conditional #VMEXIT.
3124 */
3125HMSVM_EXIT_DECL hmR0SvmExitMwait(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3126{
3127 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3128 int rc = EMInterpretMWait(pVM, pVCpu, CPUMCTX2CORE(pCtx));
3129 if ( rc == VINF_EM_HALT
3130 || rc == VINF_SUCCESS)
3131 {
3132 pCtx->rip += 3; /* Hardcoded opcode, AMD-V doesn't give us this information. */
3133
3134 if ( rc == VINF_EM_HALT
3135 && EMShouldContinueAfterHalt(pVCpu, pMixedCtx))
3136 {
3137 rc = VINF_SUCCESS;
3138 }
3139 }
3140 else
3141 {
3142 AssertMsg(rc == VERR_EM_INTERPRETER, ("hmR0SvmExitMwait: EMInterpretMWait failed with %Rrc\n", rc));
3143 rc = VERR_EM_INTERPRETER;
3144 }
3145 AssertMsg(rc == VINF_SUCCESS || rc == VINF_EM_HALT || rc == VERR_EM_INTERPRETER,
3146 ("hmR0SvmExitMwait: EMInterpretMWait failed rc=%Rrc\n", rc));
3147 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitMwait);
3148 return rc;
3149}
3150
3151
3152/**
3153 * #VMEXIT handler for shutdown (triple-fault) (SVM_EXIT_SHUTDOWN).
3154 * Conditional #VMEXIT.
3155 */
3156HMSVM_EXIT_DECL hmR0SvmExitShutdown(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3157{
3158 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3159 return VINF_EM_RESET;
3160}
3161
3162
3163/**
3164 * #VMEXIT handler for CRx reads (SVM_EXIT_READ_CR*). Conditional #VMEXIT.
3165 */
3166HMSVM_EXIT_DECL hmR0SvmExitReadCRx(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3167{
3168 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3169 /** @todo Decode Assist. */
3170 int rc = EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0 /* pvFault */);
3171 Assert(rc == VERR_EM_INTERPRETER || rc == VINF_PGM_CHANGE_MODE || rc == VINF_PGM_SYNC_CR3);
3172 Assert((pSvmTransient->u64ExitCode - SVM_EXIT_READ_CR0) <= 15);
3173 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCRxRead[pSvmTransient->u64ExitCode - SVM_EXIT_READ_CR0]);
3174 return rc;
3175}
3176
3177
3178/**
3179 * #VMEXIT handler for CRx writes (SVM_EXIT_WRITE_CR*). Conditional #VMEXIT.
3180 */
3181HMSVM_EXIT_DECL hmR0SvmExitWriteCRx(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3182{
3183 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3184 /** @todo Decode Assist. */
3185 int rc = EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0 /* pvFault */);
3186 if (rc == VINF_SUCCCES)
3187 {
3188 /* RIP has been updated by EMInterpretInstruction(). */
3189 Assert((pSvmTransient->u64ExitCode - SVM_EXIT_WRITE_CR0) <= 15);
3190 switch (pSvmTransient->u64ExitCode - SVM_EXIT_WRITE_CR0)
3191 {
3192 case 0: /* CR0. */
3193 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_GUEST_CR0;
3194 break;
3195
3196 case 3: /* CR3. */
3197 Assert(!pVM->hm.s.fNestedPaging);
3198 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_GUEST_CR3;
3199 break;
3200
3201 case 4: /* CR4. */
3202 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_GUEST_CR4;
3203 break;
3204
3205 case 8: /* CR8 (TPR). */
3206 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_SVM_GUEST_APIC_STATE;
3207 break;
3208
3209 default:
3210 AsserMsgFailed(("hmR0SvmExitWriteCRx: Invalid/Unexpected Write-CRx exit. u64ExitCode=%#RX64 %#x CRx=%#RX64\n",
3211 pSvmTransient->u64ExitCode, pSvmTransient->u64ExitCode - SVM_EXIT_WRITE_CR0));
3212 break;
3213 }
3214 }
3215 else
3216 Assert(rc == VERR_EM_INTERPRETER || rc == VINF_PGM_CHANGE_MODE || rc == VINF_PGM_SYNC_CR3);
3217 return rc;
3218}
3219
3220
3221/**
3222 * #VMEXIT handler for instructions that result in a #UD exception delivered to
3223 * the guest.
3224 */
3225HMSVM_EXIT_DECL hmR0SvmExitSetPendingXcptUD(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3226{
3227 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3228 return hmR0SvmSetPendingXcptUD(pVCpu);
3229}
3230
3231
3232/**
3233 * #VMEXIT handler for MSR read and writes (SVM_EXIT_MSR). Conditional #VMEXIT.
3234 */
3235HMSVM_EXIT_DECL hmR0SvmExitMsr(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3236{
3237 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3238 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
3239
3240 int rc;
3241 if (pVmcb->ctrl.u64ExitInfo1 == SVM_EXIT1_MSR_WRITE)
3242 {
3243 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitWrmsr);
3244
3245 /* Handle TPR patching; intercepted LSTAR write. */
3246 if ( pVM->hm.s.fTPRPatchingActive
3247 && pCtx->ecx == MSR_K8_LSTAR)
3248 {
3249 if ((pCtx->eax & 0xff) != pSvmTransient->u8GuestTpr)
3250 {
3251 /* Our patch code uses LSTAR for TPR caching for 32-bit guests. */
3252 int rc2 = PDMApicSetTPR(pVCpu, pCtx->eax & 0xff);
3253 AssertRC(rc2);
3254 }
3255 pCtx->rip += 2; /* Hardcoded opcode, AMD-V doesn't give us this information. */
3256 return VINF_SUCCESS;
3257 }
3258
3259 rc = EMInterpretWrmsr(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx));
3260 AssertMsg(rc == VINF_SUCCESS || rc == VERR_EM_INTERPRETER, ("hmR0SvmExitMsr: EMInterpretWrmsr failed rc=%Rrc\n", rc));
3261
3262 if (pCtx->ecx == MSR_K6_EFER)
3263 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_SVM_GUEST_EFER_MSR;
3264 }
3265 else
3266 {
3267 /* MSR Read access. */
3268 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdmsr);
3269 int rc = EMInterpretRdmsr(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx));
3270 AssertMsg(rc == VINF_SUCCESS || rc == VERR_EM_INTERPRETER, ("hmR0SvmExitMsr: EMInterpretRdmsr failed rc=%Rrc\n", rc));
3271 }
3272
3273 /* RIP has been updated by EMInterpret[Rd|Wr]msr(). */
3274 return rc;
3275}
3276
3277
3278/**
3279 * #VMEXIT handler for DRx read (SVM_EXIT_READ_DRx). Conditional #VMEXIT.
3280 */
3281HMSVM_EXIT_DECL hmR0SvmExitReadDRx(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3282{
3283 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3284 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitDRxRead);
3285
3286 /* We should -not- get this VM-exit if the guest is debugging. */
3287 if (CPUMIsGuestDebugStateActive(pVCpu))
3288 {
3289 AssertMsgFailed(("hmR0SvmExitReadDRx: Unexpected exit. pVCpu=%p pCtx=%p\n", pVCpu, pCtx));
3290 return VERR_SVM_UNEXPECTED_EXIT;
3291 }
3292
3293 if ( !DBGFIsStepping(pVCpu)
3294 && !CPUMIsHyperDebugStateActive(pVCpu))
3295 {
3296 /* Don't intercept DRx read and writes. */
3297 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
3298 pVmcb->ctrl.u16InterceptRdDRx = 0;
3299 pVmcb->ctrl.u16InterceptWrDRx = 0;
3300 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
3301
3302 /* Save the host & load the guest debug state, restart execution of the MOV DRx instruction. */
3303 PVM pVM = pVCpu->CTX_SUFF(pVM);
3304 rc = CPUMR0LoadGuestDebugState(pVM, pVCpu, pCtx, true /* include DR6 */);
3305 AssertRC(rc);
3306 Assert(CPUMIsGuestDebugStateActive(pVCpu));
3307
3308 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxContextSwitch);
3309 return VINF_SUCCESS;
3310 }
3311
3312 /** @todo Decode assist. */
3313 int rc = EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0 /* pvFault */);
3314 if (RT_LIKELY(rc == VINF_SUCCESS))
3315 {
3316 /* Not necessary for read accesses but whatever doesn't hurt for now, will be fixed with decode assist. */
3317 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_GUEST_DEBUG;
3318 }
3319 else
3320 Assert(c == VERR_EM_INTERPRETER);
3321 return rc;
3322}
3323
3324
3325/**
3326 * #VMEXIT handler for DRx write (SVM_EXIT_WRITE_DRx). Conditional #VMEXIT.
3327 */
3328HMSVM_EXIT_DECL hmR0SvmExitWriteDRx(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3329{
3330 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3331 /* For now it's the same since we interpret the instruction anyway. Will change when using of Decode Assist is implemented. */
3332 int rc = hmR0SvmExitReadDRx(pVCpu, pCtx, pSvmTransient);
3333 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitDRxWrite);
3334 STAM_COUNTER_DEC(&pVCpu->hm.s.StatExitDRxRead);
3335 return rc;
3336}
3337
3338
3339/**
3340 * #VMEXIT handler for I/O instructions (SVM_EXIT_IOIO). Conditional #VMEXIT.
3341 */
3342HMSVM_EXIT_DECL hmR0SvmExitIOInstr(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3343{
3344 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3345
3346 /* I/O operation lookup arrays. */
3347 static uint32_t const s_aIOSize[8] = { 0, 1, 2, 0, 4, 0, 0, 0 }; /* Size of the I/O accesses in bytes. */
3348 static uint32_t const s_aIOOpAnd[8] = { 0, 0xff, 0xffff, 0, 0xffffffff, 0, 0, 0 }; /* AND masks for saving
3349 the result (in AL/AX/EAX). */
3350
3351 /* Refer AMD spec. 15.10.2 "IN and OUT Behaviour" and Figure 15-2. "EXITINFO1 for IOIO Intercept" for the format. */
3352 SVMIOIOEXIT IoExitInfo;
3353 IoExitInfo.u = (uint32_t)pVmcb->ctrl.u64ExitInfo1;
3354 uint32_t uIOWidth = (IoExitInfo.u >> 4) & 0x7;
3355 uint32_t uIOSize = s_aIOSize[uIOWidth];
3356 uint32_t uAndVal = s_aIOOpAnd[uIOWidth];
3357
3358 if (RT_UNLIKELY(!uIOSize))
3359 {
3360 AssertMsgFailed(("hmR0SvmExitIOInstr: Invalid IO operation. uIOWidth=%u\n", uIOWidth));
3361 return VERR_EM_INTERPRETER;
3362 }
3363
3364 int rc;
3365 if (IoExitInfo.n.u1STR)
3366 {
3367 /* INS/OUTS - I/O String instruction. */
3368 PDISCPUSTATE pDis = &pVCpu->hm.s.DisState;
3369
3370 /** @todo Huh? why can't we use the segment prefix information given by AMD-V
3371 * in EXITINFO1? Investigate once this thing is up and running. */
3372
3373 rc = EMInterpretDisasCurrent(pVM, pVCpu, pDis, NULL);
3374 if (rc == VINF_SUCCESS)
3375 {
3376 if (IoExitInfo.n.u1Type == 0) /* OUT */
3377 {
3378 rc = IOMInterpretOUTSEx(pVM, pVCpu, CPUMCTX2CORE(pCtx), IoExitInfo.n.u16Port, pDis->fPrefix,
3379 (DISCPUMODE)pDis->uAddrMode, uIOSize);
3380 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOStringWrite);
3381 }
3382 else
3383 {
3384 rc = IOMInterpretINSEx(pVM, pVCpu, CPUMCTX2CORE(pCtx), IoExitInfo.n.u16Port, pDis->fPrefix,
3385 (DISCPUMODE)pDis->uAddrMode, uIOSize);
3386 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOStringRead);
3387 }
3388 }
3389 else
3390 rc = VINF_EM_RAW_EMULATE_INSTR;
3391 }
3392 else
3393 {
3394 /* IN/OUT - I/O instruction. */
3395 Assert(!IoExitInfo.n.u1REP);
3396
3397 if (IoExitInfo.n.u1Type == 0) /* OUT */
3398 {
3399 rc = IOMIOPortWrite(pVM, pVCpu, IoExitInfo.n.u16Port, pCtx->eax & uAndVal, uIOSize);
3400 if (rc == VINF_IOM_R3_IOPORT_WRITE)
3401 HMR0SavePendingIOPortWrite(pVCpu, pCtx->rip, pVmcb->ctrl.u64ExitInfo2, IoExitInfo.n.u16Port, uAndVal, uIOSize);
3402
3403 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOWrite);
3404 }
3405 else
3406 {
3407 uint32_t u32Val = 0;
3408
3409 rc = IOMIOPortRead(pVM, pVCpu, IoExitInfo.n.u16Port, &u32Val, uIOSize);
3410 if (IOM_SUCCESS(rc))
3411 {
3412 /* Save result of I/O IN instr. in AL/AX/EAX. */
3413 pCtx->eax = (pCtx->eax & ~uAndVal) | (u32Val & uAndVal);
3414 }
3415 else if (rc == VINF_IOM_R3_IOPORT_READ)
3416 HMR0SavePendingIOPortRead(pVCpu, pCtx->rip, pVmcb->ctrl.u64ExitInfo2, IoExitInfo.n.u16Port, uAndVal, uIOSize);
3417
3418 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIORead);
3419 }
3420 }
3421
3422 if (IOM_SUCCESS(rc))
3423 {
3424 /* AMD-V saves the RIP of the instruction following the IO instruction in EXITINFO2. */
3425 pCtx->rip = pVmcb->ctrl.u64ExitInfo2;
3426
3427 if (RT_LIKELY(rc == VINF_SUCCESS))
3428 {
3429 /* If any IO breakpoints are armed, then we should check if a debug trap needs to be generated. */
3430 if (pCtx->dr[7] & X86_DR7_ENABLED_MASK)
3431 {
3432 /* I/O breakpoint length, in bytes. */
3433 static uint32_t const s_aIOBPLen[4] = { 1, 2, 0, 4 };
3434
3435 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxIoCheck);
3436 for (unsigned i = 0; i < 4; i++)
3437 {
3438 unsigned uBPLen = s_aIOBPLen[X86_DR7_GET_LEN(pCtx->dr[7], i)];
3439
3440 if ( IoExitInfo.n.u16Port >= pCtx->dr[i]
3441 && IoExitInfo.n.u16Port < pCtx->dr[i] + uBPLen
3442 && (pCtx->dr[7] & (X86_DR7_L(i) | X86_DR7_G(i)))
3443 && (pCtx->dr[7] & X86_DR7_RW(i, X86_DR7_RW_IO)) == X86_DR7_RW(i, X86_DR7_RW_IO))
3444 {
3445 Assert(CPUMIsGuestDebugStateActive(pVCpu));
3446
3447 /* Clear all breakpoint status flags and set the one we just hit. */
3448 pCtx->dr[6] &= ~(X86_DR6_B0 | X86_DR6_B1 | X86_DR6_B2 | X86_DR6_B3);
3449 pCtx->dr[6] |= (uint64_t)RT_BIT(i);
3450
3451 /*
3452 * Note: AMD64 Architecture Programmer's Manual 13.1:
3453 * Bits 15:13 of the DR6 register is never cleared by the processor and must be cleared
3454 * by software after the contents have been read.
3455 */
3456 pVmcb->guest.u64DR6 = pCtx->dr[6];
3457
3458 /* X86_DR7_GD will be cleared if drx accesses should be trapped inside the guest. */
3459 pCtx->dr[7] &= ~X86_DR7_GD;
3460
3461 /* Paranoia. */
3462 pMixedCtx->dr[7] &= 0xffffffff; /* Upper 32 bits MBZ. */
3463 pMixedCtx->dr[7] &= ~(RT_BIT(11) | RT_BIT(12) | RT_BIT(14) | RT_BIT(15)); /* MBZ. */
3464 pMixedCtx->dr[7] |= 0x400; /* MB1. */
3465
3466 pVmcb->guest.u64DR7 = pCtx->dr[7];
3467 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_DRX;
3468
3469 /* Inject the debug exception. */
3470 hmR0SvmSetPendingXcptDB(pVCpu);
3471 break;
3472 }
3473 }
3474 }
3475 }
3476 }
3477
3478#ifdef DEBUG
3479 if (rc == VINF_IOM_R3_IOPORT_READ)
3480 Assert(IoExitInfo.n.u1Type != 0);
3481 else if (rc == VINF_IOM_R3_IOPORT_WRITE)
3482 Assert(IoExitInfo.n.u1Type == 0);
3483 else
3484 {
3485 AssertMsg( RT_FAILURE(rc)
3486 || rc == VINF_SUCCESS
3487 || rc == VINF_EM_RAW_EMULATE_INSTR
3488 || rc == VINF_EM_RAW_GUEST_TRAP
3489 || rc == VINF_TRPM_XCPT_DISPATCHED, ("%Rrc\n", rc));
3490 }
3491#endif
3492 return rc;
3493}
3494
3495
3496/**
3497 * #VMEXIT handler for Nested Page-faults (SVM_EXIT_NPF). Conditional
3498 * #VMEXIT.
3499 */
3500HMSVM_EXIT_DECL hmR0SvmExitNestedPF(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3501{
3502 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3503 PVM pVM = pVCpu->CTX_SUFF(pVM);
3504 Assert(pVM->hm.s.fNestedPaging);
3505
3506 /* See AMD spec. 15.25.6 "Nested versus Guest Page Faults, Fault Ordering" for VMCB details for #NPF. */
3507 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
3508 uint32_t u32ErrCode = pVmcb->ctrl.u64ExitInfo1;
3509 RTGCPHYS GCPhysFaultAddr = pVmcb->ctrl.u64ExitInfo2;
3510
3511 Log4(("#NPF at CS:RIP=%04x:%#RX64 faultaddr=%RGp errcode=%#x \n", pCtx->cs.Sel, pCtx->rip, GCPhysFaultAddr, u32ErrCode));
3512
3513#ifdef VBOX_HM_WITH_GUEST_PATCHING
3514 /* TPR patching for 32-bit guests, using the reserved bit in the page tables for MMIO regions. */
3515 if ( pVM->hm.s.fTRPPatchingAllowed
3516 && (GCPhysFaultAddr & PAGE_OFFSET_MASK) == 0x80
3517 && ( !(u32ErrCode & X86_TRAP_PF_P) /* Not present */
3518 || (u32ErrCode & (X86_TRAP_PF_P | X86_TRAP_PF_RSVD)) == (X86_TRAP_PF_P | X86_TRAP_PF_RSVD)) /* MMIO page. */
3519 && !CPUMGetGuestCPL(pVCpu)
3520 && !CPUMIsGuestInLongModeEx(pCtx)
3521 && pVM->hm.s.cPatches < RT_ELEMENTS(pVM->hm.s.aPatches))
3522 {
3523 RTGCPHYS GCPhysApicBase = pCtx->msrApicBase;
3524 GCPhysApicBase &= PAGE_BASE_GC_MASK;
3525
3526 if (GCPhysFaultAddr == GCPhysApicBase + 0x80)
3527 {
3528 /* Only attempt to patch the instruction once. */
3529 PHMTPRPATCH pPatch = (PHMTPRPATCH)RTAvloU32Get(&pVM->hm.s.PatchTree, (AVLOU32KEY)pCtx->eip);
3530 if (!pPatch)
3531 {
3532 rc = VINF_EM_HM_PATCH_TPR_INSTR;
3533 return rc;
3534 }
3535 }
3536 }
3537#endif
3538
3539 /*
3540 * Determine the nested paging mode.
3541 */
3542 PGMMODE enmNestedPagingMode;
3543#if HC_ARCH_BITS == 32
3544 if (CPUMIsGuestInLongModeEx(pCtx))
3545 enmNestedPagingMode = PGMMODE_AMD64_NX;
3546 else
3547#endif
3548 enmNestedPagingMode = PGMGetHostMode(pVM);
3549
3550 /*
3551 * MMIO optimization using the reserved (RSVD) bit in the guest page tables for MMIO pages.
3552 */
3553 int rc;
3554 Assert((u32ErrCode & (X86_TRAP_PF_RSVD | X86_TRAP_PF_P)) != X86_TRAP_PF_RSVD);
3555 if ((u32ErrCode & (X86_TRAP_PF_RSVD | X86_TRAP_PF_P)) == (X86_TRAP_PF_RSVD | X86_TRAP_PF_P))
3556 {
3557 rc = PGMR0Trap0eHandlerNPMisconfig(pVM, pVCpu, enmNestedPagingMode, CPUMCTX2CORE(pCtx), GCPhysFaultAddr, u32ErrCode);
3558
3559 /*
3560 * If we succeed, resume guest execution.
3561 * If we fail in interpreting the instruction because we couldn't get the guest physical address
3562 * of the page containing the instruction via the guest's page tables (we would invalidate the guest page
3563 * in the host TLB), resume execution which would cause a guest page fault to let the guest handle this
3564 * weird case. See @bugref{6043}.
3565 */
3566 if ( rc == VINF_SUCCESS
3567 || rc == VERR_PAGE_TABLE_NOT_PRESENT
3568 || rc == VERR_PAGE_NOT_PRESENT)
3569 {
3570 /* Successfully handled MMIO operation. */
3571 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_SVM_GUEST_APIC_STATE;
3572 rc = VINF_SUCCESS;
3573 }
3574 return rc;
3575 }
3576
3577 TRPMAssertXcptPF(pVCpu, GCPhysFaultAddr, u32ErrCode);
3578 rc = PGMR0Trap0eHandlerNestedPaging(pVM, pVCpu, enmNestedPagingMode, u32ErrCode, CPUMCTX2CORE(pCtx), GCPhysFaultAddr);
3579 TRPMResetTrap(pVCpu);
3580
3581 Log2(("#NPF: PGMR0Trap0eHandlerNestedPaging returned %Rrc\n", rc));
3582
3583 /*
3584 * Same case as PGMR0Trap0eHandlerNPMisconfig(). See comment above, @bugref{6043}.
3585 */
3586 if ( rc == VINF_SUCCESS
3587 || rc == VERR_PAGE_TABLE_NOT_PRESENT
3588 || rc == VERR_PAGE_NOT_PRESENT)
3589 {
3590 /* We've successfully synced our shadow page tables. */
3591 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitShadowPF);
3592 rc = VINF_SUCCESS;
3593 }
3594
3595 return rc;
3596}
3597
3598
3599/**
3600 * #VMEXIT handler for virtual interrupt (SVM_EXIT_VINTR). Conditional #VMEXIT.
3601 */
3602HMSVM_EXIT_DECL hmR0SvmExitVIntr(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3603{
3604 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3605
3606 pVmcb->ctrl.IntCtrl.n.u1VIrqValid = 0; /* No virtual interrupts pending, we'll inject the current one before reentry. */
3607 pVmcb->ctrl.IntCtrl.n.u8VIrqVector = 0;
3608
3609 /* Indicate that we no longer need to VM-exit when the guest is ready to receive interrupts, it is now ready. */
3610 pVmcb->ctrl.u32InterceptCtrl1 &= ~SVM_CTRL1_INTERCEPT_VINTR;
3611 pVmcb->ctrl.u64VmcbCleanBits &= ~(HMSVM_VMCB_CLEAN_INTERCEPTS | HMSVM_VMCB_CLEAN_TPR);
3612
3613 /* Deliver the pending interrupt via hmR0SvmPreRunGuest()->hmR0SvmInjectEvent() and resume guest execution. */
3614 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIntWindow);
3615 return VINF_SUCCESS;
3616}
3617
3618
3619/**
3620 * #VMEXIT handler for task switches (SVM_EXIT_TASK_SWITCH). Conditional #VMEXIT.
3621 */
3622HMSVM_EXIT_DECL hmR0SvmExitTaskSwitch(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3623{
3624 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3625
3626 /* Check if this task-switch occurred while delivery an event through the guest IDT. */
3627 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
3628 if ( !(pVmcb->ctrl.u64ExitInfo2 & (SVM_EXIT2_TASK_SWITCH_IRET | SVM_EXIT2_TASK_SWITCH_JMP))
3629 && pVCpu->hm.s.Event.fPending)
3630 {
3631 /*
3632 * AMD-V does not provide us with the original exception but we have it in u64IntrInfo since we
3633 * injected the event during VM-entry. Software interrupts and exceptions will be regenerated
3634 * when the recompiler restarts the instruction.
3635 */
3636 SVMEVENT Event;
3637 Event.u = pVCpu->hm.s.Event.u64IntrInfo;
3638 if ( Event.n.u3Type == SVM_EVENT_EXCEPTION
3639 || Event.n.u3Type == SVM_EVENT_SOFTWARE_INT)
3640 {
3641 pVCpu->hm.s.Event.fPending = false;
3642 }
3643 else
3644 Log4(("hmR0SvmExitTaskSwitch: TS occurred during event delivery. Kept pending u8Vector=%#x\n", Event.n.u8Vector));
3645 }
3646
3647 /** @todo Emulate task switch someday, currently just going back to ring-3 for
3648 * emulation. */
3649 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitTaskSwitch);
3650 return VERR_EM_INTERPRETER;
3651}
3652
3653
3654/**
3655 * #VMEXIT handler for VMMCALL (SVM_EXIT_VMMCALL). Conditional #VMEXIT.
3656 */
3657HMSVM_EXIT_DECL hmR0SvmExitVmmCall(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3658{
3659 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3660
3661 int rc = hmR0SvmEmulateMovTpr(pVM, pVCpu, pCtx);
3662 if (RT_UNLIKELY(rc != VINF_SUCCESS))
3663 hmR0SvmSetPendingXcptUD(pVCpu);
3664 return VINF_SUCCESS;
3665}
3666
3667
Note: See TracBrowser for help on using the repository browser.

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