VirtualBox

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

Last change on this file since 46566 was 46562, checked in by vboxsync, 12 years ago

VMM: AMD-V bits and VT-x comment nit.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 128.8 KB
Line 
1/* $Id: HMSVMR0.cpp 46562 2013-06-14 13:41:37Z 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 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;
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;
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;
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 pVmcb->guest.u64EFER = pCtx->msrEFER | MSR_K6_EFER_SVME;
1129
1130 /* 64-bit MSRs. */
1131 if (CPUMIsGuestInLongModeEx(pCtx))
1132 {
1133 pVmcb->guest.FS.u64Base = pCtx->fs.u64Base;
1134 pVmcb->guest.GS.u64Base = pCtx->gs.u64Base;
1135 }
1136 else
1137 {
1138 /* If the guest isn't in 64-bit mode, clear MSR_K6_LME bit from guest EFER otherwise AMD-V expects amd64 shadow paging. */
1139 pVmcb->guest.u64EFER &= ~MSR_K6_EFER_LME;
1140 }
1141
1142 /** @todo The following are used in 64-bit only (SYSCALL/SYSRET) but they might
1143 * be writable in 32-bit mode. Clarify with AMD spec. */
1144 pVmcb->guest.u64STAR = pCtx->msrSTAR;
1145 pVmcb->guest.u64LSTAR = pCtx->msrLSTAR;
1146 pVmcb->guest.u64CSTAR = pCtx->msrCSTAR;
1147 pVmcb->guest.u64SFMASK = pCtx->msrSFMASK;
1148 pVmcb->guest.u64KernelGSBase = pCtx->msrKERNELGSBASE;
1149}
1150
1151
1152/**
1153 * Loads the guest debug registers into the VMCB.
1154 *
1155 * @param pVCpu Pointer to the VMCPU.
1156 * @param pCtx Pointer to the guest-CPU context.
1157 *
1158 * @remarks No-long-jump zone!!!
1159 * @remarks Requires EFLAGS to be up-to-date in the VMCB!
1160 */
1161DECLINLINE(void) hmR0SvmLoadGuestDebugRegs(PVMCPU pVCpu, PCPUMCTX pCtx)
1162{
1163 if (!(pVCpu->hm.s.fContextUseFlags & HM_CHANGED_GUEST_DEBUG))
1164 return;
1165
1166 /** @todo Turn these into assertions if possible. */
1167 pCtx->dr[6] |= X86_DR6_INIT_VAL; /* Set reserved bits to 1. */
1168 pCtx->dr[6] &= ~RT_BIT(12); /* MBZ. */
1169
1170 pCtx->dr[7] &= 0xffffffff; /* Upper 32 bits MBZ. */
1171 pCtx->dr[7] &= ~(RT_BIT(11) | RT_BIT(12) | RT_BIT(14) | RT_BIT(15)); /* MBZ. */
1172 pCtx->dr[7] |= 0x400; /* MB1. */
1173
1174 /* Update DR6, DR7 with the guest values. */
1175 pVmcb->guest.u64DR7 = pCtx->dr[7];
1176 pVmcb->guest.u64DR6 = pCtx->dr[6];
1177 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_DRX;
1178
1179 bool fInterceptDB = false;
1180 bool fInterceptMovDRx = false;
1181 if (DBGFIsStepping(pVCpu))
1182 {
1183 /* AMD-V doesn't have any monitor-trap flag equivalent. Instead, enable tracing in the guest and trap #DB. */
1184 pVmcb->guest.u64RFlags |= X86_EFL_TF;
1185 fInterceptDB = true;
1186 }
1187
1188 if (CPUMGetHyperDR7(pVCpu) & (X86_DR7_ENABLED_MASK | X86_DR7_GD))
1189 {
1190 if (!CPUMIsHyperDebugStateActive(pVCpu))
1191 {
1192 rc = CPUMR0LoadHyperDebugState(pVM, pVCpu, pCtx, true /* include DR6 */);
1193 AssertRC(rc);
1194
1195 /* Update DR6, DR7 with the hypervisor values. */
1196 pVmcb->guest.u64DR7 = CPUMGetHyperDR7(pVCpu);
1197 pVmcb->guest.u64DR6 = CPUMGetHyperDR6(pVCpu);
1198 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_DRX;
1199 }
1200 Assert(CPUMIsHyperDebugStateActive(pVCpu));
1201 fInterceptMovDRx = true;
1202 }
1203 else if (pCtx->dr[7] & (X86_DR7_ENABLED_MASK | X86_DR7_GD))
1204 {
1205 if (!CPUMIsGuestDebugStateActive(pVCpu))
1206 {
1207 rc = CPUMR0LoadGuestDebugState(pVM, pVCpu, pCtx, true /* include DR6 */);
1208 AssertRC(rc);
1209 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxArmed);
1210 }
1211 Assert(CPUMIsGuestDebugStateActive(pVCpu));
1212 Assert(fInterceptMovDRx == false);
1213 }
1214 else if (!CPUMIsGuestDebugStateActive(pVCpu))
1215 {
1216 /* For the first time we would need to intercept MOV DRx accesses even when the guest debug registers aren't loaded. */
1217 fInterceptMovDRx = true;
1218 }
1219
1220 if (fInterceptDB)
1221 hmR0SvmAddXcptIntercept(X86_XCPT_DB);
1222 else
1223 hmR0SvmRemoveXcptIntercept(X86_XCPT_DB);
1224
1225 if (fInterceptMovDRx)
1226 {
1227 if ( pVmcb->ctrl.u16InterceptRdDRx != 0xffff
1228 || pVmcb->ctrl.u16InterceptWrDRx != 0xffff)
1229 {
1230 pVmcb->ctrl.u16InterceptRdDRx = 0xffff;
1231 pVmcb->ctrl.u16InterceptWrDRx = 0xffff;
1232 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
1233 }
1234 }
1235 else
1236 {
1237 if ( pVmcb->ctrl.u16InterceptRdDRx
1238 || pVmcb->ctrl.u16InterceptWrDRx)
1239 {
1240 pVmcb->ctrl.u16InterceptRdDRx = 0;
1241 pVmcb->ctrl.u16InterceptWrDRx = 0;
1242 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
1243 }
1244 }
1245
1246 pVCpu->hm.s.fContextUseFlags &= ~HM_CHANGED_GUEST_DEBUG;
1247}
1248
1249
1250/**
1251 * Loads the guest APIC state (currently just the TPR).
1252 *
1253 * @returns VBox status code.
1254 * @param pVCpu Pointer to the VMCPU.
1255 * @param pVmcb Pointer to the VMCB.
1256 * @param pCtx Pointer to the guest-CPU context.
1257 */
1258DECLINLINE(int) hmR0SvmLoadGuestApicState(PVMCPU pVCpu, PSVMVMCB pVmcb, PCPUMCTX pCtx)
1259{
1260 if (!(pVCpu->hm.s.fContextUseFlags & HM_CHANGED_SVM_GUEST_APIC_STATE))
1261 return VINF_SUCCESS;
1262
1263 bool fPendingIntr;
1264 uint8_t u8Tpr;
1265 int rc = PDMApicGetTPR(pVCpu, &u8Tpr, &fPendingIntr, NULL /* pu8PendingIrq */);
1266 AssertRCReturn(rc, rc);
1267
1268 /** Assume that we need to trap all TPR accesses and thus need not check on
1269 * every #VMEXIT if we should update the TPR. */
1270 Assert(pVmcb->ctrl.IntCtrl.n.u1VIrqMasking);
1271 pVCpu->hm.s.svm.fSyncVTpr = false;
1272
1273 /* 32-bit guests uses LSTAR MSR for patching guest code which touches the TPR. */
1274 if (pVCpu->CTX_SUFF(pVM)->hm.s.fTPRPatchingActive)
1275 {
1276 pCtx->msrLSTAR = u8LastTPR;
1277
1278 /* If there are interrupts pending, intercept LSTAR writes, otherwise don't intercept reads or writes. */
1279 if (fPendingIntr)
1280 hmR0SvmSetMsrPermission(pVCpu, MSR_K8_LSTAR, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_INTERCEPT_WRITE);
1281 else
1282 {
1283 hmR0SvmSetMsrPermission(pVCpu, MSR_K8_LSTAR, SVMMSREXIT_PASSTHRU_READ, SVMMSREXIT_PASSTHRU_WRITE);
1284 pVCpu->hm.s.svm.fSyncVTpr = true;
1285 }
1286
1287 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_IOPM_MSRPM;
1288 }
1289 else
1290 {
1291 /* Bits 3-0 of the VTPR field correspond to bits 7-4 of the TPR (which is the Task-Priority Class). */
1292 pVmcb->ctrl.IntCtrl.n.u8VTPR = (u8Tpr >> 4);
1293
1294 /* If there are interrupts pending, intercept CR8 writes to evaluate ASAP if we can deliver the interrupt to the guest. */
1295 if (fPending)
1296 pVmcb->ctrl.u16InterceptWrCRx |= RT_BIT(8);
1297 else
1298 {
1299 pVmcb->ctrl.u16InterceptWrCRx &= ~RT_BIT(8);
1300 pVCpu->hm.s.svm.fSyncVTpr = true;
1301 }
1302
1303 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
1304 }
1305
1306 pVCpu->hm.s.fContextUseFlags &= ~HM_CHANGED_SVM_GUEST_APIC_STATE;
1307 return rc;
1308}
1309
1310
1311/**
1312 * Sets up the appropriate function to run guest code.
1313 *
1314 * @returns VBox status code.
1315 * @param pVCpu Pointer to the VMCPU.
1316 * @param pCtx Pointer to the guest-CPU context.
1317 *
1318 * @remarks No-long-jump zone!!!
1319 */
1320static int hmR0SvmSetupVMRunHandler(PVMCPU pVCpu, PCPUMCTX pCtx)
1321{
1322 if (CPUMIsGuestInLongModeEx(pCtx))
1323 {
1324#ifndef VBOX_ENABLE_64_BITS_GUESTS
1325 return VERR_PGM_UNSUPPORTED_SHADOW_PAGING_MODE;
1326#endif
1327 Assert(pVCpu->CTX_SUFF(pVM)->hm.s.fAllow64BitGuests); /* Guaranteed by hmR3InitFinalizeR0(). */
1328#if HC_ARCH_BITS == 32 && !defined(VBOX_WITH_HYBRID_32BIT_KERNEL)
1329 /* 32-bit host. We need to switch to 64-bit before running the 64-bit guest. */
1330 pVCpu->hm.s.svm.pfnVMRun = SVMR0VMSwitcherRun64;
1331#else
1332 /* 64-bit host or hybrid host. */
1333 pVCpu->hm.s.svm.pfnVMRun = SVMR0VMRun64;
1334#endif
1335 }
1336 else
1337 {
1338 /* Guest is not in long mode, use the 32-bit handler. */
1339 pVCpu->hm.s.svm.pfnVMRun = SVMR0VMRun;
1340 }
1341 return VINF_SUCCESS;
1342}
1343
1344
1345/**
1346 * Enters the AMD-V session.
1347 *
1348 * @returns VBox status code.
1349 * @param pVM Pointer to the VM.
1350 * @param pVCpu Pointer to the VMCPU.
1351 * @param pCpu Pointer to the CPU info struct.
1352 */
1353VMMR0DECL(int) SVMR0Enter(PVM pVM, PVMCPU pVCpu, PHMGLOBLCPUINFO pCpu)
1354{
1355 AssertPtr(pVM);
1356 AssertPtr(pVCpu);
1357 Assert(pVM->hm.s.svm.fSupported);
1358 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1359 NOREF(pCpu);
1360
1361 LogFlowFunc(("pVM=%p pVCpu=%p\n", pVM, pVCpu));
1362
1363 /* Nothing to do here. */
1364 return VINF_SUCCESS;
1365}
1366
1367
1368/**
1369 * Leaves the AMD-V session.
1370 *
1371 * @returns VBox status code.
1372 * @param pVM Pointer to the VM.
1373 * @param pVCpu Pointer to the VMCPU.
1374 * @param pCtx Pointer to the guest-CPU context.
1375 */
1376VMMR0DECL(int) SVMR0Leave(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
1377{
1378 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1379 NOREF(pVM);
1380 NOREF(pVCpu);
1381 NOREF(pCtx);
1382
1383 /* Nothing to do here. Everything is taken care of in hmR0SvmLongJmpToRing3(). */
1384 return VINF_SUCCESS;
1385}
1386
1387
1388/**
1389 * Saves the host state.
1390 *
1391 * @returns VBox status code.
1392 * @param pVM Pointer to the VM.
1393 * @param pVCpu Pointer to the VMCPU.
1394 *
1395 * @remarks No-long-jump zone!!!
1396 */
1397VMMR0DECL(int) SVMR0SaveHostState(PVM pVM, PVMCPU pVCpu)
1398{
1399 NOREF(pVM);
1400 NOREF(pVCpu);
1401 /* Nothing to do here. AMD-V does this for us automatically during the world-switch. */
1402 return VINF_SUCCESS;
1403}
1404
1405
1406/**
1407 * Loads the guest state.
1408 *
1409 * @returns VBox status code.
1410 * @param pVM Pointer to the VM.
1411 * @param pVCpu Pointer to the VMCPU.
1412 * @param pCtx Pointer to the guest-CPU context.
1413 *
1414 * @remarks No-long-jump zone!!!
1415 */
1416VMMR0DECL(int) SVMR0LoadGuestState(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
1417{
1418 AssertPtr(pVM);
1419 AssertPtr(pVCpu);
1420 AssertPtr(pCtx);
1421 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1422
1423 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
1424 AssertMsgReturn(pVmcb, ("Invalid pVmcb\n"), VERR_SVM_INVALID_PVMCB);
1425
1426 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatLoadGuestState, x);
1427
1428 int rc = hmR0SvmLoadGuestControlRegs(pVCpu, pVmcb, pCtx);
1429 AssertLogRelMsgRCReturn(rc, ("hmR0SvmLoadGuestControlRegs! rc=%Rrc (pVM=%p pVCpu=%p)\n", rc, pVM, pVCpu), rc);
1430
1431 hmR0SvmLoadGuestSegmentRegs(pVCpu, pVmcb, pCtx);
1432 hmR0SvmLoadGuestMsrs(pVCpu, pVmcb, pCtx);
1433
1434 pVmcb->guest.u64RIP = pCtx->rip;
1435 pVmcb->guest.u64RSP = pCtx->rsp;
1436 pVmcb->guest.u64RFlags = pCtx->eflags.u32;
1437 pVmcb->guest.u8CPL = pCtx->ss.Attr.n.u2Dpl;
1438 pVmcb->guest.u64RAX = pCtx->rax;
1439
1440 /* hmR0SvmLoadGuestDebugRegs() must be called -after- updating guest RFLAGS as the RFLAGS may need to be changed. */
1441 hmR0SvmLoadGuestDebugRegs(pVCpu, pVmcb, pCtx);
1442
1443 rc = hmR0SvmLoadGuestApicState(pVCpu, pVmcb, pCtx);
1444 AssertLogRelMsgRCReturn(rc, ("hmR0SvmLoadGuestApicState! rc=%Rrc (pVM=%p pVCpu=%p)\n", rc, pVM, pVCpu), rc);
1445
1446 rc = hmR0SvmSetupVMRunHandler(pVCpu, pCtx);
1447 AssertLogRelMsgRCReturn(rc, ("hmR0SvmSetupVMRunHandler! rc=%Rrc (pVM=%p pVCpu=%p)\n", rc, pVM, pVCpu), rc);
1448
1449 /* Clear any unused and reserved bits. */
1450 pVCpu->hm.s.fContextUseFlags &= ~( HM_CHANGED_GUEST_SYSENTER_CS_MSR
1451 | HM_CHANGED_GUEST_SYSENTER_EIP_MSR
1452 | HM_CHANGED_GUEST_SYSENTER_ESP_MSR);
1453
1454 AssertMsg(!pVCpu->hm.s.fContextUseFlags,
1455 ("Missed updating flags while loading guest state. pVM=%p pVCpu=%p fContextUseFlags=%#RX32\n",
1456 pVM, pVCpu, pVCpu->hm.s.fContextUseFlags));
1457
1458 STAM_PROFILE_ADV_STOP(&pVCpu->hm.s.StatLoadGuestState, x);
1459
1460 return rc;
1461}
1462
1463
1464
1465/**
1466 * Saves the entire guest state from the VMCB into the
1467 * guest-CPU context. Currently there is no residual state left in the CPU that
1468 * is not updated in the VMCB.
1469 *
1470 * @returns VBox status code.
1471 * @param pVCpu Pointer to the VMCPU.
1472 * @param pMixedCtx Pointer to the guest-CPU context. The data may be
1473 * out-of-sync. Make sure to update the required fields
1474 * before using them.
1475 */
1476static void hmR0SvmSaveGuestState(PVMCPU pVCpu, PCPUMCTX pMixedCtx)
1477{
1478 Assert(VMMRZCallRing3IsEnabled(pVCpu));
1479
1480 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
1481
1482 pMixedCtx->rip = pVmcb->guest.u64RIP;
1483 pMixedCtx->rsp = pVmcb->guest.u64RSP;
1484 pMixedCtx->eflags.u32 = pVmcb->guest.u64RFlags;
1485 pMixedCtx->rax = pVmcb->guest.u64RAX;
1486
1487 /*
1488 * Guest interrupt shadow.
1489 */
1490 if (pVmcb->ctrl.u64IntShadow & SVM_INTERRUPT_SHADOW_ACTIVE)
1491 EMSetInhibitInterruptsPC(pVCpu, pMixedCtx->rip);
1492 else
1493 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
1494
1495 /*
1496 * Guest Control registers: CR2, CR3 (handled at the end) - accesses to other control registers are always intercepted.
1497 */
1498 pMixedCtx->cr2 = pVmcb->guest.u64CR2;
1499
1500 /*
1501 * Guest MSRs.
1502 */
1503 pMixedCtx->msrSTAR = pVmcb->guest.u64STAR; /* legacy syscall eip, cs & ss */
1504 pMixedCtx->msrLSTAR = pVmcb->guest.u64LSTAR; /* 64-bit mode syscall rip */
1505 pMixedCtx->msrCSTAR = pVmcb->guest.u64CSTAR; /* compatibility mode syscall rip */
1506 pMixedCtx->msrSFMASK = pVmcb->guest.u64SFMASK; /* syscall flag mask */
1507 pMixedCtx->msrKERNELGSBASE = pVmcb->guest.u64KernelGSBase; /* swapgs exchange value */
1508 pMixedCtx->SysEnter.cs = pVmcb->guest.u64SysEnterCS;
1509 pMixedCtx->SysEnter.eip = pVmcb->guest.u64SysEnterEIP;
1510 pMixedCtx->SysEnter.esp = pVmcb->guest.u64SysEnterESP;
1511
1512 /*
1513 * Guest segment registers (includes FS, GS base MSRs for 64-bit guests).
1514 */
1515 HMSVM_SAVE_SEG_REG(CS, ss);
1516 HMSVM_SAVE_SEG_REG(SS, cs);
1517 HMSVM_SAVE_SEG_REG(DS, ds);
1518 HMSVM_SAVE_SEG_REG(ES, es);
1519 HMSVM_SAVE_SEG_REG(FS, fs);
1520 HMSVM_SAVE_SEG_REG(GS, gs);
1521
1522 /*
1523 * Correct the hidden CS granularity flag. Haven't seen it being wrong in any other
1524 * register (yet).
1525 */
1526 /** @todo Verify this. */
1527 if ( !pMixedCtx->cs.Attr.n.u1Granularity
1528 && pMixedCtx->cs.Attr.n.u1Present
1529 && pMixedCtx->cs.u32Limit > UINT32_C(0xfffff))
1530 {
1531 Assert((pMixedCtx->cs.u32Limit & 0xfff) == 0xfff);
1532 pMixedCtx->cs.Attr.n.u1Granularity = 1;
1533 }
1534#ifdef VBOX_STRICT
1535# define HMSVM_ASSERT_SEL_GRANULARITY(reg) \
1536 AssertMsg( !pMixedCtx->reg.Attr.n.u1Present \
1537 || ( pMixedCtx->reg.Attr.n.u1Granularity \
1538 ? (pMixedCtx->reg.u32Limit & 0xfff) == 0xfff \
1539 : pMixedCtx->reg.u32Limit <= UINT32_C(0xfffff)), \
1540 ("Invalid Segment Attributes %#x %#x %#llx\n", pMixedCtx->reg.u32Limit,
1541 pMixedCtx->reg.Attr.u, pMixedCtx->reg.u64Base))
1542
1543 HMSVM_ASSERT_SEG_GRANULARITY(cs);
1544 HMSVM_ASSERT_SEG_GRANULARITY(ss);
1545 HMSVM_ASSERT_SEG_GRANULARITY(ds);
1546 HMSVM_ASSERT_SEG_GRANULARITY(es);
1547 HMSVM_ASSERT_SEG_GRANULARITY(fs);
1548 HMSVM_ASSERT_SEG_GRANULARITY(gs);
1549
1550# undef HMSVM_ASSERT_SEL_GRANULARITY
1551#endif
1552
1553 /*
1554 * Sync the hidden SS DPL field. AMD CPUs have a separate CPL field in the VMCB and uses that
1555 * and thus it's possible that when the CPL changes during guest execution that the SS DPL
1556 * isn't updated by AMD-V. Observed on some AMD Fusion CPUs with 64-bit guests.
1557 * See AMD spec. 15.5.1 "Basic operation".
1558 */
1559 Assert(!(pVmcb->guest.u8CPL & ~0x3));
1560 pMixedCtx->ss.Attr.n.u2Dpl = pVmcb->guest.u8CPL & 0x3;
1561
1562 /*
1563 * Guest Descriptor-Table registers.
1564 */
1565 HMSVM_SAVE_SEG_REG(TR, tr);
1566 HMSVM_SAVE_SEG_REG(LDTR, ldtr);
1567 pMixedCtx->gdtr.cbGdt = pVmcb->guest.GDTR.u32Limit;
1568 pMixedCtx->gdtr.pGdt = pVmcb->guest.GDTR.u64Base;
1569
1570 pMixedCtx->idtr.cbIdt = pVmcb->guest.IDTR.u32Limit;
1571 pMixedCtx->idtr.pIdt = pVmcb->guest.IDTR.u64Base;
1572
1573 /*
1574 * Guest Debug registers.
1575 */
1576 pMixedCtx->dr[6] = pVmcb->guest.u64DR6;
1577 pMixedCtx->dr[7] = pVmcb->guest.u64DR7;
1578
1579 /*
1580 * With Nested Paging, CR3 changes are not intercepted. Therefore, sync. it now.
1581 * This is done as the very last step of syncing the guest state, as PGMUpdateCR3() may cause longjmp's to ring-3.
1582 */
1583 if ( pVM->hm.s.fNestedPaging
1584 && pMixedCtx->cr3 != pVmcb->guest.u64CR3)
1585 {
1586 CPUMSetGuestCR3(pVCpu, pVmcb->guest.u64CR3);
1587 PGMUpdateCR3(pVCpu, pVmcb->guest.u64CR3);
1588 }
1589}
1590
1591
1592/**
1593 * Does the necessary state syncing before doing a longjmp to ring-3.
1594 *
1595 * @param pVM Pointer to the VM.
1596 * @param pVCpu Pointer to the VMCPU.
1597 * @param pCtx Pointer to the guest-CPU context.
1598 * @param rcExit The reason for exiting to ring-3. Can be
1599 * VINF_VMM_UNKNOWN_RING3_CALL.
1600 *
1601 * @remarks No-long-jmp zone!!!
1602 */
1603static void hmR0SvmLongJmpToRing3(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, int rcExit)
1604{
1605 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
1606 Assert(VMMR0IsLogFlushDisabled(pVCpu));
1607
1608 /* Restore host FPU state if necessary and resync on next R0 reentry .*/
1609 if (CPUMIsGuestFPUStateActive(pVCpu))
1610 {
1611 CPUMR0SaveGuestFPU(pVM, pVCpu, pCtx);
1612 Assert(!CPUMIsGuestFPUStateActive(pVCpu));
1613 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_GUEST_CR0;
1614 }
1615
1616 /* Restore host debug registers if necessary and resync on next R0 reentry. */
1617 if (CPUMIsGuestDebugStateActive(pVCpu))
1618 {
1619 CPUMR0SaveGuestDebugState(pVM, pVCpu, pCtx, true /* save DR6 */);
1620 Assert(!CPUMIsGuestDebugStateActive(pVCpu));
1621 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_GUEST_DEBUG;
1622 }
1623 else if (CPUMIsHyperDebugStateActive(pVCpu))
1624 {
1625 CPUMR0LoadHostDebugState(pVM, pVCpu);
1626 Assert(!CPUMIsHyperDebugStateActive(pVCpu));
1627 Assert(pVmcb->ctrl.u16InterceptRdDRx == 0xffff);
1628 Assert(pVmcb->ctrl.u16InterceptWrDRx == 0xffff);
1629 }
1630
1631 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchLongJmpToR3);
1632 VMCPU_CMPXCHG_STATE(pVCpu, VMCPUSTATE_STARTED_HM, VMCPUSTATE_STARTED_EXEC);
1633}
1634
1635
1636/**
1637 * VMMRZCallRing3() callback wrapper which saves the guest state (or restores
1638 * any remaining host state) before we longjump to ring-3 and possibly get
1639 * preempted.
1640 *
1641 * @param pVCpu Pointer to the VMCPU.
1642 * @param enmOperation The operation causing the ring-3 longjump.
1643 * @param pvUser The user argument (pointer to the possibly
1644 * out-of-date guest-CPU context).
1645 *
1646 * @remarks Must never be called with @a enmOperation ==
1647 * VMMCALLRING3_VM_R0_ASSERTION.
1648 */
1649DECLCALLBACK(void) hmR0SvmCallRing3Callback(PVMCPU pVCpu, VMMCALLRING3 enmOperation, void *pvUser)
1650{
1651 /* VMMRZCallRing3() already makes sure we never get called as a result of an longjmp due to an assertion, */
1652 Assert(pVCpu);
1653 Assert(pvUser);
1654 Assert(VMMRZCallRing3IsEnabled(pVCpu));
1655 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1656
1657 VMMRZCallRing3Disable(pVCpu);
1658 Assert(VMMR0IsLogFlushDisabled(pVCpu));
1659 Log4(("hmR0SvmCallRing3Callback->hmR0SvmLongJmpToRing3\n"));
1660 hmR0SvmLongJmpToRing3(pVCpu->CTX_SUFF(pVM), pVCpu, (PCPUMCTX)pvUser, VINF_VMM_UNKNOWN_RING3_CALL);
1661 VMMRZCallRing3Enable(pVCpu);
1662}
1663
1664
1665/**
1666 * An action requires us to go back to ring-3. This function does the necessary
1667 * steps before we can safely return to ring-3. This is not the same as longjmps
1668 * to ring-3, this is voluntary.
1669 *
1670 * @param pVM Pointer to the VM.
1671 * @param pVCpu Pointer to the VMCPU.
1672 * @param pCtx Pointer to the guest-CPU context.
1673 * @param rcExit The reason for exiting to ring-3. Can be
1674 * VINF_VMM_UNKNOWN_RING3_CALL.
1675 */
1676static void hmR0SvmExitToRing3(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, int rcExit)
1677{
1678 Assert(pVM);
1679 Assert(pVCpu);
1680 Assert(pCtx);
1681 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
1682
1683 if (RT_UNLIKELY(rcExit == VERR_SVM_INVALID_GUEST_STATE))
1684 {
1685 /* We don't need to do any syncing here, we're not going to come back to execute anything again. */
1686 return;
1687 }
1688
1689 /* Please, no longjumps here (any logging shouldn't flush jump back to ring-3). NO LOGGING BEFORE THIS POINT! */
1690 VMMRZCallRing3Disable(pVCpu);
1691 Log4(("hmR0SvmExitToRing3: rcExit=%d\n", rcExit));
1692
1693 /* We need to do this only while truly exiting the "inner loop" back to ring-3 and -not- for any longjmp to ring3. */
1694 if (pVCpu->hm.s.Event.fPending)
1695 {
1696 hmR0SvmPendingEventToTrpmTrap(pVCpu);
1697 Assert(!pVCpu->hm.s.Event.fPending);
1698 }
1699
1700 /* Sync. the guest state. */
1701 hmR0SvmLongJmpToRing3(pVM, pVCpu, pCtx, rcExit);
1702 STAM_COUNTER_DEC(&pVCpu->hm.s.StatSwitchLongJmpToR3);
1703
1704 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_TO_R3);
1705 CPUMSetChangedFlags(pVCpu, CPUM_CHANGED_SYSENTER_MSR
1706 | CPUM_CHANGED_LDTR
1707 | CPUM_CHANGED_GDTR
1708 | CPUM_CHANGED_IDTR
1709 | CPUM_CHANGED_TR
1710 | CPUM_CHANGED_HIDDEN_SEL_REGS);
1711
1712 /* On our way back from ring-3 the following needs to be done. */
1713 /** @todo This can change with preemption hooks. */
1714 if (rcExit == VINF_EM_RAW_INTERRUPT)
1715 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_HOST_CONTEXT;
1716 else
1717 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_HOST_CONTEXT | HM_CHANGED_ALL_GUEST;
1718
1719 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchExitToR3);
1720 VMMRZCallRing3Enable(pVCpu);
1721}
1722
1723
1724/**
1725 * Sets up the usage of TSC offsetting for the VCPU.
1726 *
1727 * @param pVCpu Pointer to the VMCPU.
1728 *
1729 * @remarks No-long-jump zone!!!
1730 */
1731static void hmR0SvmSetupTscOffsetting(PVMCPU pVCpu)
1732{
1733 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
1734 if (TMCpuTickCanUseRealTSC(pVCpu, &pVmcb->ctrl.u64TSCOffset))
1735 {
1736 uint64_t u64CurTSC = ASMReadTSC();
1737 if (u64CurTSC + pVmcb->ctrl.u64TSCOffset > TMCpuTickGetLastSeen(pVCpu))
1738 {
1739 pVmcb->ctrl.u32InterceptCtrl1 &= ~SVM_CTRL1_INTERCEPT_RDTSC;
1740 pVmcb->ctrl.u32InterceptCtrl2 &= ~SVM_CTRL2_INTERCEPT_RDTSCP;
1741 STAM_COUNTER_INC(&pVCpu->hm.s.StatTscOffset);
1742 }
1743 else
1744 {
1745 pVmcb->ctrl.u32InterceptCtrl1 |= SVM_CTRL1_INTERCEPT_RDTSC;
1746 pVmcb->ctrl.u32InterceptCtrl2 |= SVM_CTRL2_INTERCEPT_RDTSCP;
1747 STAM_COUNTER_INC(&pVCpu->hm.s.StatTscInterceptOverFlow);
1748 }
1749 }
1750 else
1751 {
1752 pVmcb->ctrl.u32InterceptCtrl1 |= SVM_CTRL1_INTERCEPT_RDTSC;
1753 pVmcb->ctrl.u32InterceptCtrl2 |= SVM_CTRL2_INTERCEPT_RDTSCP;
1754 STAM_COUNTER_INC(&pVCpu->hm.s.StatTscIntercept);
1755 }
1756
1757 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
1758}
1759
1760
1761/**
1762 * Sets an event as a pending event to be injected into the guest.
1763 *
1764 * @param pVCpu Pointer to the VMCPU.
1765 * @param pEvent Pointer to the SVM event.
1766 * @param GCPtrFaultAddress The fault-address (CR2) in case it's a
1767 * page-fault.
1768 */
1769DECLINLINE(void) hmR0SvmSetPendingEvent(PVMCPU pVCpu, PSVMEVENT pEvent, RTGCUINTPTR GCPtrFaultAddress)
1770{
1771 Assert(!pVCpu->hm.s.Event.fPending);
1772
1773 pVCpu->hm.s.Event.u64IntrInfo = pEvent->u;
1774 pVCpu->hm.s.Event.fPending = true;
1775 pVCpu->hm.s.Event.GCPtrFaultAddress = GCPtrFaultAddress;
1776
1777#ifdef VBOX_STRICT
1778 if (GCPtrFaultAddress)
1779 {
1780 AssertMsg( pEvent->n.u8Vector == X86_XCPT_PF
1781 && pEvent->n.u3Type == SVM_EVENT_EXCEPTION,
1782 ("hmR0SvmSetPendingEvent: Setting fault-address for non-#PF. u8Vector=%#x Type=%#RX32 GCPtrFaultAddr=%#RGx\n",
1783 pEvent->n.u8Vector, (uint32_t)pEvent->n.u3Type, GCPtrFaultAddress));
1784 Assert(GCPtrFaultAddress == CPUMGetGuestCR2(pVCpu));
1785 }
1786#endif
1787
1788 Log4(("hmR0SvmSetPendingEvent: u=%#RX64 u8Vector=%#x ErrorCodeValid=%#x ErrorCode=%#RX32\n", pEvent->u,
1789 pEvent->n.u8Vector, pEvent->n.u3Type, (uint8_t)pEvent->n.u1ErrorCodeValid, pEvent->n.u32ErrorCode));
1790}
1791
1792
1793/**
1794 * Injects an event into the guest upon VMRUN by updating the relevant field
1795 * in the VMCB.
1796 *
1797 * @param pVCpu Pointer to the VMCPU.
1798 * @param pVmcb Pointer to the guest VMCB.
1799 * @param pCtx Pointer to the guest-CPU context.
1800 * @param pEvent Pointer to the event.
1801 *
1802 * @remarks No-long-jump zone!!!
1803 * @remarks Requires CR0!
1804 */
1805DECLINLINE(void) hmR0SvmInjectEventVmcb(PVMCPU pVCpu, PSVMVMCB pVmcb, PCPUMCTX pCtx, PSVMEVENT pEvent)
1806{
1807 pVmcb->ctrl.EventInject.u = pEvent->u;
1808 STAM_COUNTER_INC(&pVCpu->hm.s.paStatInjectedIrqsR0[pEvent->n.u8Vector & MASK_INJECT_IRQ_STAT]);
1809}
1810
1811
1812/**
1813 * Converts any TRPM trap into a pending SVM event. This is typically used when
1814 * entering from ring-3 (not longjmp returns).
1815 *
1816 * @param pVCpu Pointer to the VMCPU.
1817 */
1818static void hmR0SvmTrpmTrapToPendingEvent(PVMCPU pVCpu)
1819{
1820 Assert(TRPMHasTrap(pVCpu));
1821 Assert(!pVCpu->hm.s.Event.fPending);
1822
1823 uint8_t uVector;
1824 TRPMEVENT enmTrpmEvent;
1825 RTGCUINT uErrCode;
1826 RTGCUINTPTR GCPtrFaultAddress;
1827 uint8_t cbInstr;
1828
1829 int rc = TRPMQueryTrapAll(pVCpu, &uVector, &enmTrpmEvent, &uErrCode, &GCPtrFaultAddress, &cbInstr);
1830 AssertRC(rc);
1831
1832 PSVMEVENT pEvent = &pVCpu->hm.s.Event;
1833 pEvent->u = 0;
1834 pEvent->n.u1Valid = 1;
1835
1836 /* Refer AMD spec. 15.20 "Event Injection" for the format. */
1837 if (enmTrpmEvent == TRPM_TRAP)
1838 {
1839 pEvent->n.u3Type = SVM_EVENT_EXCEPTION;
1840 switch (uVector)
1841 {
1842 case X86_XCPT_PF:
1843 case X86_XCPT_DF:
1844 case X86_XCPT_TS:
1845 case X86_XCPT_NP:
1846 case X86_XCPT_SS:
1847 case X86_XCPT_GP:
1848 case X86_XCPT_AC:
1849 {
1850 pEvent->n.u32ErrorCode = uErrCode;
1851 pEvent->n.u1ErrorCodeValid = 1;
1852 break;
1853 }
1854 }
1855 }
1856 else if (enmTrpmEvent == TRPM_HARDWARE_INT)
1857 {
1858 if (uVector == X86_XCPT_NMI)
1859 pEvent->n.u3Type = SVM_EVENT_NMI;
1860 else
1861 pEvent->n.u3Type = SVM_EVENT_EXTERNAL_IRQ;
1862 }
1863 else if (enmTrpmEvent == TRPM_SOFTWARE_INT)
1864 pEvent->n.u3Type = SVM_EVENT_SOFTWARE_INT;
1865 else
1866 AssertMsgFailed(("Invalid TRPM event type %d\n", enmTrpmEvent));
1867
1868 rc = TRPMResetTrap(pVCpu);
1869 AssertRC(rc);
1870
1871 Log4(("TRPM->HM event: u=%#RX64 u8Vector=%#x uErrorCodeValid=%#x uErrorCode=%#RX32\n", pEvent->u, pEvent->n.u8Vector,
1872 pEvent->n.u1ErrorCodeValid, pEvent->n.u32ErrorCode));
1873}
1874
1875
1876/**
1877 * Converts any pending SVM event into a TRPM trap. Typically used when leaving
1878 * AMD-V to execute any instruction.
1879 *
1880 * @param pvCpu Pointer to the VMCPU.
1881 */
1882static void hmR0SvmPendingEventToTrpmTrap(PVMCPU pVCpu)
1883{
1884 Assert(pVCpu->hm.s.Event.fPending);
1885 Assert(TRPMQueryTrap(pVCpu, NULL /* pu8TrapNo */, NULL /* pEnmType */) == VERR_TRPM_NO_ACTIVE_TRAP);
1886
1887 PSVMEVENT pEvent = &pVCpu->hm.s.Event;
1888 uint8_t uVector = pEvent->n.u8Vector;
1889 uint8_t uVectorType = pEvent->n.u3Type;
1890
1891 TRPMEVENT enmTrapType;
1892 switch (uVectorType)
1893 {
1894 case SVM_EVENT_EXTERNAL_IRQ
1895 case SVM_EVENT_NMI:
1896 enmTrapType = TRPM_HARDWARE_INT;
1897 break;
1898 case SVM_EVENT_SOFTWARE_INT:
1899 enmTrapType = TRPM_SOFTWARE_INT;
1900 break;
1901 case SVM_EVENT_EXCEPTION:
1902 enmTrapType = TRPM_TRAP;
1903 break;
1904 default:
1905 AssertMsgFailed(("Invalid pending-event type %#x\n", uVectorType));
1906 enmTrapType = TRPM_32BIT_HACK;
1907 break;
1908 }
1909
1910 Log4(("HM event->TRPM: uVector=%#x enmTrapType=%d\n", uVector, uVectorType));
1911
1912 int rc = TRPMAssertTrap(pVCpu, uVector, enmTrapType);
1913 AssertRC(rc);
1914
1915 if (pEvent->n.u1ErrorCodeValid)
1916 TRPMSetErrorCode(pVCpu, pEvent->n.u32ErrorCode);
1917
1918 if ( uVectorType == SVM_EVENT_EXCEPTION
1919 && uVector == X86_XCPT_PF)
1920 {
1921 TRPMSetFaultAddress(pVCpu, pVCpu->hm.s.Event.GCPtrFaultAddress);
1922 Assert(pVCpu->hm.s.Event.GCPtrFaultAddress == CPUMGetGuestCR2(pVCpu));
1923 }
1924 else if (uVectorType == SVM_EVENT_SOFTWARE_INT)
1925 {
1926 AssertMsg( uVectorType == SVM_EVENT_SOFTWARE_INT
1927 || (uVector == X86_XCPT_BP || uVector == X86_XCPT_OF),
1928 ("Invalid vector: uVector=%#x uVectorType=%#x\n", uVector, uVectorType));
1929 TRPMSetInstrLength(pVCpu, pVCpu->hm.s.Event.cbInstr);
1930 }
1931 pVCpu->hm.s.Event.fPending = false;
1932}
1933
1934
1935/**
1936 * Gets the guest's interrupt-shadow.
1937 *
1938 * @returns The guest's interrupt-shadow.
1939 * @param pVCpu Pointer to the VMCPU.
1940 * @param pCtx Pointer to the guest-CPU context.
1941 *
1942 * @remarks No-long-jump zone!!!
1943 * @remarks Has side-effects with VMCPU_FF_INHIBIT_INTERRUPTS force-flag.
1944 */
1945DECLINLINE(uint32_t) hmR0SvmGetGuestIntrShadow(PVMCPU pVCpu, PCPUMCTX pCtx)
1946{
1947 /*
1948 * Instructions like STI and MOV SS inhibit interrupts till the next instruction completes. Check if we should
1949 * inhibit interrupts or clear any existing interrupt-inhibition.
1950 */
1951 uint32_t uIntrState = 0;
1952 if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
1953 {
1954 if (pCtx->rip != EMGetInhibitInterruptsPC(pVCpu))
1955 {
1956 /*
1957 * We can clear the inhibit force flag as even if we go back to the recompiler without executing guest code in
1958 * AMD-V, the flag's condition to be cleared is met and thus the cleared state is correct.
1959 */
1960 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
1961 }
1962 else
1963 uIntrState = SVM_INTERRUPT_SHADOW_ACTIVE;
1964 }
1965 return uIntrState;
1966}
1967
1968
1969/**
1970 * Sets the virtual interrupt intercept control in the VMCB which
1971 * instructs AMD-V to cause a #VMEXIT as soon as the guest is in a state to
1972 * receive interrupts.
1973 *
1974 * @param pVmcb Pointer to the VMCB.
1975 */
1976DECLINLINE(void) hmR0SvmSetVirtIntrIntercept(PSVMVMCB pVmcb)
1977{
1978 if (!(pVmcb->ctrl.u32InterceptCtrl1 & SVM_CTRL1_INTERCEPT_VINTR))
1979 {
1980 pVmcb->ctrl.IntCtrl.n.u1VIrqValid = 1; /* A virtual interrupt is pending. */
1981 pVmcb->ctrl.IntCtrl.n.u8VIrqVector = 0; /* Not necessary as we #VMEXIT for delivering the interrupt. */
1982 pVmcb->ctrl.u32InterceptCtrl1 |= SVM_CTRL1_INTERCEPT_VINTR;
1983 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
1984 }
1985}
1986
1987
1988/**
1989 * Injects any pending events into the guest if the guest is in a state to
1990 * receive them.
1991 *
1992 * @param pVCpu Pointer to the VMCPU.
1993 * @param pCtx Pointer to the guest-CPU context.
1994 */
1995static void hmR0SvmInjectPendingEvent(PVMCPU pVCpu, PCPUMCTX pCtx)
1996{
1997 Assert(!TRPMHasTrap(pVCpu));
1998
1999 const bool fIntShadow = !!hmR0SvmGetGuestIntrShadow(pVCpu, pCtx);
2000 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
2001
2002 SVMEVENT Event;
2003 Event.u = 0;
2004 if (pVCpu->hm.s.Event.fPending) /* First, inject any pending HM events. */
2005 {
2006 Event.u = pVCpu->hm.s.Event.u64IntrInfo;
2007 bool fInject = true;
2008 if ( fIntShadow
2009 && ( Event.n.u3Type == SVM_EVENT_EXTERNAL_IRQ
2010 || Event.n.u3Type == SVM_EVENT_NMI))
2011 {
2012 fInject = false;
2013 }
2014
2015 if ( fInject
2016 && Event.n.u1Valid)
2017 {
2018 pVCpu->hm.s.Event.fPending = false;
2019 hmR0SvmInjectEvent(pVCpu, pVmcb, pCtx, &Event);
2020 }
2021 else
2022 hmR0SvmSetVirtIntrIntercept(pVmcb);
2023 } /** @todo SMI. SMIs take priority over NMIs. */
2024 else if (VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_INTERRUPT_NMI)) /* NMI. NMIs take priority over regular interrupts . */
2025 {
2026 if (!fIntShadow)
2027 {
2028 Log4(("Injecting NMI\n"));
2029 Event.n.u1Valid = 1;
2030 Event.n.u8Vector = X86_XCPT_NMI;
2031 Event.n.u3Type = SVM_EVENT_NMI;
2032
2033 hmR0SvmInjectEvent(pVCpu, pVmcb, pCtx, &Event);
2034 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INTERRUPT_NMI);
2035 }
2036 else
2037 hmR0SvmSetVirtIntrIntercept(pVmcb);
2038 }
2039 else if (VMCPU_FF_IS_PENDING(pVCpu, (VMCPU_FF_INTERRUPT_APIC | VMCPU_FF_INTERRUPT_PIC)))
2040 {
2041 /* Check if there are guest external interrupts (PIC/APIC) pending and inject them if the guest can receive them. */
2042 const bool fBlockInt = !(pCtx->eflags.u32 & X86_EFL_IF);
2043 if ( !fBlockInt
2044 && !fIntShadow)
2045 {
2046 uint8_t u8Interrupt;
2047 rc = PDMGetInterrupt(pVCpu, &u8Interrupt);
2048 if (RT_SUCCESS(rc))
2049 {
2050 Log4(("Injecting interrupt u8Interrupt=%#x\n", u8Interrupt));
2051
2052 Event.n.u1Valid = 1;
2053 Event.n.u8Vector = u8Interrupt;
2054 Event.n.u3Type = SVM_EVENT_EXTERNAL_IRQ;
2055
2056 hmR0SvmInjectEvent(pVCpu, pVmcb, pCtx, &Event);
2057 STAM_COUNTER_INC(&pVCpu->hm.s.StatIntInject);
2058 }
2059 else
2060 {
2061 /** @todo Does this actually happen? If not turn it into an assertion. */
2062 Assert(!VMCPU_FF_IS_PENDING(pVCpu, (VMCPU_FF_INTERRUPT_APIC | VMCPU_FF_INTERRUPT_PIC)));
2063 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchGuestIrq);
2064 }
2065 }
2066 else
2067 hmR0SvmSetVirtIntrIntercept(pVmcb);
2068 }
2069
2070 /* Update the guest interrupt shadow in the VMCB. */
2071 pVmcb->ctrl.u64IntShadow = !!fIntShadow;
2072}
2073
2074
2075/**
2076 * Reports world-switch error and dumps some useful debug info.
2077 *
2078 * @param pVM Pointer to the VM.
2079 * @param pVCpu Pointer to the VMCPU.
2080 * @param rcVMRun The return code from VMRUN (or
2081 * VERR_SVM_INVALID_GUEST_STATE for invalid
2082 * guest-state).
2083 * @param pCtx Pointer to the guest-CPU context.
2084 */
2085static void hmR0SvmReportWorldSwitchError(PVM pVM, PVMCPU pVCpu, int rcVMRun, PCPUMCTX pCtx)
2086{
2087 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
2088 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
2089
2090 if (rcVMRun == VERR_SVM_INVALID_GUEST_STATE)
2091 {
2092 HMDumpRegs(pVM, pVCpu, pCtx);
2093#ifdef VBOX_STRICT
2094 Log4(("ctrl.u64VmcbCleanBits %#RX64\n", pVmcb->ctrl.u64VmcbCleanBits));
2095 Log4(("ctrl.u16InterceptRdCRx %#x\n", pVmcb->ctrl.u16InterceptRdCRx));
2096 Log4(("ctrl.u16InterceptWrCRx %#x\n", pVmcb->ctrl.u16InterceptWrCRx));
2097 Log4(("ctrl.u16InterceptRdDRx %#x\n", pVmcb->ctrl.u16InterceptRdDRx));
2098 Log4(("ctrl.u16InterceptWrDRx %#x\n", pVmcb->ctrl.u16InterceptWrDRx));
2099 Log4(("ctrl.u32InterceptException %#x\n", pVmcb->ctrl.u32InterceptException));
2100 Log4(("ctrl.u32InterceptCtrl1 %#x\n", pVmcb->ctrl.u32InterceptCtrl1));
2101 Log4(("ctrl.u32InterceptCtrl2 %#x\n", pVmcb->ctrl.u32InterceptCtrl2));
2102 Log4(("ctrl.u64IOPMPhysAddr %#RX64\n", pVmcb->ctrl.u64IOPMPhysAddr));
2103 Log4(("ctrl.u64MSRPMPhysAddr %#RX64\n", pVmcb->ctrl.u64MSRPMPhysAddr));
2104 Log4(("ctrl.u64TSCOffset %#RX64\n", pVmcb->ctrl.u64TSCOffset));
2105
2106 Log4(("ctrl.TLBCtrl.u32ASID %#x\n", pVmcb->ctrl.TLBCtrl.n.u32ASID));
2107 Log4(("ctrl.TLBCtrl.u8TLBFlush %#x\n", pVmcb->ctrl.TLBCtrl.n.u8TLBFlush));
2108 Log4(("ctrl.TLBCtrl.u24Reserved %#x\n", pVmcb->ctrl.TLBCtrl.n.u24Reserved));
2109
2110 Log4(("ctrl.IntCtrl.u8VTPR %#x\n", pVmcb->ctrl.IntCtrl.n.u8VTPR));
2111 Log4(("ctrl.IntCtrl.u1VIrqValid %#x\n", pVmcb->ctrl.IntCtrl.n.u1VIrqValid));
2112 Log4(("ctrl.IntCtrl.u7Reserved %#x\n", pVmcb->ctrl.IntCtrl.n.u7Reserved));
2113 Log4(("ctrl.IntCtrl.u4VIrqPriority %#x\n", pVmcb->ctrl.IntCtrl.n.u4VIrqPriority));
2114 Log4(("ctrl.IntCtrl.u1IgnoreTPR %#x\n", pVmcb->ctrl.IntCtrl.n.u1IgnoreTPR));
2115 Log4(("ctrl.IntCtrl.u3Reserved %#x\n", pVmcb->ctrl.IntCtrl.n.u3Reserved));
2116 Log4(("ctrl.IntCtrl.u1VIrqMasking %#x\n", pVmcb->ctrl.IntCtrl.n.u1VIrqMasking));
2117 Log4(("ctrl.IntCtrl.u6Reserved %#x\n", pVmcb->ctrl.IntCtrl.n.u6Reserved));
2118 Log4(("ctrl.IntCtrl.u8VIrqVector %#x\n", pVmcb->ctrl.IntCtrl.n.u8VIrqVector));
2119 Log4(("ctrl.IntCtrl.u24Reserved %#x\n", pVmcb->ctrl.IntCtrl.n.u24Reserved));
2120
2121 Log4(("ctrl.u64IntShadow %#RX64\n", pVmcb->ctrl.u64IntShadow));
2122 Log4(("ctrl.u64ExitCode %#RX64\n", pVmcb->ctrl.u64ExitCode));
2123 Log4(("ctrl.u64ExitInfo1 %#RX64\n", pVmcb->ctrl.u64ExitInfo1));
2124 Log4(("ctrl.u64ExitInfo2 %#RX64\n", pVmcb->ctrl.u64ExitInfo2));
2125 Log4(("ctrl.ExitIntInfo.u8Vector %#x\n", pVmcb->ctrl.ExitIntInfo.n.u8Vector));
2126 Log4(("ctrl.ExitIntInfo.u3Type %#x\n", pVmcb->ctrl.ExitIntInfo.n.u3Type));
2127 Log4(("ctrl.ExitIntInfo.u1ErrorCodeValid %#x\n", pVmcb->ctrl.ExitIntInfo.n.u1ErrorCodeValid));
2128 Log4(("ctrl.ExitIntInfo.u19Reserved %#x\n", pVmcb->ctrl.ExitIntInfo.n.u19Reserved));
2129 Log4(("ctrl.ExitIntInfo.u1Valid %#x\n", pVmcb->ctrl.ExitIntInfo.n.u1Valid));
2130 Log4(("ctrl.ExitIntInfo.u32ErrorCode %#x\n", pVmcb->ctrl.ExitIntInfo.n.u32ErrorCode));
2131 Log4(("ctrl.NestedPaging %#RX64\n", pVmcb->ctrl.NestedPaging.u));
2132 Log4(("ctrl.EventInject.u8Vector %#x\n", pVmcb->ctrl.EventInject.n.u8Vector));
2133 Log4(("ctrl.EventInject.u3Type %#x\n", pVmcb->ctrl.EventInject.n.u3Type));
2134 Log4(("ctrl.EventInject.u1ErrorCodeValid %#x\n", pVmcb->ctrl.EventInject.n.u1ErrorCodeValid));
2135 Log4(("ctrl.EventInject.u19Reserved %#x\n", pVmcb->ctrl.EventInject.n.u19Reserved));
2136 Log4(("ctrl.EventInject.u1Valid %#x\n", pVmcb->ctrl.EventInject.n.u1Valid));
2137 Log4(("ctrl.EventInject.u32ErrorCode %#x\n", pVmcb->ctrl.EventInject.n.u32ErrorCode));
2138
2139 Log4(("ctrl.u64NestedPagingCR3 %#RX64\n", pVmcb->ctrl.u64NestedPagingCR3));
2140 Log4(("ctrl.u64LBRVirt %#RX64\n", pVmcb->ctrl.u64LBRVirt));
2141
2142 Log4(("guest.CS.u16Sel %RTsel\n", pVmcb->guest.CS.u16Sel));
2143 Log4(("guest.CS.u16Attr %#x\n", pVmcb->guest.CS.u16Attr));
2144 Log4(("guest.CS.u32Limit %#RX32\n", pVmcb->guest.CS.u32Limit));
2145 Log4(("guest.CS.u64Base %#RX64\n", pVmcb->guest.CS.u64Base));
2146 Log4(("guest.DS.u16Sel %#RTsel\n", pVmcb->guest.DS.u16Sel));
2147 Log4(("guest.DS.u16Attr %#x\n", pVmcb->guest.DS.u16Attr));
2148 Log4(("guest.DS.u32Limit %#RX32\n", pVmcb->guest.DS.u32Limit));
2149 Log4(("guest.DS.u64Base %#RX64\n", pVmcb->guest.DS.u64Base));
2150 Log4(("guest.ES.u16Sel %RTsel\n", pVmcb->guest.ES.u16Sel));
2151 Log4(("guest.ES.u16Attr %#x\n", pVmcb->guest.ES.u16Attr));
2152 Log4(("guest.ES.u32Limit %#RX32\n", pVmcb->guest.ES.u32Limit));
2153 Log4(("guest.ES.u64Base %#RX64\n", pVmcb->guest.ES.u64Base));
2154 Log4(("guest.FS.u16Sel %RTsel\n", pVmcb->guest.FS.u16Sel));
2155 Log4(("guest.FS.u16Attr %#x\n", pVmcb->guest.FS.u16Attr));
2156 Log4(("guest.FS.u32Limit %#RX32\n", pVmcb->guest.FS.u32Limit));
2157 Log4(("guest.FS.u64Base %#RX64\n", pVmcb->guest.FS.u64Base));
2158 Log4(("guest.GS.u16Sel %RTsel\n", pVmcb->guest.GS.u16Sel));
2159 Log4(("guest.GS.u16Attr %#x\n", pVmcb->guest.GS.u16Attr));
2160 Log4(("guest.GS.u32Limit %#RX32\n", pVmcb->guest.GS.u32Limit));
2161 Log4(("guest.GS.u64Base %#RX64\n", pVmcb->guest.GS.u64Base));
2162
2163 Log4(("guest.GDTR.u32Limit %#RX32\n", pVmcb->guest.GDTR.u32Limit));
2164 Log4(("guest.GDTR.u64Base %#RX64\n", pVmcb->guest.GDTR.u64Base));
2165
2166 Log4(("guest.LDTR.u16Sel %RTsel\n", pVmcb->guest.LDTR.u16Sel));
2167 Log4(("guest.LDTR.u16Attr %#x\n", pVmcb->guest.LDTR.u16Attr));
2168 Log4(("guest.LDTR.u32Limit %#RX32\n", pVmcb->guest.LDTR.u32Limit));
2169 Log4(("guest.LDTR.u64Base %#RX64\n", pVmcb->guest.LDTR.u64Base));
2170
2171 Log4(("guest.IDTR.u32Limit %#RX32\n", pVmcb->guest.IDTR.u32Limit));
2172 Log4(("guest.IDTR.u64Base %#RX64\n", pVmcb->guest.IDTR.u64Base));
2173
2174 Log4(("guest.TR.u16Sel %RTsel\n", pVmcb->guest.TR.u16Sel));
2175 Log4(("guest.TR.u16Attr %#x\n", pVmcb->guest.TR.u16Attr));
2176 Log4(("guest.TR.u32Limit %#RX32\n", pVmcb->guest.TR.u32Limit));
2177 Log4(("guest.TR.u64Base %#RX64\n", pVmcb->guest.TR.u64Base));
2178
2179 Log4(("guest.u8CPL %#x\n", pVmcb->guest.u8CPL));
2180 Log4(("guest.u64CR0 %#RX64\n", pVmcb->guest.u64CR0));
2181 Log4(("guest.u64CR2 %#RX64\n", pVmcb->guest.u64CR2));
2182 Log4(("guest.u64CR3 %#RX64\n", pVmcb->guest.u64CR3));
2183 Log4(("guest.u64CR4 %#RX64\n", pVmcb->guest.u64CR4));
2184 Log4(("guest.u64DR6 %#RX64\n", pVmcb->guest.u64DR6));
2185 Log4(("guest.u64DR7 %#RX64\n", pVmcb->guest.u64DR7));
2186
2187 Log4(("guest.u64RIP %#RX64\n", pVmcb->guest.u64RIP));
2188 Log4(("guest.u64RSP %#RX64\n", pVmcb->guest.u64RSP));
2189 Log4(("guest.u64RAX %#RX64\n", pVmcb->guest.u64RAX));
2190 Log4(("guest.u64RFlags %#RX64\n", pVmcb->guest.u64RFlags));
2191
2192 Log4(("guest.u64SysEnterCS %#RX64\n", pVmcb->guest.u64SysEnterCS));
2193 Log4(("guest.u64SysEnterEIP %#RX64\n", pVmcb->guest.u64SysEnterEIP));
2194 Log4(("guest.u64SysEnterESP %#RX64\n", pVmcb->guest.u64SysEnterESP));
2195
2196 Log4(("guest.u64EFER %#RX64\n", pVmcb->guest.u64EFER));
2197 Log4(("guest.u64STAR %#RX64\n", pVmcb->guest.u64STAR));
2198 Log4(("guest.u64LSTAR %#RX64\n", pVmcb->guest.u64LSTAR));
2199 Log4(("guest.u64CSTAR %#RX64\n", pVmcb->guest.u64CSTAR));
2200 Log4(("guest.u64SFMASK %#RX64\n", pVmcb->guest.u64SFMASK));
2201 Log4(("guest.u64KernelGSBase %#RX64\n", pVmcb->guest.u64KernelGSBase));
2202 Log4(("guest.u64GPAT %#RX64\n", pVmcb->guest.u64GPAT));
2203 Log4(("guest.u64DBGCTL %#RX64\n", pVmcb->guest.u64DBGCTL));
2204 Log4(("guest.u64BR_FROM %#RX64\n", pVmcb->guest.u64BR_FROM));
2205 Log4(("guest.u64BR_TO %#RX64\n", pVmcb->guest.u64BR_TO));
2206 Log4(("guest.u64LASTEXCPFROM %#RX64\n", pVmcb->guest.u64LASTEXCPFROM));
2207 Log4(("guest.u64LASTEXCPTO %#RX64\n", pVmcb->guest.u64LASTEXCPTO));
2208#endif
2209 }
2210 else
2211 Log4(("hmR0SvmReportWorldSwitchError: rcVMRun=%d\n", rcVMRun));
2212}
2213
2214
2215/**
2216 * Check per-VM and per-VCPU force flag actions that require us to go back to
2217 * ring-3 for one reason or another.
2218 *
2219 * @returns VBox status code (information status code included).
2220 * @retval VINF_SUCCESS if we don't have any actions that require going back to
2221 * ring-3.
2222 * @retval VINF_PGM_SYNC_CR3 if we have pending PGM CR3 sync.
2223 * @retval VINF_EM_PENDING_REQUEST if we have pending requests (like hardware
2224 * interrupts)
2225 * @retval VINF_PGM_POOL_FLUSH_PENDING if PGM is doing a pool flush and requires
2226 * all EMTs to be in ring-3.
2227 * @retval VINF_EM_RAW_TO_R3 if there is pending DMA requests.
2228 * @retval VINF_EM_NO_MEMORY PGM is out of memory, we need to return
2229 * to the EM loop.
2230 *
2231 * @param pVM Pointer to the VM.
2232 * @param pVCpu Pointer to the VMCPU.
2233 * @param pCtx Pointer to the guest-CPU context.
2234 */
2235static int hmR0SvmCheckForceFlags(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
2236{
2237 Assert(VMMRZCallRing3IsEnabled(pVCpu));
2238
2239 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)
2240 || VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_TO_R3_MASK | VMCPU_FF_PGM_SYNC_CR3 | VMCPU_FF_PGM_SYNC_CR3_NON_GLOBAL
2241 | VMCPU_FF_REQUEST | VMCPU_FF_HM_UPDATE_CR3))
2242 {
2243 /* Pending HM CR3 sync. No PAE PDPEs (VMCPU_FF_HM_UPDATE_PAE_PDPES) on AMD-V. */
2244 if (VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_UPDATE_CR3))
2245 {
2246 rc = PGMUpdateCR3(pVCpu, pCtx->cr3);
2247 Assert(rc == VINF_SUCCESS || rc == VINF_PGM_SYNC_CR3);
2248 Assert(!VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_UPDATE_CR3));
2249 }
2250
2251 /* Pending PGM C3 sync. */
2252 if (VMCPU_FF_IS_PENDING(pVCpu,VMCPU_FF_PGM_SYNC_CR3 | VMCPU_FF_PGM_SYNC_CR3_NON_GLOBAL))
2253 {
2254 rc = PGMSyncCR3(pVCpu, pCtx->cr0, pCtx->cr3, pCtx->cr4, VMCPU_FF_IS_SET(pVCpu, VMCPU_FF_PGM_SYNC_CR3));
2255 if (rc != VINF_SUCCESS)
2256 {
2257 AssertRC(rc);
2258 Log4(("hmR0SvmCheckForceFlags: PGMSyncCR3 forcing us back to ring-3. rc=%d\n", rc));
2259 return rc;
2260 }
2261 }
2262
2263 /* Pending HM-to-R3 operations (critsects, timers, EMT rendezvous etc.) */
2264 /* -XXX- what was that about single stepping? */
2265 if ( VM_FF_IS_PENDING(pVM, VM_FF_HM_TO_R3_MASK)
2266 || VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_HM_TO_R3_MASK))
2267 {
2268 STAM_COUNTER_INC(&pVCpu->hm.s.StatSwitchHmToR3FF);
2269 rc = RT_UNLIKELY(VM_FF_IS_PENDING(pVM, VM_FF_PGM_NO_MEMORY)) ? VINF_EM_NO_MEMORY : VINF_EM_RAW_TO_R3;
2270 Log4(("hmR0SvmCheckForceFlags: HM_TO_R3 forcing us back to ring-3. rc=%d\n", rc));
2271 return rc;
2272 }
2273
2274 /* Pending VM request packets, such as hardware interrupts. */
2275 if ( VM_FF_IS_PENDING(pVM, VM_FF_REQUEST)
2276 || VMCPU_FF_IS_PENDING(pVCpu, VMCPU_FF_REQUEST))
2277 {
2278 Log4(("hmR0SvmCheckForceFlags: Pending VM request forcing us back to ring-3\n"));
2279 return VINF_EM_PENDING_REQUEST;
2280 }
2281
2282 /* Pending PGM pool flushes. */
2283 if (VM_FF_IS_PENDING(pVM, VM_FF_PGM_POOL_FLUSH_PENDING))
2284 {
2285 Log4(("hmR0SvmCheckForceFlags: PGM pool flush pending forcing us back to ring-3\n"));
2286 return VINF_PGM_POOL_FLUSH_PENDING;
2287 }
2288
2289 /* Pending DMA requests. */
2290 if (VM_FF_IS_PENDING(pVM, VM_FF_PDM_DMA))
2291 {
2292 Log4(("hmR0SvmCheckForceFlags: Pending DMA request forcing us back to ring-3\n"));
2293 return VINF_EM_RAW_TO_R3;
2294 }
2295 }
2296
2297 /* Paranoia. */
2298 Assert(rc != VERR_EM_INTERPRETER);
2299 return VINF_SUCCESS;
2300}
2301
2302
2303/**
2304 * Does the preparations before executing guest code in AMD-V.
2305 *
2306 * This may cause longjmps to ring-3 and may even result in rescheduling to the
2307 * recompiler. We must be cautious what we do here regarding committing
2308 * guest-state information into the the VMCB assuming we assuredly execute the
2309 * guest in AMD-V. If we fall back to the recompiler after updating the VMCB and
2310 * clearing the common-state (TRPM/forceflags), we must undo those changes so
2311 * that the recompiler can (and should) use them when it resumes guest
2312 * execution. Otherwise such operations must be done when we can no longer
2313 * exit to ring-3.
2314 *
2315 * @returns VBox status code (informational status codes included).
2316 * @retval VINF_SUCCESS if we can proceed with running the guest.
2317 * @retval VINF_* scheduling changes, we have to go back to ring-3.
2318 *
2319 * @param pVCpu Pointer to the VMCPU.
2320 * @param pCtx Pointer to the guest-CPU context.
2321 * @param pSvmTransient Pointer to the SVM transient structure.
2322 */
2323DECLINE(int) hmR0SvmPreRunGuest(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
2324{
2325 /* Check force flag actions that might require us to go back to ring-3. */
2326 int rc = hmR0SvmCheckForceFlags(pVM, pVCpu, pCtx);
2327 if (rc != VINF_SUCCESS)
2328 return rc;
2329
2330#ifdef VBOX_WITH_VMMR0_DISABLE_PREEMPTION
2331 /* We disable interrupts so that we don't miss any interrupts that would flag preemption (IPI/timers etc.) */
2332 pSvmTransient->uEFlags = ASMIntDisableFlags();
2333 if (RTThreadPreemptIsPending(NIL_RTTHREAD))
2334 {
2335 ASMSetFlags(pSvmTransient->uEFlags);
2336 STAM_COUNTER_INC(&pVCpu->hm.s.StatPendingHostIrq);
2337 /* Don't use VINF_EM_RAW_INTERRUPT_HYPER as we can't assume the host does kernel preemption. Maybe some day? */
2338 return VINF_EM_RAW_INTERRUPT;
2339 }
2340 VMCPU_ASSERT_STATE(pVCpu, VMCPUSTATE_STARTED_HM);
2341 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_EXEC);
2342#endif
2343
2344 /* Convert any pending TRPM traps to HM events for injection. */
2345 /** @todo Optimization: move this before disabling interrupts, restore state
2346 * using pVmcb->ctrl.EventInject.u. */
2347 if (TRPMHasTrap(pVCpu))
2348 hmR0SvmTrpmTrapToPendingEvent(pVCpu);
2349
2350 hmR0SvmInjectPendingEvent(pVCpu, pCtx);
2351
2352 return VINF_SUCCESS;
2353}
2354
2355
2356/**
2357 * Prepares to run guest code in VT-x and we've committed to doing so. This
2358 * means there is no backing out to ring-3 or anywhere else at this
2359 * point.
2360 *
2361 * @param pVM Pointer to the VM.
2362 * @param pVCpu Pointer to the VMCPU.
2363 * @param pCtx Pointer to the guest-CPU context.
2364 * @param pSvmTransient Pointer to the SVM transient structure.
2365 *
2366 * @remarks Called with preemption disabled.
2367 * @remarks No-long-jump zone!!!
2368 */
2369DECLINLINE(void) hmR0SvmPreRunGuestCommitted(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
2370{
2371 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
2372 Assert(VMMR0IsLogFlushDisabled(pVCpu));
2373
2374#ifndef VBOX_WITH_VMMR0_DISABLE_PREEMPTION
2375 /** @todo I don't see the point of this, VMMR0EntryFast() already disables interrupts for the entire period. */
2376 pSvmTransient->uEFlags = ASMIntDisableFlags();
2377 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_EXEC);
2378#endif
2379
2380 /*
2381 * Re-enable nested paging (automatically disabled on every VM-exit). See AMD spec. 15.25.3 "Enabling Nested Paging".
2382 * We avoid changing the corresponding VMCB Clean Bit as we're not changing it to a different value since the previous run.
2383 */
2384 /** @todo The above assumption could be wrong. It's not documented what
2385 * should be done wrt to the VMCB Clean Bit, but we'll find out the
2386 * hard way. */
2387 pVmcb->ctrl.NestedPaging.n.u1NestedPaging = pVM->hm.s.fNestedPaging;
2388
2389 /* Load the guest state. */
2390 int rc = SVMR0LoadGuestState(pVM, pVCpu, pCtx);
2391 AssertRC(rc);
2392 AssertMsg(!pVCpu->hm.s.fContextUseFlags, ("fContextUseFlags =%#x\n", pVCpu->hm.s.fContextUseFlags));
2393 STAM_COUNTER_INC(&pVCpu->hm.s.StatLoadFull);
2394
2395 /*
2396 * If we're not intercepting TPR changes in the guest, save the guest TPR before the world-switch
2397 * so we can update it on the way back if the guest changed the TPR.
2398 */
2399 if (pVCpu->hm.s.svm.fSyncVTpr)
2400 {
2401 if (pVM->hm.s.fTPRPatchingActive)
2402 pSvmTransient->u8GuestTpr = pCtx->msrLSTAR;
2403 else
2404 pSvmTransient->u8GuestTpr = pVmcb->ctrl.IntCtrl.n.u8VTPR;
2405 }
2406
2407 /* Flush the appropriate tagged-TLB entries. */
2408 ASMAtomicWriteBool(&pVCpu->hm.s.fCheckedTLBFlush, true); /* Used for TLB-shootdowns, set this across the world switch. */
2409 hmR0SvmFlushTaggedTlb(pVCpu);
2410 Assert(HMR0GetCurrentCpu()->idCpu == pVCpu->hm.s.idLastCpu);
2411
2412 TMNotifyStartOfExecution(pVCpu); /* Finally, notify TM to resume its clocks as we're about
2413 to start executing. */
2414
2415 /*
2416 * Save the current Host TSC_AUX and write the guest TSC_AUX to the host, so that
2417 * RDTSCPs (that don't cause exits) reads the guest MSR. See @bugref{3324}.
2418 *
2419 * This should be done -after- any RDTSCPs for obtaining the host timestamp (TM, STAM etc).
2420 */
2421 if ( (pVM->hm.s.cpuid.u32AMDFeatureEDX & X86_CPUID_EXT_FEATURE_EDX_RDTSCP)
2422 && !(pVmcb->ctrl.u32InterceptCtrl2 & SVM_CTRL2_INTERCEPT_RDTSCP))
2423 {
2424 pVCpu->hm.s.u64HostTscAux = ASMRdMsr(MSR_K8_TSC_AUX);
2425 uint64_t u64GuestTscAux = 0;
2426 rc2 = CPUMQueryGuestMsr(pVCpu, MSR_K8_TSC_AUX, &u64GuestTscAux);
2427 AssertRC(rc2);
2428 ASMWrMsr(MSR_K8_TSC_AUX, u64GuestTscAux);
2429 }
2430}
2431
2432
2433/**
2434 * Wrapper for running the guest code in AMD-V.
2435 *
2436 * @returns VBox strict status code.
2437 * @param pVM Pointer to the VM.
2438 * @param pVCpu Pointer to the VMCPU.
2439 * @param pCtx Pointer to the guest-CPU context.
2440 *
2441 * @remarks No-long-jump zone!!!
2442 */
2443DECLINLINE(int) hmR0SvmRunGuest(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
2444{
2445 /*
2446 * 64-bit Windows uses XMM registers in the kernel as the Microsoft compiler expresses floating-point operations
2447 * using SSE instructions. Some XMM registers (XMM6-XMM15) are callee-saved and thus the need for this XMM wrapper.
2448 * Refer MSDN docs. "Configuring Programs for 64-bit / x64 Software Conventions / Register Usage" for details.
2449 */
2450#ifdef VBOX_WITH_KERNEL_USING_XMM
2451 return HMR0SVMRunWrapXMM(pVCpu->hm.s.svm.HCPhysVmcbHost, pVCpu->hm.s.svm.HCPhysVmcb, pCtx, pVM, pVCpu,
2452 pVCpu->hm.s.svm.pfnVMRun);
2453#else
2454 return pVCpu->hm.s.svm.pfnVMRun(pVCpu->hm.s.svm.HCPhysVmcbHost, pVCpu->hm.s.svm.HCPhysVmcb, pCtx, pVM, pVCpu);
2455#endif
2456}
2457
2458
2459/**
2460 * Performs some essential restoration of state after running guest code in
2461 * AMD-V.
2462 *
2463 * @param pVM Pointer to the VM.
2464 * @param pVCpu Pointer to the VMCPU.
2465 * @param pMixedCtx Pointer to the guest-CPU context. The data maybe
2466 * out-of-sync. Make sure to update the required fields
2467 * before using them.
2468 * @param pSvmTransient Pointer to the SVM transient structure.
2469 * @param rcVMRun Return code of VMRUN.
2470 *
2471 * @remarks Called with interrupts disabled.
2472 * @remarks No-long-jump zone!!! This function will however re-enable longjmps
2473 * unconditionally when it is safe to do so.
2474 */
2475DECLINLINE(void) hmR0SvmPostRunGuest(PVM pVM, PVMCPU pVCpu, PCPUMCTX pMixedCtx, PSVMTRANSIENT pSvmTransient, rcVMRun)
2476{
2477 Assert(!VMMRZCallRing3IsEnabled(pVCpu));
2478
2479 ASMAtomicWriteBool(&pVCpu->hm.s.fCheckedTLBFlush, false); /* See HMInvalidatePageOnAllVCpus(): used for TLB-shootdowns. */
2480 ASMAtomicIncU32(&pVCpu->hm.s.cWorldSwitchExits); /* Initialized in vmR3CreateUVM(): used for TLB-shootdowns. */
2481
2482 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
2483 pVmcb->ctrl.u64VmcbCleanBits = HMSVM_VMCB_CLEAN_ALL; /* Mark the VMCB-state cache as unmodified by VMM. */
2484
2485 /* Restore host's TSC_AUX if required. */
2486 if (!(pVmcb->ctrl.u32InterceptCtrl1 & SVM_CTRL1_INTERCEPT_RDTSC))
2487 {
2488 if (pVM->hm.s.cpuid.u32AMDFeatureEDX & X86_CPUID_EXT_FEATURE_EDX_RDTSCP)
2489 ASMWrMsr(MSR_K8_TSC_AUX, pVCpu->hm.s.u64HostTscAux);
2490
2491 /** @todo Find a way to fix hardcoding a guestimate. */
2492 TMCpuTickSetLastSeen(pVCpu, ASMReadTSC() +
2493 pVmcb->ctrl.u64TSCOffset - 0x400);
2494 }
2495
2496 TMNotifyEndOfExecution(pVCpu); /* Notify TM that the guest is no longer running. */
2497 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_HM);
2498
2499 Assert(!(ASMGetFlags() & X86_EFL_IF));
2500 ASMSetFlags(pSvmTransient->uEFlags); /* Enable interrupts. */
2501
2502 VMMRZCallRing3SetNotification(pVCpu, hmR0SvmCallRing3Callback, pMixedCtx);
2503 VMMRZCallRing3Enable(pVCpu); /* It is now safe to do longjmps to ring-3!!! */
2504
2505 /* If VMRUN failed, we can bail out early. This does -not- cover SVM_EXIT_INVALID. */
2506 if (RT_UNLIKELY(rcVMRun != VINF_SUCCESS))
2507 {
2508 Log4(("VMRUN failure: rcVMRun=%Rrc\n", rcVMRun));
2509 return;
2510 }
2511
2512 pSvmTransient->u64ExitCode = pVmcb->ctrl.u64ExitCode;
2513 hmR0SvmSaveGuestState(pVCpu, pMixedCtx); /* Save the guest state from the VMCB to the guest-CPU context. */
2514
2515 if (RT_LIKELY(pSvmTransient->u64ExitCode != SVM_EXIT_INVALID))
2516 {
2517 if (pVCpu->hm.s.svm.fSyncVTpr)
2518 {
2519 /* TPR patching (for 32-bit guests) uses LSTAR MSR for holding the TPR value, otherwise uses the VTPR. */
2520 if ( pVM->hm.s.fTPRPatchingActive
2521 && (pCtx->msrLSTAR & 0xff) != pSvmTransient->u8GuestTpr)
2522 {
2523 int rc = PDMApicSetTPR(pVCpu, pCtx->msrLSTAR & 0xff);
2524 AssertRC(rc);
2525 }
2526 else if ((uint8_t)(pSvmTransient->u8GuestTpr >> 4) != pVmcb->ctrl.IntCtrl.n.u8VTPR)
2527 {
2528 int rc = PDMApicSetTPR(pVCpu, (pVmcb->ctrl.IntCtrl.n.u8VTPR << 4));
2529 AssertRC(rc);
2530 }
2531 }
2532
2533 /* -XXX- premature interruption during event injection */
2534 }
2535}
2536
2537
2538/**
2539 * Runs the guest code using AMD-V.
2540 *
2541 * @returns VBox status code.
2542 * @param pVM Pointer to the VM.
2543 * @param pVCpu Pointer to the VMCPU.
2544 * @param pCtx Pointer to the guest-CPU context.
2545 */
2546VMMR0DECL(int) SVMR0RunGuestCode(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
2547{
2548 Assert(VMMRZCallRing3IsEnabled(pVCpu));
2549 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD));
2550
2551 SVMTRANSIENT SvmTransient;
2552 uint32_t cLoops = 0;
2553 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
2554 int rc = VERR_INTERNAL_ERROR_5;
2555
2556 for (;; cLoops++)
2557 {
2558 Assert(!HMR0SuspendPending());
2559 AssertMsg(pVCpu->hm.s.idEnteredCpu == RTMpCpuId(),
2560 ("Illegal migration! Entered on CPU %u Current %u cLoops=%u\n", (unsigned)pVCpu->hm.s.idEnteredCpu,
2561 (unsigned)RTMpCpuId(), cLoops));
2562
2563 /* Preparatory work for running guest code, this may return to ring-3 for some last minute updates. */
2564 STAM_PROFILE_ADV_START(&pVCpu->hm.s.StatEntry, x);
2565 rc = hmR0SvmPreRunGuest(pVM, pVCpu, pCtx, &SvmTransient);
2566 if (rc != VINF_SUCCESS)
2567 break;
2568
2569 /*
2570 * No longjmps to ring-3 from this point on!!!
2571 * Asserts() will still longjmp to ring-3 (but won't return), which is intentional, better than a kernel panic.
2572 * This also disables flushing of the R0-logger instance (if any).
2573 */
2574 VMMRZCallRing3Disable(pVCpu);
2575 VMMRZCallRing3RemoveNotification(pVCpu);
2576 hmR0SvmPreRunGuestCommitted(pVM, pVCpu, pCtx, &SvmTransient);
2577
2578 rc = hmR0SvmRunGuest(pVM, pVCpu, pCtx);
2579
2580 /*
2581 * Restore any residual host-state and save any bits shared between host and guest into the guest-CPU state.
2582 * This will also re-enable longjmps to ring-3 when it has reached a safe point!!!
2583 */
2584 hmR0SvmPostRunGuest(pVM, pVCpu, pCtx, &SvmTransient, rc);
2585 if (RT_UNLIKELY( rc != VINF_SUCCESS /* Check for errors with running the VM (VMRUN). */
2586 || SvmTransient.u64ExitCode == SVM_EXIT_INVALID)) /* Check for errors due to invalid guest state. */
2587 {
2588 if (rc == VINF_SUCCESS);
2589 rc = VERR_SVM_INVALID_GUEST_STATE;
2590 hmR0SvmReportWorldSwitchError(pVM, pVCpu, rc, pCtx, &SvmTransient);
2591 return rc;
2592 }
2593
2594 /* Handle the #VMEXIT. */
2595 AssertMsg(SvmTransient.u64ExitCode != SVM_EXIT_INVALID, ("%#x\n", SvmTransient.u64ExitCode));
2596 HMSVM_EXITCODE_STAM_COUNTER_INC(SvmTransient.u64ExitCode);
2597 rc = hmR0SvmHandleExit(pVCpu, pCtx, &SvmTransient);
2598 if (rc != VINF_SUCCESS)
2599 break;
2600 else if (cLoops > pVM->hm.s.cMaxResumeLoops)
2601 {
2602 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitMaxResume);
2603 rc = VINF_EM_RAW_INTERRUPT;
2604 break;
2605 }
2606 }
2607
2608 if (rc == VERR_EM_INTERPRETER)
2609 rc = VINF_EM_RAW_EMULATE_INSTR;
2610 else if (rc == VINF_EM_RESET)
2611 rc = VINF_EM_TRIPLE_FAULT;
2612 hmR0SvmExitToRing3(pVM, pVCpu, pCtx, rc);
2613 return rc;
2614}
2615
2616
2617/**
2618 * Handles a #VMEXIT (for all EXITCODE values except SVM_EXIT_INVALID).
2619 *
2620 * @returns VBox status code (informational status codes included).
2621 * @param pVCpu Pointer to the VMCPU.
2622 * @param pCtx Pointer to the guest-CPU context.
2623 * @param pSvmTransient Pointer to the SVM transient structure.
2624 */
2625DECLINLINE(int) hmR0SvmHandleExit(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
2626{
2627 Assert(pSvmTransient->u64ExitCode > 0);
2628 Assert(pSvmTransient->u64ExitCode <= SVM_EXIT_MAX);
2629
2630 int rc;
2631 uint32_t u32ExitCode = pSvmTransient->u64ExitCode;
2632 switch (pSvmTransient->u64ExitCode)
2633 {
2634 case SVM_EXIT_CPUID:
2635 return hmR0SvmExitCpuid(pVCpu, pCtx, pSvmTransient);
2636
2637 case SVM_EXIT_RDTSC:
2638 return hmR0SvmExitRdtsc(pVCpu, pCtx, pSvmTransient);
2639
2640 case SVM_EXIT_RDTSCP:
2641 return hmR0SvmExitRdtscp(pVCpu, pCtx, pSvmTransient);
2642
2643 case SVM_EXIT_MONITOR:
2644 return hmR0SvmExitMonitor(pVCpu, pCtx, pSvmTransient);
2645
2646 case SVM_EXIT_MWAIT:
2647 return hmR0SvmExitMwait(pVCpu, pCtx, pSvmTransient);
2648
2649 case SVM_EXIT_WRITE_CR0:
2650 case SVM_EXIT_WRITE_CR3:
2651 case SVM_EXIT_WRITE_CR4:
2652 case SVM_EXIT_WRITE_CR8:
2653 return hmR0SvmExitWriteCRx(pVCpu, pCtx, pSvmTransient);
2654
2655 case SVM_EXIT_READ_CR0:
2656 case SVM_EXIT_READ_CR3:
2657 case SVM_EXIT_READ_CR4:
2658 return hmR0SvmExitReadCRx(pVCpu, pCtx, pSvmTransient);
2659
2660 case SVM_EXIT_MSR:
2661 return hmR0SvmExitMsr(pVCpu, pCtx, pSvmTransient);
2662
2663 case SVM_EXIT_INTR:
2664 case SVM_EXIT_FERR_FREEZE:
2665 case SVM_EXIT_NMI:
2666 case SVM_EXIT_INIT:
2667 return hmR0SvmExitIntr(pVCpu, pCtx, pSvmTransient);
2668
2669 case SVM_EXIT_WBINVD:
2670 return hmR0SvmExitWbinvd(pVCpu, pCtx, pSvmTransient);
2671
2672 case SVM_EXIT_INVD:
2673 return hmR0SvmExitInvd(pVCpu, pCtx, pSvmTransient);
2674
2675 case SVM_EXIT_RDPMC:
2676 return hmR0SvmExitRdpmc(pVCpu, pCtx, pSvmTransient);
2677
2678 case SVM_EXIT_READ_DR0: case SVM_EXIT_READ_DR1: case SVM_EXIT_READ_DR2: case SVM_EXIT_READ_DR3:
2679 case SVM_EXIT_READ_DR6: case SVM_EXIT_READ_DR7: case SVM_EXIT_READ_DR8: case SVM_EXIT_READ_DR9:
2680 case SVM_EXIT_READ_DR10: case SVM_EXIT_READ_DR11: case SVM_EXIT_READ_DR12: case SVM_EXIT_READ_DR13:
2681 case SVM_EXIT_READ_DR14: case SVM_EXIT_READ_DR15:
2682 return hmR0SvmExitReadDRx(pVCpu, pCtx, pSvmTransient);
2683
2684 case SVM_EXIT_WRITE_DR0: case SVM_EXIT_WRITE_DR1: case SVM_EXIT_WRITE_DR2: case SVM_EXIT_WRITE_DR3:
2685 case SVM_EXIT_WRITE_DR6: case SVM_EXIT_WRITE_DR7: case SVM_EXIT_WRITE_DR8: case SVM_EXIT_WRITE_DR9:
2686 case SVM_EXIT_WRITE_DR10: case SVM_EXIT_WRITE_DR11: case SVM_EXIT_WRITE_DR12: case SVM_EXIT_WRITE_DR13:
2687 case SVM_EXIT_WRITE_DR14: case SVM_EXIT_WRITE_DR15:
2688 return hmR0SvmExitWriteDRx(pVCpu, pCtx, pSvmTransient);
2689
2690 default:
2691 {
2692 case SVM_EXIT_INVLPGA:
2693 case SVM_EXIT_RSM:
2694 case SVM_EXIT_VMRUN:
2695 case SVM_EXIT_VMLOAD:
2696 case SVM_EXIT_VMSAVE:
2697 case SVM_EXIT_STGI:
2698 case SVM_EXIT_CLGI:
2699 case SVM_EXIT_SKINIT:
2700 return hmR0SvmExitSetPendingXcptUD(pVCpu, pCtx, pSvmTransient);
2701
2702 default:
2703 {
2704 rc = VERR_SVM_UNEXPECTED_EXIT;
2705 AssertMsgFailed(("hmR0SvmHandleExit: Unexpected exit code %#x\n", u32ExitCode));
2706 break;
2707 }
2708 }
2709 }
2710 return rc;
2711}
2712
2713
2714#ifdef DEBUG
2715/* Is there some generic IPRT define for this that are not in Runtime/internal/\* ?? */
2716# define HMSVM_ASSERT_PREEMPT_CPUID_VAR() \
2717 RTCPUID const idAssertCpu = RTThreadPreemptIsEnabled(NIL_RTTHREAD) ? NIL_RTCPUID : RTMpCpuId()
2718
2719# define HMSVM_ASSERT_PREEMPT_CPUID() \
2720 do \
2721 { \
2722 RTCPUID const idAssertCpuNow = RTThreadPreemptIsEnabled(NIL_RTTHREAD) ? NIL_RTCPUID : RTMpCpuId(); \
2723 AssertMsg(idAssertCpu == idAssertCpuNow, ("SVM %#x, %#x\n", idAssertCpu, idAssertCpuNow)); \
2724 } while (0)
2725
2726# define HMSVM_VALIDATE_EXIT_HANDLER_PARAMS() \
2727 do { \
2728 AssertPtr(pVCpu); \
2729 AssertPtr(pMixedCtx); \
2730 AssertPtr(pSvmTransient); \
2731 Assert(ASMIntAreEnabled()); \
2732 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD)); \
2733 HMSVM_ASSERT_PREEMPT_CPUID_VAR(); \
2734 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)); \
2735 Assert(!RTThreadPreemptIsEnabled(NIL_RTTHREAD)); \
2736 if (VMMR0IsLogFlushDisabled(pVCpu)) \
2737 HMSVM_ASSERT_PREEMPT_CPUID(); \
2738 HMSVM_STOP_EXIT_DISPATCH_PROF(); \
2739 } while (0)
2740#else /* Release builds */
2741# define HMSVM_VALIDATE_EXIT_HANDLER_PARAMS() do { } while(0)
2742#endif
2743
2744
2745/**
2746 * Worker for hmR0SvmInterpretInvlpg().
2747 *
2748 * @return VBox status code.
2749 * @param pVCpu Pointer to the VMCPU.
2750 * @param pCpu Pointer to the disassembler state.
2751 * @param pRegFrame Pointer to the register frame.
2752 */
2753static int hmR0SvmInterpretInvlPgEx(PVMCPU pVCpu, PDISCPUSTATE pCpu, PCPUMCTXCORE pRegFrame)
2754{
2755 DISQPVPARAMVAL Param1;
2756 RTGCPTR GCPtrPage;
2757
2758 int rc = DISQueryParamVal(pRegFrame, pCpu, &pCpu->Param1, &Param1, DISQPVWHICH_SRC);
2759 if (RT_FAILURE(rc))
2760 return VERR_EM_INTERPRETER;
2761
2762 if ( Param1.type == DISQPV_TYPE_IMMEDIATE
2763 || Param1.type == DISQPV_TYPE_ADDRESS)
2764 {
2765 if (!(Param1.flags & (DISQPV_FLAG_32 | DISQPV_FLAG_64)))
2766 return VERR_EM_INTERPRETER;
2767
2768 GCPtrPage = Param1.val.val64;
2769 rc = EMInterpretInvlpg(pVCpu->CTX_SUFF(pVM), pVCpu, pRegFrame, GCPtrPage);
2770 }
2771 else
2772 {
2773 Log4(("hmR0SvmInterpretInvlPgEx invalid parameter type %#x\n", Param1.type));
2774 rc = VERR_EM_INTERPRETER;
2775 }
2776
2777 return rc;
2778}
2779
2780
2781/**
2782 * Interprets INVLPG.
2783 *
2784 * @returns VBox status code.
2785 * @retval VINF_* Scheduling instructions.
2786 * @retval VERR_EM_INTERPRETER Something we can't cope with.
2787 * @retval VERR_* Fatal errors.
2788 *
2789 * @param pVM Pointer to the VM.
2790 * @param pRegFrame Pointer to the register frame.
2791 *
2792 * @remarks Updates the RIP if the instruction was executed successfully.
2793 */
2794static int hmR0SvmInterpretInvlpg(PVM pVM, PVMCPU pVCpu, PCPUMCTXCORE pRegFrame)
2795{
2796 /* Only allow 32 & 64 bit code. */
2797 if (CPUMGetGuestCodeBits(pVCpu) != 16)
2798 {
2799 PDISSTATE pDis = &pVCpu->hm.s.DisState;
2800 int rc = EMInterpretDisasCurrent(pVM, pVCpu, pDis, NULL /* pcbInstr */);
2801 if ( RT_SUCCESS(rc)
2802 && pDis->pCurInstr->uOpcode == OP_INVLPG)
2803 {
2804 rc = hmR0SvmInterpretInvlPgEx(pVCpu, pDis, pRegFrame);
2805 if (RT_SUCCESS(rc))
2806 pRegFrame->rip += pDis->cbInstr;
2807 return rc;
2808 }
2809 else
2810 Log4(("hmR0SvmInterpretInvlpg: EMInterpretDisasCurrent returned %Rrc uOpCode=%#x\n", rc, pDis->pCurInstr->uOpcode));
2811 }
2812 return VERR_EM_INTERPRETER;
2813}
2814
2815
2816/**
2817 * Sets an invalid-opcode (#UD) exception as pending-for-injection into the VM.
2818 *
2819 * @param pVCpu Pointer to the VMCPU.
2820 */
2821DECLINLINE(void) hmR0SvmSetPendingXcptUD(PVMCPU pVCpu)
2822{
2823 SVMEVENT Event;
2824 Event.u = 0;
2825 Event.n.u1Valid = 1;
2826 Event.n.u3Type = SVM_EVENT_EXCEPTION;
2827 Event.n.u8Vector = X86_XCPT_UD;
2828 hmR0SvmSetPendingEvent(pVCpu, &Event);
2829}
2830
2831
2832/**
2833 * Sets an debug (#DB) exception as pending-for-injection into the VM.
2834 *
2835 * @param pVCpu Pointer to the VMCPU.
2836 */
2837DECLINLINE(void) hmR0SvmSetPendingXcptDB(PVMCPU pVCpu)
2838{
2839 SVMEVENT Event;
2840 Event.u = 0;
2841 Event.n.u1Valid = 1;
2842 Event.n.u3Type = SVM_EVENT_EXCEPTION;
2843 Event.n.u8Vector = X86_XCPT_DB;
2844 hmR0SvmSetPendingEvent(pVCpu, &Event);
2845}
2846
2847
2848/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
2849/* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- #VMEXIT handlers -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- */
2850/* -=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= */
2851
2852/**
2853 * #VMEXIT handler for external interrupts, NMIs, FPU assertion freeze and INIT
2854 * signals (SVM_EXIT_INTR, SVM_EXIT_NMI, SVM_EXIT_FERR_FREEZE, SVM_EXIT_INIT).
2855 */
2856HMSVM_EXIT_DECL hmR0SvmExitIntr(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
2857{
2858 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
2859 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitExtInt);
2860 /* 32-bit Windows hosts (4 cores) has trouble with this on Intel; causes higher interrupt latency. Assuming the
2861 same for AMD-V.*/
2862#if HC_ARCH_BITS == 64 && defined(VBOX_WITH_VMMR0_DISABLE_PREEMPTION)
2863 Assert(ASMIntAreEnabled());
2864 return VINF_SUCCESS;
2865#else
2866 return VINF_EM_RAW_INTERRUPT;
2867#endif
2868}
2869
2870
2871/**
2872 * #VMEXIT handler for WBINVD (SVM_EXIT_WBINVD). Conditional #VMEXIT.
2873 */
2874HMSVM_EXIT_DECL hmR0SvmExitWbinvd(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
2875{
2876 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
2877 pCtx->rip += 2; /* Hardcoded opcode, AMD-V doesn't give us this information. */
2878 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitWbinvd);
2879 return VINF_SUCCESS;
2880}
2881
2882
2883/**
2884 * #VMEXIT handler for INVD (SVM_EXIT_INVD). Unconditional #VMEXIT.
2885 */
2886HMSVM_EXIT_DECL hmR0SvmExitInvd(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
2887{
2888 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
2889 pCtx->rip += 2; /* Hardcoded opcode, AMD-V doesn't give us this information. */
2890 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitInvd);
2891 return VINF_SUCCESS;
2892}
2893
2894
2895/**
2896 * #VMEXIT handler for INVD (SVM_EXIT_CPUID). Conditional #VMEXIT.
2897 */
2898HMSVM_EXIT_DECL hmR0SvmExitCpuid(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
2899{
2900 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
2901 PVM pVM = pVCpu->CTX_SUFF(pVM);
2902 int rc = EMInterpretCpuId(pVM, pVCpu, CPUMCTX2CORE(pCtx));
2903 if (RT_LIKELY(rc == VINF_SUCCESS))
2904 pCtx->rip += 2; /* Hardcoded opcode, AMD-V doesn't give us this information. */
2905 else
2906 {
2907 AssertMsgFailed(("hmR0SvmExitCpuid: EMInterpretCpuId failed with %Rrc\n", rc));
2908 rc = VERR_EM_INTERPRETER;
2909 }
2910 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCpuid);
2911 return rc;
2912}
2913
2914
2915/**
2916 * #VMEXIT handler for RDTSC (SVM_EXIT_RDTSC). Conditional #VMEXIT.
2917 */
2918HMSVM_EXIT_DECL hmR0SvmExitRdtsc(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
2919{
2920 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
2921 PVM pVM = pVCpu->CTX_SUFF(pVM);
2922 rc = EMInterpretRdtsc(pVM, pVCpu, CPUMCTX2CORE(pCtx));
2923 if (RT_LIKELY(rc == VINF_SUCCESS))
2924 pCtx->rip += 2; /* Hardcoded opcode, AMD-V doesn't give us this information. */
2925 else
2926 {
2927 AssertMsgFailed(("hmR0SvmExitRdtsc: EMInterpretRdtsc failed with %Rrc\n", rc));
2928 rc = VERR_EM_INTERPRETER;
2929 }
2930 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdtsc);
2931 return rc;
2932}
2933
2934
2935/**
2936 * #VMEXIT handler for RDTSCP (SVM_EXIT_RDTSCP). Conditional #VMEXIT.
2937 */
2938HMSVM_EXIT_DECL hmR0SvmExitRdtscp(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
2939{
2940 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
2941 int rc = EMInterpretRdtscp(pVM, pVCpu, pCtx);
2942 if (RT_LIKELY(rc == VINF_SUCCESS))
2943 pCtx->rip += 3; /* Hardcoded opcode, AMD-V doesn't give us this information. */
2944 else
2945 {
2946 AssertMsgFailed(("hmR0SvmExitRdtsc: EMInterpretRdtscp failed with %Rrc\n", rc));
2947 rc = VERR_EM_INTERPRETER;
2948 }
2949 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdtscp);
2950 return rc;
2951}
2952
2953
2954/**
2955 * #VMEXIT handler for RDPMC (SVM_EXIT_RDPMC). Conditional #VMEXIT.
2956 */
2957HMSVM_EXIT_DECL hmR0SvmExitRdpmc(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
2958{
2959 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
2960 int rc = EMInterpretRdpmc(pVM, pVCpu, CPUMCTX2CORE(pCtx));
2961 if (RT_LIKELY(rc == VINF_SUCCESS))
2962 pCtx->rip += 2; /* Hardcoded opcode, AMD-V doesn't give us this information. */
2963 else
2964 {
2965 AssertMsgFailed(("hmR0SvmExitRdpmc: EMInterpretRdpmc failed with %Rrc\n", rc));
2966 rc = VERR_EM_INTERPRETER;
2967 }
2968 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdpmc);
2969 return rc;
2970}
2971
2972
2973/**
2974 * #VMEXIT handler for INVLPG (SVM_EXIT_INVLPG). Conditional #VMEXIT.
2975 */
2976HMSVM_EXIT_DECL hmR0SvmExitInvlpg(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
2977{
2978 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
2979 Assert(!pVM->hm.s.fNestedPaging);
2980
2981 /** @todo Decode Assist. */
2982 int rc = hmR0SvmInterpretInvlpg(pVM, pVCpu, CPUMCTX2CORE(pCtx)); /* Updates RIP if successful. */
2983 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitInvlpg);
2984 Assert(rc == VINF_SUCCESS || rc == VERR_EM_INTERPRETER);
2985 return rc;
2986}
2987
2988
2989/**
2990 * #VMEXIT handler for HLT (SVM_EXIT_HLT). Conditional #VMEXIT.
2991 */
2992HMSVM_EXIT_DECL hmR0SvmExitHlt(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
2993{
2994 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
2995 pCtx->rip++; /* Hardcoded opcode, AMD-V doesn't give us this information. */
2996 int rc = EMShouldContinueAfterHalt(pVCpu, pCtx) ? VINF_SUCCESS : VINF_EM_HALT;
2997 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitHlt);
2998 return rc;
2999}
3000
3001
3002/**
3003 * #VMEXIT handler for MONITOR (SVM_EXIT_MONITOR). Conditional #VMEXIT.
3004 */
3005HMSVM_EXIT_DECL hmR0SvmExitMonitor(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3006{
3007 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3008 int rc = EMInterpretMonitor(pVM, pVCpu, CPUMCTX2CORE(pCtx));
3009 if (RT_LIKELY(rc == VINF_SUCCESS))
3010 pCtx->rip += 3; /* Hardcoded opcode, AMD-V doesn't give us this information. */
3011 else
3012 {
3013 AssertMsg(rc == VERR_EM_INTERPRETER, ("hmR0SvmExitMonitor: EMInterpretMonitor failed with %Rrc\n", rc));
3014 rc = VERR_EM_INTERPRETER;
3015 }
3016 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitMonitor);
3017 return rc;
3018}
3019
3020
3021/**
3022 * #VMEXIT handler for MWAIT (SVM_EXIT_MWAIT). Conditional #VMEXIT.
3023 */
3024HMSVM_EXIT_DECL hmR0SvmExitMwait(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3025{
3026 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3027 int rc = EMInterpretMWait(pVM, pVCpu, CPUMCTX2CORE(pCtx));
3028 if ( rc == VINF_EM_HALT
3029 || rc == VINF_SUCCESS)
3030 {
3031 pCtx->rip += 3; /* Hardcoded opcode, AMD-V doesn't give us this information. */
3032
3033 if ( rc == VINF_EM_HALT
3034 && EMShouldContinueAfterHalt(pVCpu, pMixedCtx))
3035 {
3036 rc = VINF_SUCCESS;
3037 }
3038 }
3039 else
3040 {
3041 AssertMsg(rc == VERR_EM_INTERPRETER, ("hmR0SvmExitMwait: EMInterpretMWait failed with %Rrc\n", rc));
3042 rc = VERR_EM_INTERPRETER;
3043 }
3044 AssertMsg(rc == VINF_SUCCESS || rc == VINF_EM_HALT || rc == VERR_EM_INTERPRETER,
3045 ("hmR0SvmExitMwait: EMInterpretMWait failed rc=%Rrc\n", rc));
3046 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitMwait);
3047 return rc;
3048}
3049
3050
3051/**
3052 * #VMEXIT handler for shutdown (triple-fault) (SVM_EXIT_SHUTDOWN).
3053 * Conditional #VMEXIT.
3054 */
3055HMSVM_EXIT_DECL hmR0SvmExitShutdown(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3056{
3057 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3058 return VINF_EM_RESET;
3059}
3060
3061
3062/**
3063 * #VMEXIT handler for CRx reads (SVM_EXIT_READ_CR*). Conditional #VMEXIT.
3064 */
3065HMSVM_EXIT_DECL hmR0SvmExitReadCRx(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3066{
3067 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3068 /** @todo Decode Assist. */
3069 int rc = EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0 /* pvFault */);
3070 Assert(rc == VERR_EM_INTERPRETER || rc == VINF_PGM_CHANGE_MODE || rc == VINF_PGM_SYNC_CR3);
3071 Assert((pSvmTransient->u64ExitCode - SVM_EXIT_READ_CR0) <= 15);
3072 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitCRxRead[pSvmTransient->u64ExitCode - SVM_EXIT_READ_CR0]);
3073 return rc;
3074}
3075
3076
3077/**
3078 * #VMEXIT handler for CRx writes (SVM_EXIT_WRITE_CR*). Conditional #VMEXIT.
3079 */
3080HMSVM_EXIT_DECL hmR0SvmExitWriteCRx(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3081{
3082 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3083 /** @todo Decode Assist. */
3084 int rc = EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0 /* pvFault */);
3085 if (rc == VINF_SUCCCES)
3086 {
3087 /* RIP has been updated by EMInterpretInstruction(). */
3088 Assert((pSvmTransient->u64ExitCode - SVM_EXIT_WRITE_CR0) <= 15);
3089 switch (pSvmTransient->u64ExitCode - SVM_EXIT_WRITE_CR0)
3090 {
3091 case 0: /* CR0. */
3092 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_GUEST_CR0;
3093 break;
3094
3095 case 3: /* CR3. */
3096 Assert(!pVM->hm.s.fNestedPaging);
3097 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_GUEST_CR3;
3098 break;
3099
3100 case 4: /* CR4. */
3101 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_GUEST_CR4;
3102 break;
3103
3104 case 8: /* CR8 (TPR). */
3105 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_SVM_GUEST_APIC_STATE;
3106 break;
3107
3108 default:
3109 AsserMsgFailed(("hmR0SvmExitWriteCRx: Invalid/Unexpected Write-CRx exit. u64ExitCode=%#RX64 %#x CRx=%#RX64\n",
3110 pSvmTransient->u64ExitCode, pSvmTransient->u64ExitCode - SVM_EXIT_WRITE_CR0));
3111 break;
3112 }
3113 }
3114 else
3115 Assert(rc == VERR_EM_INTERPRETER || rc == VINF_PGM_CHANGE_MODE || rc == VINF_PGM_SYNC_CR3);
3116 return rc;
3117}
3118
3119
3120/**
3121 * #VMEXIT handler for instructions that result in a #UD exception delivered to
3122 * the guest.
3123 */
3124HMSVM_EXIT_DECL hmR0SvmExitSetPendingXcptUD(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3125{
3126 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3127 return hmR0SvmSetPendingXcptUD(pVCpu);
3128}
3129
3130
3131/**
3132 * #VMEXIT handler for MSR read and writes (SVM_EXIT_MSR). Conditional #VMEXIT.
3133 */
3134HMSVM_EXIT_DECL hmR0SvmExitMsr(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3135{
3136 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3137 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
3138
3139 int rc;
3140 if (pVmcb->ctrl.u64ExitInfo1 == SVM_EXIT1_MSR_WRITE)
3141 {
3142 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitWrmsr);
3143
3144 /* Handle TPR patching; intercepted LSTAR write. */
3145 if ( pVM->hm.s.fTPRPatchingActive
3146 && pCtx->ecx == MSR_K8_LSTAR)
3147 {
3148 if ((pCtx->eax & 0xff) != pSvmTransient->u8GuestTpr)
3149 {
3150 /* Our patch code uses LSTAR for TPR caching for 32-bit guests. */
3151 int rc2 = PDMApicSetTPR(pVCpu, pCtx->eax & 0xff);
3152 AssertRC(rc2);
3153 }
3154 pCtx->rip += 2; /* Hardcoded opcode, AMD-V doesn't give us this information. */
3155 return VINF_SUCCESS;
3156 }
3157
3158 rc = EMInterpretWrmsr(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx));
3159 AssertMsg(rc == VINF_SUCCESS || rc == VERR_EM_INTERPRETER, ("hmR0SvmExitMsr: EMInterpretWrmsr failed rc=%Rrc\n", rc));
3160 }
3161 else
3162 {
3163 /* MSR Read access. */
3164 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitRdmsr);
3165 int rc = EMInterpretRdmsr(pVCpu->CTX_SUFF(pVM), pVCpu, CPUMCTX2CORE(pCtx));
3166 AssertMsg(rc == VINF_SUCCESS || rc == VERR_EM_INTERPRETER, ("hmR0SvmExitMsr: EMInterpretRdmsr failed rc=%Rrc\n", rc));
3167 }
3168
3169 /* RIP has been updated by EMInterpret[Rd|Wr]msr(). */
3170 return rc;
3171}
3172
3173
3174/**
3175 * #VMEXIT handler for DRx read (SVM_EXIT_READ_DRx). Conditional #VMEXIT.
3176 */
3177HMSVM_EXIT_DECL hmR0SvmExitReadDRx(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3178{
3179 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3180 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitDRxRead);
3181
3182 /* We should -not- get this VM-exit if the guest is debugging. */
3183 if (CPUMIsGuestDebugStateActive(pVCpu))
3184 {
3185 AssertMsgFailed(("hmR0SvmExitReadDRx: Unexpected exit. pVCpu=%p pCtx=%p\n", pVCpu, pCtx));
3186 return VERR_SVM_UNEXPECTED_EXIT;
3187 }
3188
3189 if ( !DBGFIsStepping(pVCpu)
3190 && !CPUMIsHyperDebugStateActive(pVCpu))
3191 {
3192 /* Don't intercept DRx read and writes. */
3193 PSVMVMCB pVmcb = (PSVMVMCB)pVCpu->hm.s.svm.pvVmcb;
3194 pVmcb->ctrl.u16InterceptRdDRx = 0;
3195 pVmcb->ctrl.u16InterceptWrDRx = 0;
3196 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_INTERCEPTS;
3197
3198 /* Save the host & load the guest debug state, restart execution of the MOV DRx instruction. */
3199 PVM pVM = pVCpu->CTX_SUFF(pVM);
3200 rc = CPUMR0LoadGuestDebugState(pVM, pVCpu, pCtx, true /* include DR6 */);
3201 AssertRC(rc);
3202 Assert(CPUMIsGuestDebugStateActive(pVCpu));
3203
3204 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxContextSwitch);
3205 return VINF_SUCCESS;
3206 }
3207
3208 /** @todo Decode assist. */
3209 int rc = EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0 /* pvFault */);
3210 if (RT_LIKELY(rc == VINF_SUCCESS))
3211 {
3212 /* Not necessary for read accesses but whatever doesn't hurt for now, will be fixed with decode assist. */
3213 pVCpu->hm.s.fContextUseFlags |= HM_CHANGED_GUEST_DEBUG;
3214 }
3215 else
3216 Assert(c == VERR_EM_INTERPRETER);
3217 return rc;
3218}
3219
3220
3221/**
3222 * #VMEXIT handler for DRx write (SVM_EXIT_WRITE_DRx). Conditional #VMEXIT.
3223 */
3224HMSVM_EXIT_DECL hmR0SvmExitWriteDRx(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3225{
3226 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3227 /* For now it's the same since we interpret the instruction anyway. Will change when using of Decode Assist is implemented. */
3228 int rc = hmR0SvmExitReadDRx(pVCpu, pCtx, pSvmTransient);
3229 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitDRxWrite);
3230 STAM_COUNTER_DEC(&pVCpu->hm.s.StatExitDRxRead);
3231 return rc;
3232}
3233
3234
3235/**
3236 * #VMEXIT handler for I/O instructions (SVM_EXIT_IOIO). Conditional #VMEXIT.
3237 */
3238HMSVM_EXIT_DECL hmR0SvmExitIOInstr(PVMCPU pVCpu, PCPUMCTX pCtx, PSVMTRANSIENT pSvmTransient)
3239{
3240 HMSVM_VALIDATE_EXIT_HANDLER_PARAMS();
3241
3242 /* I/O operation lookup arrays. */
3243 static uint32_t const s_aIOSize[8] = { 0, 1, 2, 0, 4, 0, 0, 0 }; /* Size of the I/O accesses in bytes. */
3244 static uint32_t const s_aIOOpAnd[8] = { 0, 0xff, 0xffff, 0, 0xffffffff, 0, 0, 0 }; /* AND masks for saving
3245 the result (in AL/AX/EAX). */
3246
3247 /* Refer AMD spec. 15.10.2 "IN and OUT Behaviour" and Figure 15-2. "EXITINFO1 for IOIO Intercept" for the format. */
3248 SVMIOIOEXIT IoExitInfo;
3249 IoExitInfo.u = (uint32_t)pVmcb->ctrl.u64ExitInfo1;
3250 uint32_t uIOWidth = (IoExitInfo.u >> 4) & 0x7;
3251 uint32_t uIOSize = s_aIOSize[uIOWidth];
3252 uint32_t uAndVal = s_aIOOpAnd[uIOWidth];
3253
3254 if (RT_UNLIKELY(!uIOSize))
3255 {
3256 AssertMsgFailed(("hmR0SvmExitIOInstr: Invalid IO operation. uIOWidth=%u\n", uIOWidth));
3257 return VERR_EM_INTERPRETER;
3258 }
3259
3260 int rc;
3261 if (IoExitInfo.n.u1STR)
3262 {
3263 /* INS/OUTS - I/O String instruction. */
3264 PDISCPUSTATE pDis = &pVCpu->hm.s.DisState;
3265
3266 /** @todo Huh? why can't we use the segment prefix information given by AMD-V
3267 * in EXITINFO1? Investigate once this thing is up and running. */
3268
3269 rc = EMInterpretDisasCurrent(pVM, pVCpu, pDis, NULL);
3270 if (rc == VINF_SUCCESS)
3271 {
3272 if (IoExitInfo.n.u1Type == 0) /* OUT */
3273 {
3274 rc = IOMInterpretOUTSEx(pVM, pVCpu, CPUMCTX2CORE(pCtx), IoExitInfo.n.u16Port, pDis->fPrefix,
3275 (DISCPUMODE)pDis->uAddrMode, uIOSize);
3276 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOStringWrite);
3277 }
3278 else
3279 {
3280 rc = IOMInterpretINSEx(pVM, pVCpu, CPUMCTX2CORE(pCtx), IoExitInfo.n.u16Port, pDis->fPrefix,
3281 (DISCPUMODE)pDis->uAddrMode, uIOSize);
3282 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOStringRead);
3283 }
3284 }
3285 else
3286 rc = VINF_EM_RAW_EMULATE_INSTR;
3287 }
3288 else
3289 {
3290 /* IN/OUT - I/O instruction. */
3291 Assert(!IoExitInfo.n.u1REP);
3292
3293 if (IoExitInfo.n.u1Type == 0) /* OUT */
3294 {
3295 rc = IOMIOPortWrite(pVM, pVCpu, IoExitInfo.n.u16Port, pCtx->eax & uAndVal, uIOSize);
3296 if (rc == VINF_IOM_R3_IOPORT_WRITE)
3297 HMR0SavePendingIOPortWrite(pVCpu, pCtx->rip, pVmcb->ctrl.u64ExitInfo2, IoExitInfo.n.u16Port, uAndVal, uIOSize);
3298
3299 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIOWrite);
3300 }
3301 else
3302 {
3303 uint32_t u32Val = 0;
3304
3305 rc = IOMIOPortRead(pVM, pVCpu, IoExitInfo.n.u16Port, &u32Val, uIOSize);
3306 if (IOM_SUCCESS(rc))
3307 {
3308 /* Save result of I/O IN instr. in AL/AX/EAX. */
3309 pCtx->eax = (pCtx->eax & ~uAndVal) | (u32Val & uAndVal);
3310 }
3311 else if (rc == VINF_IOM_R3_IOPORT_READ)
3312 HMR0SavePendingIOPortRead(pVCpu, pCtx->rip, pVmcb->ctrl.u64ExitInfo2, IoExitInfo.n.u16Port, uAndVal, uIOSize);
3313
3314 STAM_COUNTER_INC(&pVCpu->hm.s.StatExitIORead);
3315 }
3316 }
3317
3318 if (IOM_SUCCESS(rc))
3319 {
3320 /* AMD-V saves the RIP of the instruction following the IO instruction in EXITINFO2. */
3321 pCtx->rip = pVmcb->ctrl.u64ExitInfo2;
3322
3323 if (RT_LIKELY(rc == VINF_SUCCESS))
3324 {
3325 /* If any IO breakpoints are armed, then we should check if a debug trap needs to be generated. */
3326 if (pCtx->dr[7] & X86_DR7_ENABLED_MASK)
3327 {
3328 /* I/O breakpoint length, in bytes. */
3329 static uint32_t const s_aIOBPLen[4] = { 1, 2, 0, 4 };
3330
3331 STAM_COUNTER_INC(&pVCpu->hm.s.StatDRxIoCheck);
3332 for (unsigned i = 0; i < 4; i++)
3333 {
3334 unsigned uBPLen = s_aIOBPLen[X86_DR7_GET_LEN(pCtx->dr[7], i)];
3335
3336 if ( IoExitInfo.n.u16Port >= pCtx->dr[i]
3337 && IoExitInfo.n.u16Port < pCtx->dr[i] + uBPLen
3338 && (pCtx->dr[7] & (X86_DR7_L(i) | X86_DR7_G(i)))
3339 && (pCtx->dr[7] & X86_DR7_RW(i, X86_DR7_RW_IO)) == X86_DR7_RW(i, X86_DR7_RW_IO))
3340 {
3341 Assert(CPUMIsGuestDebugStateActive(pVCpu));
3342
3343 /* Clear all breakpoint status flags and set the one we just hit. */
3344 pCtx->dr[6] &= ~(X86_DR6_B0 | X86_DR6_B1 | X86_DR6_B2 | X86_DR6_B3);
3345 pCtx->dr[6] |= (uint64_t)RT_BIT(i);
3346
3347 /*
3348 * Note: AMD64 Architecture Programmer's Manual 13.1:
3349 * Bits 15:13 of the DR6 register is never cleared by the processor and must be cleared
3350 * by software after the contents have been read.
3351 */
3352 pVmcb->guest.u64DR6 = pCtx->dr[6];
3353
3354 /* X86_DR7_GD will be cleared if drx accesses should be trapped inside the guest. */
3355 pCtx->dr[7] &= ~X86_DR7_GD;
3356
3357 /* Paranoia. */
3358 pMixedCtx->dr[7] &= 0xffffffff; /* Upper 32 bits MBZ. */
3359 pMixedCtx->dr[7] &= ~(RT_BIT(11) | RT_BIT(12) | RT_BIT(14) | RT_BIT(15)); /* MBZ. */
3360 pMixedCtx->dr[7] |= 0x400; /* MB1. */
3361
3362 pVmcb->guest.u64DR7 = pCtx->dr[7];
3363 pVmcb->ctrl.u64VmcbCleanBits &= ~HMSVM_VMCB_CLEAN_DRX;
3364
3365 /* Inject the debug exception. */
3366 hmR0SvmSetPendingXcptDB(pVCpu);
3367 break;
3368 }
3369 }
3370 }
3371 }
3372 }
3373
3374#ifdef DEBUG
3375 if (rc == VINF_IOM_R3_IOPORT_READ)
3376 Assert(IoExitInfo.n.u1Type != 0);
3377 else if (rc == VINF_IOM_R3_IOPORT_WRITE)
3378 Assert(IoExitInfo.n.u1Type == 0);
3379 else
3380 {
3381 AssertMsg( RT_FAILURE(rc)
3382 || rc == VINF_SUCCESS
3383 || rc == VINF_EM_RAW_EMULATE_INSTR
3384 || rc == VINF_EM_RAW_GUEST_TRAP
3385 || rc == VINF_TRPM_XCPT_DISPATCHED, ("%Rrc\n", rc));
3386 }
3387#endif
3388 return rc;
3389}
3390
Note: See TracBrowser for help on using the repository browser.

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