VirtualBox

source: vbox/trunk/src/VBox/VMM/VMMR0/HWSVMR0.cpp@ 43197

Last change on this file since 43197 was 43073, checked in by vboxsync, 13 years ago

VMM/HWSVMR0: Fix assertion for AMD erratum Cpus that require flushing the entire TLB on every world switch.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 122.7 KB
Line 
1/* $Id: HWSVMR0.cpp 43073 2012-08-29 12:55:52Z vboxsync $ */
2/** @file
3 * HM SVM (AMD-V) - Host Context Ring-0.
4 */
5
6/*
7 * Copyright (C) 2006-2012 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#define LOG_GROUP LOG_GROUP_HWACCM
22#include <VBox/vmm/hwaccm.h>
23#include <VBox/vmm/pgm.h>
24#include <VBox/vmm/selm.h>
25#include <VBox/vmm/iom.h>
26#include <VBox/vmm/dbgf.h>
27#include <VBox/vmm/dbgftrace.h>
28#include <VBox/vmm/tm.h>
29#include <VBox/vmm/pdmapi.h>
30#include "HWACCMInternal.h"
31#include <VBox/vmm/vm.h>
32#include <VBox/vmm/hwacc_svm.h>
33#include <VBox/err.h>
34#include <VBox/log.h>
35#include <VBox/dis.h>
36#include <VBox/disopcode.h>
37#include <iprt/param.h>
38#include <iprt/assert.h>
39#include <iprt/asm.h>
40#include <iprt/asm-amd64-x86.h>
41#include <iprt/cpuset.h>
42#include <iprt/mp.h>
43#include <iprt/time.h>
44#ifdef VBOX_WITH_VMMR0_DISABLE_PREEMPTION
45# include <iprt/thread.h>
46#endif
47#include <iprt/x86.h>
48#include "HWSVMR0.h"
49
50#include "dtrace/VBoxVMM.h"
51
52
53/*******************************************************************************
54* Internal Functions *
55*******************************************************************************/
56static int hmR0SvmInterpretInvlpg(PVM pVM, PVMCPU pVCpu, PCPUMCTXCORE pRegFrame);
57static int hmR0SvmEmulateTprVMMCall(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx);
58static void hmR0SvmSetMSRPermission(PVMCPU pVCpu, unsigned ulMSR, bool fRead, bool fWrite);
59
60
61/*******************************************************************************
62* Global Variables *
63*******************************************************************************/
64/* IO operation lookup arrays. */
65static uint32_t const g_aIOSize[8] = {0, 1, 2, 0, 4, 0, 0, 0};
66static uint32_t const g_aIOOpAnd[8] = {0, 0xff, 0xffff, 0, 0xffffffff, 0, 0, 0};
67
68
69/**
70 * Sets up and activates AMD-V on the current CPU.
71 *
72 * @returns VBox status code.
73 * @param pCpu Pointer to the CPU info struct.
74 * @param pVM Pointer to the VM (can be NULL after a resume!).
75 * @param pvCpuPage Pointer to the global CPU page.
76 * @param HCPhysCpuPage Physical address of the global CPU page.
77 */
78VMMR0DECL(int) SVMR0EnableCpu(PHMGLOBLCPUINFO pCpu, PVM pVM, void *pvCpuPage, RTHCPHYS HCPhysCpuPage)
79{
80 AssertReturn(HCPhysCpuPage != 0 && HCPhysCpuPage != NIL_RTHCPHYS, VERR_INVALID_PARAMETER);
81 AssertReturn(pvCpuPage, VERR_INVALID_PARAMETER);
82
83 /*
84 * We must turn on AMD-V and setup the host state physical address, as those MSRs are per cpu/core.
85 */
86 uint64_t fEfer = ASMRdMsr(MSR_K6_EFER);
87 if (fEfer & MSR_K6_EFER_SVME)
88 {
89 /*
90 * If the VBOX_HWVIRTEX_IGNORE_SVM_IN_USE is active, then we blindly use AMD-V.
91 */
92 if ( pVM
93 && pVM->hwaccm.s.svm.fIgnoreInUseError)
94 {
95 pCpu->fIgnoreAMDVInUseError = true;
96 }
97
98 if (!pCpu->fIgnoreAMDVInUseError)
99 return VERR_SVM_IN_USE;
100 }
101
102 /* Turn on AMD-V in the EFER MSR. */
103 ASMWrMsr(MSR_K6_EFER, fEfer | MSR_K6_EFER_SVME);
104
105 /* Write the physical page address where the CPU will store the host state while executing the VM. */
106 ASMWrMsr(MSR_K8_VM_HSAVE_PA, HCPhysCpuPage);
107
108 /*
109 * Theoretically, other hypervisors may have used ASIDs, ideally we should flush all non-zero ASIDs
110 * when enabling SVM. AMD doesn't have an SVM instruction to flush all ASIDs (flushing is done
111 * upon VMRUN). Therefore, just set the fFlushASIDBeforeUse flag which instructs hmR0SvmSetupTLB()
112 * to flush the TLB with before using a new ASID.
113 */
114 pCpu->fFlushASIDBeforeUse = true;
115
116 /*
117 * Ensure each VCPU scheduled on this CPU gets a new VPID on resume. See @bugref{6255}.
118 */
119 ++pCpu->cTLBFlushes;
120
121 return VINF_SUCCESS;
122}
123
124
125/**
126 * Deactivates AMD-V on the current CPU.
127 *
128 * @returns VBox status code.
129 * @param pCpu Pointer to the CPU info struct.
130 * @param pvCpuPage Pointer to the global CPU page.
131 * @param HCPhysCpuPage Physical address of the global CPU page.
132 */
133VMMR0DECL(int) SVMR0DisableCpu(PHMGLOBLCPUINFO pCpu, void *pvCpuPage, RTHCPHYS HCPhysCpuPage)
134{
135 AssertReturn(HCPhysCpuPage != 0 && HCPhysCpuPage != NIL_RTHCPHYS, VERR_INVALID_PARAMETER);
136 AssertReturn(pvCpuPage, VERR_INVALID_PARAMETER);
137 NOREF(pCpu);
138
139 /* Turn off AMD-V in the EFER MSR. */
140 uint64_t fEfer = ASMRdMsr(MSR_K6_EFER);
141 ASMWrMsr(MSR_K6_EFER, fEfer & ~MSR_K6_EFER_SVME);
142
143 /* Invalidate host state physical address. */
144 ASMWrMsr(MSR_K8_VM_HSAVE_PA, 0);
145
146 return VINF_SUCCESS;
147}
148
149
150/**
151 * Does Ring-0 per VM AMD-V init.
152 *
153 * @returns VBox status code.
154 * @param pVM Pointer to the VM.
155 */
156VMMR0DECL(int) SVMR0InitVM(PVM pVM)
157{
158 int rc;
159
160 pVM->hwaccm.s.svm.pMemObjIOBitmap = NIL_RTR0MEMOBJ;
161
162 /* Allocate 12 KB for the IO bitmap (doesn't seem to be a way to convince SVM not to use it) */
163 rc = RTR0MemObjAllocCont(&pVM->hwaccm.s.svm.pMemObjIOBitmap, 3 << PAGE_SHIFT, true /* executable R0 mapping */);
164 if (RT_FAILURE(rc))
165 return rc;
166
167 pVM->hwaccm.s.svm.pIOBitmap = RTR0MemObjAddress(pVM->hwaccm.s.svm.pMemObjIOBitmap);
168 pVM->hwaccm.s.svm.pIOBitmapPhys = RTR0MemObjGetPagePhysAddr(pVM->hwaccm.s.svm.pMemObjIOBitmap, 0);
169 /* Set all bits to intercept all IO accesses. */
170 ASMMemFill32(pVM->hwaccm.s.svm.pIOBitmap, 3 << PAGE_SHIFT, 0xffffffff);
171
172 /*
173 * Erratum 170 which requires a forced TLB flush for each world switch:
174 * See http://www.amd.com/us-en/assets/content_type/white_papers_and_tech_docs/33610.pdf
175 *
176 * All BH-G1/2 and DH-G1/2 models include a fix:
177 * Athlon X2: 0x6b 1/2
178 * 0x68 1/2
179 * Athlon 64: 0x7f 1
180 * 0x6f 2
181 * Sempron: 0x7f 1/2
182 * 0x6f 2
183 * 0x6c 2
184 * 0x7c 2
185 * Turion 64: 0x68 2
186 */
187 uint32_t u32Dummy;
188 uint32_t u32Version, u32Family, u32Model, u32Stepping, u32BaseFamily;
189 ASMCpuId(1, &u32Version, &u32Dummy, &u32Dummy, &u32Dummy);
190 u32BaseFamily = (u32Version >> 8) & 0xf;
191 u32Family = u32BaseFamily + (u32BaseFamily == 0xf ? ((u32Version >> 20) & 0x7f) : 0);
192 u32Model = ((u32Version >> 4) & 0xf);
193 u32Model = u32Model | ((u32BaseFamily == 0xf ? (u32Version >> 16) & 0x0f : 0) << 4);
194 u32Stepping = u32Version & 0xf;
195 if ( u32Family == 0xf
196 && !((u32Model == 0x68 || u32Model == 0x6b || u32Model == 0x7f) && u32Stepping >= 1)
197 && !((u32Model == 0x6f || u32Model == 0x6c || u32Model == 0x7c) && u32Stepping >= 2))
198 {
199 Log(("SVMR0InitVM: AMD cpu with erratum 170 family %x model %x stepping %x\n", u32Family, u32Model, u32Stepping));
200 pVM->hwaccm.s.svm.fAlwaysFlushTLB = true;
201 }
202
203 /* Allocate VMCBs for all guest CPUs. */
204 for (VMCPUID i = 0; i < pVM->cCpus; i++)
205 {
206 PVMCPU pVCpu = &pVM->aCpus[i];
207
208 pVCpu->hwaccm.s.svm.pMemObjVMCBHost = NIL_RTR0MEMOBJ;
209 pVCpu->hwaccm.s.svm.pMemObjVMCB = NIL_RTR0MEMOBJ;
210 pVCpu->hwaccm.s.svm.pMemObjMSRBitmap = NIL_RTR0MEMOBJ;
211
212 /* Allocate one page for the host context */
213 rc = RTR0MemObjAllocCont(&pVCpu->hwaccm.s.svm.pMemObjVMCBHost, 1 << PAGE_SHIFT, true /* executable R0 mapping */);
214 if (RT_FAILURE(rc))
215 return rc;
216
217 pVCpu->hwaccm.s.svm.pVMCBHost = RTR0MemObjAddress(pVCpu->hwaccm.s.svm.pMemObjVMCBHost);
218 pVCpu->hwaccm.s.svm.pVMCBHostPhys = RTR0MemObjGetPagePhysAddr(pVCpu->hwaccm.s.svm.pMemObjVMCBHost, 0);
219 Assert(pVCpu->hwaccm.s.svm.pVMCBHostPhys < _4G);
220 ASMMemZeroPage(pVCpu->hwaccm.s.svm.pVMCBHost);
221
222 /* Allocate one page for the VM control block (VMCB). */
223 rc = RTR0MemObjAllocCont(&pVCpu->hwaccm.s.svm.pMemObjVMCB, 1 << PAGE_SHIFT, true /* executable R0 mapping */);
224 if (RT_FAILURE(rc))
225 return rc;
226
227 pVCpu->hwaccm.s.svm.pVMCB = RTR0MemObjAddress(pVCpu->hwaccm.s.svm.pMemObjVMCB);
228 pVCpu->hwaccm.s.svm.pVMCBPhys = RTR0MemObjGetPagePhysAddr(pVCpu->hwaccm.s.svm.pMemObjVMCB, 0);
229 Assert(pVCpu->hwaccm.s.svm.pVMCBPhys < _4G);
230 ASMMemZeroPage(pVCpu->hwaccm.s.svm.pVMCB);
231
232 /* Allocate 8 KB for the MSR bitmap (doesn't seem to be a way to convince SVM not to use it) */
233 rc = RTR0MemObjAllocCont(&pVCpu->hwaccm.s.svm.pMemObjMSRBitmap, 2 << PAGE_SHIFT, true /* executable R0 mapping */);
234 if (RT_FAILURE(rc))
235 return rc;
236
237 pVCpu->hwaccm.s.svm.pMSRBitmap = RTR0MemObjAddress(pVCpu->hwaccm.s.svm.pMemObjMSRBitmap);
238 pVCpu->hwaccm.s.svm.pMSRBitmapPhys = RTR0MemObjGetPagePhysAddr(pVCpu->hwaccm.s.svm.pMemObjMSRBitmap, 0);
239 /* Set all bits to intercept all MSR accesses. */
240 ASMMemFill32(pVCpu->hwaccm.s.svm.pMSRBitmap, 2 << PAGE_SHIFT, 0xffffffff);
241 }
242
243 return VINF_SUCCESS;
244}
245
246
247/**
248 * Does Ring-0 per VM AMD-V termination.
249 *
250 * @returns VBox status code.
251 * @param pVM Pointer to the VM.
252 */
253VMMR0DECL(int) SVMR0TermVM(PVM pVM)
254{
255 for (VMCPUID i = 0; i < pVM->cCpus; i++)
256 {
257 PVMCPU pVCpu = &pVM->aCpus[i];
258
259 if (pVCpu->hwaccm.s.svm.pMemObjVMCBHost != NIL_RTR0MEMOBJ)
260 {
261 RTR0MemObjFree(pVCpu->hwaccm.s.svm.pMemObjVMCBHost, false);
262 pVCpu->hwaccm.s.svm.pVMCBHost = 0;
263 pVCpu->hwaccm.s.svm.pVMCBHostPhys = 0;
264 pVCpu->hwaccm.s.svm.pMemObjVMCBHost = NIL_RTR0MEMOBJ;
265 }
266
267 if (pVCpu->hwaccm.s.svm.pMemObjVMCB != NIL_RTR0MEMOBJ)
268 {
269 RTR0MemObjFree(pVCpu->hwaccm.s.svm.pMemObjVMCB, false);
270 pVCpu->hwaccm.s.svm.pVMCB = 0;
271 pVCpu->hwaccm.s.svm.pVMCBPhys = 0;
272 pVCpu->hwaccm.s.svm.pMemObjVMCB = NIL_RTR0MEMOBJ;
273 }
274 if (pVCpu->hwaccm.s.svm.pMemObjMSRBitmap != NIL_RTR0MEMOBJ)
275 {
276 RTR0MemObjFree(pVCpu->hwaccm.s.svm.pMemObjMSRBitmap, false);
277 pVCpu->hwaccm.s.svm.pMSRBitmap = 0;
278 pVCpu->hwaccm.s.svm.pMSRBitmapPhys = 0;
279 pVCpu->hwaccm.s.svm.pMemObjMSRBitmap = NIL_RTR0MEMOBJ;
280 }
281 }
282 if (pVM->hwaccm.s.svm.pMemObjIOBitmap != NIL_RTR0MEMOBJ)
283 {
284 RTR0MemObjFree(pVM->hwaccm.s.svm.pMemObjIOBitmap, false);
285 pVM->hwaccm.s.svm.pIOBitmap = 0;
286 pVM->hwaccm.s.svm.pIOBitmapPhys = 0;
287 pVM->hwaccm.s.svm.pMemObjIOBitmap = NIL_RTR0MEMOBJ;
288 }
289 return VINF_SUCCESS;
290}
291
292
293/**
294 * Sets up AMD-V for the specified VM.
295 *
296 * @returns VBox status code.
297 * @param pVM Pointer to the VM.
298 */
299VMMR0DECL(int) SVMR0SetupVM(PVM pVM)
300{
301 int rc = VINF_SUCCESS;
302
303 AssertReturn(pVM, VERR_INVALID_PARAMETER);
304 Assert(pVM->hwaccm.s.svm.fSupported);
305
306 for (VMCPUID i = 0; i < pVM->cCpus; i++)
307 {
308 PVMCPU pVCpu = &pVM->aCpus[i];
309 SVM_VMCB *pVMCB = (SVM_VMCB *)pVM->aCpus[i].hwaccm.s.svm.pVMCB;
310
311 AssertMsgReturn(pVMCB, ("Invalid pVMCB\n"), VERR_HMSVM_INVALID_PVMCB);
312
313 /*
314 * Program the control fields. Most of them never have to be changed again.
315 * CR0/4 reads must be intercepted, our shadow values are not necessarily the same as the guest's.
316 * Note: CR0 & CR4 can be safely read when guest and shadow copies are identical.
317 */
318 pVMCB->ctrl.u16InterceptRdCRx = RT_BIT(0) | RT_BIT(4);
319
320 /* CR0/4 writes must be intercepted for obvious reasons. */
321 pVMCB->ctrl.u16InterceptWrCRx = RT_BIT(0) | RT_BIT(4);
322
323 /* Intercept all DRx reads and writes by default. Changed later on. */
324 pVMCB->ctrl.u16InterceptRdDRx = 0xFFFF;
325 pVMCB->ctrl.u16InterceptWrDRx = 0xFFFF;
326
327 /* Intercept traps; only #NM is always intercepted. */
328 pVMCB->ctrl.u32InterceptException = RT_BIT(X86_XCPT_NM);
329#ifdef VBOX_ALWAYS_TRAP_PF
330 pVMCB->ctrl.u32InterceptException |= RT_BIT(X86_XCPT_PF);
331#endif
332#ifdef VBOX_STRICT
333 pVMCB->ctrl.u32InterceptException |= RT_BIT(X86_XCPT_BP)
334 | RT_BIT(X86_XCPT_DB)
335 | RT_BIT(X86_XCPT_DE)
336 | RT_BIT(X86_XCPT_UD)
337 | RT_BIT(X86_XCPT_NP)
338 | RT_BIT(X86_XCPT_SS)
339 | RT_BIT(X86_XCPT_GP)
340 | RT_BIT(X86_XCPT_MF)
341 ;
342#endif
343
344 /* Set up instruction and miscellaneous intercepts. */
345 pVMCB->ctrl.u32InterceptCtrl1 = SVM_CTRL1_INTERCEPT_INTR
346 | SVM_CTRL1_INTERCEPT_VINTR
347 | SVM_CTRL1_INTERCEPT_NMI
348 | SVM_CTRL1_INTERCEPT_SMI
349 | SVM_CTRL1_INTERCEPT_INIT
350 | SVM_CTRL1_INTERCEPT_RDPMC
351 | SVM_CTRL1_INTERCEPT_CPUID
352 | SVM_CTRL1_INTERCEPT_RSM
353 | SVM_CTRL1_INTERCEPT_HLT
354 | SVM_CTRL1_INTERCEPT_INOUT_BITMAP
355 | SVM_CTRL1_INTERCEPT_MSR_SHADOW
356 | SVM_CTRL1_INTERCEPT_INVLPGA /* AMD only */
357 | SVM_CTRL1_INTERCEPT_SHUTDOWN /* fatal */
358 | SVM_CTRL1_INTERCEPT_FERR_FREEZE; /* Legacy FPU FERR handling. */
359 ;
360 pVMCB->ctrl.u32InterceptCtrl2 = SVM_CTRL2_INTERCEPT_VMRUN /* required */
361 | SVM_CTRL2_INTERCEPT_VMMCALL
362 | SVM_CTRL2_INTERCEPT_VMLOAD
363 | SVM_CTRL2_INTERCEPT_VMSAVE
364 | SVM_CTRL2_INTERCEPT_STGI
365 | SVM_CTRL2_INTERCEPT_CLGI
366 | SVM_CTRL2_INTERCEPT_SKINIT
367 | SVM_CTRL2_INTERCEPT_WBINVD
368 | SVM_CTRL2_INTERCEPT_MONITOR
369 | SVM_CTRL2_INTERCEPT_MWAIT_UNCOND; /* don't execute mwait or else we'll idle inside the
370 guest (host thinks the cpu load is high) */
371
372 Log(("pVMCB->ctrl.u32InterceptException = %x\n", pVMCB->ctrl.u32InterceptException));
373 Log(("pVMCB->ctrl.u32InterceptCtrl1 = %x\n", pVMCB->ctrl.u32InterceptCtrl1));
374 Log(("pVMCB->ctrl.u32InterceptCtrl2 = %x\n", pVMCB->ctrl.u32InterceptCtrl2));
375
376 /* Virtualize masking of INTR interrupts. (reads/writes from/to CR8 go to the V_TPR register) */
377 pVMCB->ctrl.IntCtrl.n.u1VIrqMasking = 1;
378
379 /* Ignore the priority in the TPR; just deliver it when we tell it to. */
380 pVMCB->ctrl.IntCtrl.n.u1IgnoreTPR = 1;
381
382 /* Set IO and MSR bitmap addresses. */
383 pVMCB->ctrl.u64IOPMPhysAddr = pVM->hwaccm.s.svm.pIOBitmapPhys;
384 pVMCB->ctrl.u64MSRPMPhysAddr = pVCpu->hwaccm.s.svm.pMSRBitmapPhys;
385
386 /* No LBR virtualization. */
387 pVMCB->ctrl.u64LBRVirt = 0;
388
389 /* The ASID must start at 1; the host uses 0. */
390 pVMCB->ctrl.TLBCtrl.n.u32ASID = 1;
391
392 /*
393 * Setup the PAT MSR (nested paging only)
394 * The default value should be 0x0007040600070406ULL, but we want to treat all guest memory as WB,
395 * so choose type 6 for all PAT slots.
396 */
397 pVMCB->guest.u64GPAT = 0x0006060606060606ULL;
398
399 /* If nested paging is not in use, additional intercepts have to be set up. */
400 if (!pVM->hwaccm.s.fNestedPaging)
401 {
402 /* CR3 reads/writes must be intercepted; our shadow values are different from guest's. */
403 pVMCB->ctrl.u16InterceptRdCRx |= RT_BIT(3);
404 pVMCB->ctrl.u16InterceptWrCRx |= RT_BIT(3);
405
406 /*
407 * We must also intercept:
408 * - INVLPG (must go through shadow paging)
409 * - task switches (may change CR3/EFLAGS/LDT)
410 */
411 pVMCB->ctrl.u32InterceptCtrl1 |= SVM_CTRL1_INTERCEPT_INVLPG
412 | SVM_CTRL1_INTERCEPT_TASK_SWITCH;
413
414 /* Page faults must be intercepted to implement shadow paging. */
415 pVMCB->ctrl.u32InterceptException |= RT_BIT(X86_XCPT_PF);
416 }
417
418 /*
419 * The following MSRs are saved automatically by vmload/vmsave, so we allow the guest
420 * to modify them directly.
421 */
422 hmR0SvmSetMSRPermission(pVCpu, MSR_K8_LSTAR, true, true);
423 hmR0SvmSetMSRPermission(pVCpu, MSR_K8_CSTAR, true, true);
424 hmR0SvmSetMSRPermission(pVCpu, MSR_K6_STAR, true, true);
425 hmR0SvmSetMSRPermission(pVCpu, MSR_K8_SF_MASK, true, true);
426 hmR0SvmSetMSRPermission(pVCpu, MSR_K8_FS_BASE, true, true);
427 hmR0SvmSetMSRPermission(pVCpu, MSR_K8_GS_BASE, true, true);
428 hmR0SvmSetMSRPermission(pVCpu, MSR_K8_KERNEL_GS_BASE, true, true);
429 hmR0SvmSetMSRPermission(pVCpu, MSR_IA32_SYSENTER_CS, true, true);
430 hmR0SvmSetMSRPermission(pVCpu, MSR_IA32_SYSENTER_ESP, true, true);
431 hmR0SvmSetMSRPermission(pVCpu, MSR_IA32_SYSENTER_EIP, true, true);
432 }
433
434 return rc;
435}
436
437
438/**
439 * Sets the permission bits for the specified MSR.
440 *
441 * @param pVCpu Pointer to the VMCPU.
442 * @param ulMSR MSR value.
443 * @param fRead Whether reading is allowed.
444 * @param fWrite Whether writing is allowed.
445 */
446static void hmR0SvmSetMSRPermission(PVMCPU pVCpu, unsigned ulMSR, bool fRead, bool fWrite)
447{
448 unsigned ulBit;
449 uint8_t *pMSRBitmap = (uint8_t *)pVCpu->hwaccm.s.svm.pMSRBitmap;
450
451 if (ulMSR <= 0x00001FFF)
452 {
453 /* Pentium-compatible MSRs */
454 ulBit = ulMSR * 2;
455 }
456 else if ( ulMSR >= 0xC0000000
457 && ulMSR <= 0xC0001FFF)
458 {
459 /* AMD Sixth Generation x86 Processor MSRs and SYSCALL */
460 ulBit = (ulMSR - 0xC0000000) * 2;
461 pMSRBitmap += 0x800;
462 }
463 else if ( ulMSR >= 0xC0010000
464 && ulMSR <= 0xC0011FFF)
465 {
466 /* AMD Seventh and Eighth Generation Processor MSRs */
467 ulBit = (ulMSR - 0xC0001000) * 2;
468 pMSRBitmap += 0x1000;
469 }
470 else
471 {
472 AssertFailed();
473 return;
474 }
475 Assert(ulBit < 16 * 1024 - 1);
476 if (fRead)
477 ASMBitClear(pMSRBitmap, ulBit);
478 else
479 ASMBitSet(pMSRBitmap, ulBit);
480
481 if (fWrite)
482 ASMBitClear(pMSRBitmap, ulBit + 1);
483 else
484 ASMBitSet(pMSRBitmap, ulBit + 1);
485}
486
487
488/**
489 * Injects an event (trap or external interrupt).
490 *
491 * @param pVCpu Pointer to the VMCPU.
492 * @param pVMCB Pointer to the VMCB.
493 * @param pCtx Pointer to the guest CPU context.
494 * @param pIntInfo Pointer to the SVM interrupt info.
495 */
496DECLINLINE(void) hmR0SvmInjectEvent(PVMCPU pVCpu, SVM_VMCB *pVMCB, CPUMCTX *pCtx, SVM_EVENT *pEvent)
497{
498#ifdef VBOX_WITH_STATISTICS
499 STAM_COUNTER_INC(&pVCpu->hwaccm.s.paStatInjectedIrqsR0[pEvent->n.u8Vector & MASK_INJECT_IRQ_STAT]);
500#endif
501
502#ifdef VBOX_STRICT
503 if (pEvent->n.u8Vector == 0xE)
504 {
505 Log(("SVM: Inject int %d at %RGv error code=%02x CR2=%RGv intInfo=%08x\n", pEvent->n.u8Vector,
506 (RTGCPTR)pCtx->rip, pEvent->n.u32ErrorCode, (RTGCPTR)pCtx->cr2, pEvent->au64[0]));
507 }
508 else if (pEvent->n.u8Vector < 0x20)
509 Log(("SVM: Inject int %d at %RGv error code=%08x\n", pEvent->n.u8Vector, (RTGCPTR)pCtx->rip, pEvent->n.u32ErrorCode));
510 else
511 {
512 Log(("INJ-EI: %x at %RGv\n", pEvent->n.u8Vector, (RTGCPTR)pCtx->rip));
513 Assert(!VMCPU_FF_ISSET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS));
514 Assert(pCtx->eflags.u32 & X86_EFL_IF);
515 }
516#endif
517
518 /* Set event injection state. */
519 pVMCB->ctrl.EventInject.au64[0] = pEvent->au64[0];
520}
521
522
523/**
524 * Checks for pending guest interrupts and injects them.
525 *
526 * @returns VBox status code.
527 * @param pVM Pointer to the VM.
528 * @param pVCpu Pointer to the VMCPU.
529 * @param pVMCB Pointer to the VMCB.
530 * @param pCtx Pointer to the guest CPU Context.
531 */
532static int hmR0SvmCheckPendingInterrupt(PVM pVM, PVMCPU pVCpu, SVM_VMCB *pVMCB, CPUMCTX *pCtx)
533{
534 int rc;
535 NOREF(pVM);
536
537 /*
538 * Dispatch any pending interrupts (injected before, but a VM-exit occurred prematurely).
539 */
540 if (pVCpu->hwaccm.s.Event.fPending)
541 {
542 SVM_EVENT Event;
543
544 Log(("Reinjecting event %08x %08x at %RGv\n", pVCpu->hwaccm.s.Event.intInfo, pVCpu->hwaccm.s.Event.errCode,
545 (RTGCPTR)pCtx->rip));
546 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatIntReinject);
547 Event.au64[0] = pVCpu->hwaccm.s.Event.intInfo;
548 hmR0SvmInjectEvent(pVCpu, pVMCB, pCtx, &Event);
549
550 pVCpu->hwaccm.s.Event.fPending = false;
551 return VINF_SUCCESS;
552 }
553
554 /*
555 * If an active trap is already pending, we must forward it first!
556 */
557 if (!TRPMHasTrap(pVCpu))
558 {
559 if (VMCPU_FF_TESTANDCLEAR(pVCpu, VMCPU_FF_INTERRUPT_NMI))
560 {
561 SVM_EVENT Event;
562
563 Log(("CPU%d: injecting #NMI\n", pVCpu->idCpu));
564 Event.n.u8Vector = X86_XCPT_NMI;
565 Event.n.u1Valid = 1;
566 Event.n.u32ErrorCode = 0;
567 Event.n.u3Type = SVM_EVENT_NMI;
568
569 hmR0SvmInjectEvent(pVCpu, pVMCB, pCtx, &Event);
570 return VINF_SUCCESS;
571 }
572
573 /** @todo SMI interrupts. */
574
575 /*
576 * When external interrupts are pending, we should exit the VM when IF is set.
577 */
578 if (VMCPU_FF_ISPENDING(pVCpu, (VMCPU_FF_INTERRUPT_APIC|VMCPU_FF_INTERRUPT_PIC)))
579 {
580 if ( !(pCtx->eflags.u32 & X86_EFL_IF)
581 || VMCPU_FF_ISSET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
582 {
583 if (!pVMCB->ctrl.IntCtrl.n.u1VIrqValid)
584 {
585 if (!VMCPU_FF_ISSET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
586 LogFlow(("Enable irq window exit!\n"));
587 else
588 {
589 Log(("Pending interrupt blocked at %RGv by VM_FF_INHIBIT_INTERRUPTS -> irq window exit\n",
590 (RTGCPTR)pCtx->rip));
591 }
592
593 /** @todo Use virtual interrupt method to inject a pending IRQ; dispatched as
594 * soon as guest.IF is set. */
595 pVMCB->ctrl.u32InterceptCtrl1 |= SVM_CTRL1_INTERCEPT_VINTR;
596 pVMCB->ctrl.IntCtrl.n.u1VIrqValid = 1;
597 pVMCB->ctrl.IntCtrl.n.u8VIrqVector = 0; /* don't care */
598 }
599 }
600 else
601 {
602 uint8_t u8Interrupt;
603
604 rc = PDMGetInterrupt(pVCpu, &u8Interrupt);
605 Log(("Dispatch interrupt: u8Interrupt=%x (%d) rc=%Rrc\n", u8Interrupt, u8Interrupt, rc));
606 if (RT_SUCCESS(rc))
607 {
608 rc = TRPMAssertTrap(pVCpu, u8Interrupt, TRPM_HARDWARE_INT);
609 AssertRC(rc);
610 }
611 else
612 {
613 /* Can only happen in rare cases where a pending interrupt is cleared behind our back */
614 Assert(!VMCPU_FF_ISPENDING(pVCpu, (VMCPU_FF_INTERRUPT_APIC|VMCPU_FF_INTERRUPT_PIC)));
615 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatSwitchGuestIrq);
616 /* Just continue */
617 }
618 }
619 }
620 }
621
622#ifdef VBOX_STRICT
623 if (TRPMHasTrap(pVCpu))
624 {
625 uint8_t u8Vector;
626 rc = TRPMQueryTrapAll(pVCpu, &u8Vector, 0, 0, 0);
627 AssertRC(rc);
628 }
629#endif
630
631 if ( (pCtx->eflags.u32 & X86_EFL_IF)
632 && (!VMCPU_FF_ISSET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
633 && TRPMHasTrap(pVCpu)
634 )
635 {
636 uint8_t u8Vector;
637 TRPMEVENT enmType;
638 SVM_EVENT Event;
639 RTGCUINT u32ErrorCode;
640
641 Event.au64[0] = 0;
642
643 /* If a new event is pending, then dispatch it now. */
644 rc = TRPMQueryTrapAll(pVCpu, &u8Vector, &enmType, &u32ErrorCode, 0);
645 AssertRC(rc);
646 Assert(pCtx->eflags.Bits.u1IF == 1 || enmType == TRPM_TRAP);
647 Assert(enmType != TRPM_SOFTWARE_INT);
648
649 /* Clear the pending trap. */
650 rc = TRPMResetTrap(pVCpu);
651 AssertRC(rc);
652
653 Event.n.u8Vector = u8Vector;
654 Event.n.u1Valid = 1;
655 Event.n.u32ErrorCode = u32ErrorCode;
656
657 if (enmType == TRPM_TRAP)
658 {
659 switch (u8Vector)
660 {
661 case X86_XCPT_DF:
662 case X86_XCPT_TS:
663 case X86_XCPT_NP:
664 case X86_XCPT_SS:
665 case X86_XCPT_GP:
666 case X86_XCPT_PF:
667 case X86_XCPT_AC:
668 /* Valid error codes. */
669 Event.n.u1ErrorCodeValid = 1;
670 break;
671 default:
672 break;
673 }
674 if (u8Vector == X86_XCPT_NMI)
675 Event.n.u3Type = SVM_EVENT_NMI;
676 else
677 Event.n.u3Type = SVM_EVENT_EXCEPTION;
678 }
679 else
680 Event.n.u3Type = SVM_EVENT_EXTERNAL_IRQ;
681
682 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatIntInject);
683 hmR0SvmInjectEvent(pVCpu, pVMCB, pCtx, &Event);
684 } /* if (interrupts can be dispatched) */
685
686 return VINF_SUCCESS;
687}
688
689
690/**
691 * Save the host state.
692 *
693 * @returns VBox status code.
694 * @param pVM Pointer to the VM.
695 * @param pVCpu Pointer to the VMCPU.
696 */
697VMMR0DECL(int) SVMR0SaveHostState(PVM pVM, PVMCPU pVCpu)
698{
699 NOREF(pVM);
700 NOREF(pVCpu);
701 /* Nothing to do here. */
702 return VINF_SUCCESS;
703}
704
705
706/**
707 * Loads the guest state.
708 *
709 * NOTE: Don't do anything here that can cause a jump back to ring-3!!!
710 *
711 * @returns VBox status code.
712 * @param pVM Pointer to the VM.
713 * @param pVCpu Pointer to the VMCPU.
714 * @param pCtx Pointer to the guest CPU context.
715 */
716VMMR0DECL(int) SVMR0LoadGuestState(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
717{
718 RTGCUINTPTR val;
719 SVM_VMCB *pVMCB;
720
721 if (pVM == NULL)
722 return VERR_INVALID_PARAMETER;
723
724 /* Setup AMD SVM. */
725 Assert(pVM->hwaccm.s.svm.fSupported);
726
727 pVMCB = (SVM_VMCB *)pVCpu->hwaccm.s.svm.pVMCB;
728 AssertMsgReturn(pVMCB, ("Invalid pVMCB\n"), VERR_HMSVM_INVALID_PVMCB);
729
730 /* Guest CPU context: ES, CS, SS, DS, FS, GS. */
731 if (pVCpu->hwaccm.s.fContextUseFlags & HWACCM_CHANGED_GUEST_SEGMENT_REGS)
732 {
733 SVM_WRITE_SELREG(CS, cs);
734 SVM_WRITE_SELREG(SS, ss);
735 SVM_WRITE_SELREG(DS, ds);
736 SVM_WRITE_SELREG(ES, es);
737 SVM_WRITE_SELREG(FS, fs);
738 SVM_WRITE_SELREG(GS, gs);
739 }
740
741 /* Guest CPU context: LDTR. */
742 if (pVCpu->hwaccm.s.fContextUseFlags & HWACCM_CHANGED_GUEST_LDTR)
743 {
744 SVM_WRITE_SELREG(LDTR, ldtr);
745 }
746
747 /* Guest CPU context: TR. */
748 if (pVCpu->hwaccm.s.fContextUseFlags & HWACCM_CHANGED_GUEST_TR)
749 {
750 SVM_WRITE_SELREG(TR, tr);
751 }
752
753 /* Guest CPU context: GDTR. */
754 if (pVCpu->hwaccm.s.fContextUseFlags & HWACCM_CHANGED_GUEST_GDTR)
755 {
756 pVMCB->guest.GDTR.u32Limit = pCtx->gdtr.cbGdt;
757 pVMCB->guest.GDTR.u64Base = pCtx->gdtr.pGdt;
758 }
759
760 /* Guest CPU context: IDTR. */
761 if (pVCpu->hwaccm.s.fContextUseFlags & HWACCM_CHANGED_GUEST_IDTR)
762 {
763 pVMCB->guest.IDTR.u32Limit = pCtx->idtr.cbIdt;
764 pVMCB->guest.IDTR.u64Base = pCtx->idtr.pIdt;
765 }
766
767 /*
768 * Sysenter MSRs (unconditional)
769 */
770 pVMCB->guest.u64SysEnterCS = pCtx->SysEnter.cs;
771 pVMCB->guest.u64SysEnterEIP = pCtx->SysEnter.eip;
772 pVMCB->guest.u64SysEnterESP = pCtx->SysEnter.esp;
773
774 /* Control registers */
775 if (pVCpu->hwaccm.s.fContextUseFlags & HWACCM_CHANGED_GUEST_CR0)
776 {
777 val = pCtx->cr0;
778 if (!CPUMIsGuestFPUStateActive(pVCpu))
779 {
780 /* Always use #NM exceptions to load the FPU/XMM state on demand. */
781 val |= X86_CR0_TS | X86_CR0_ET | X86_CR0_NE | X86_CR0_MP;
782 }
783 else
784 {
785 /** @todo check if we support the old style mess correctly. */
786 if (!(val & X86_CR0_NE))
787 {
788 Log(("Forcing X86_CR0_NE!!!\n"));
789
790 /* Also catch floating point exceptions as we need to report them to the guest in a different way. */
791 if (!pVCpu->hwaccm.s.fFPUOldStyleOverride)
792 {
793 pVMCB->ctrl.u32InterceptException |= RT_BIT(X86_XCPT_MF);
794 pVCpu->hwaccm.s.fFPUOldStyleOverride = true;
795 }
796 }
797 val |= X86_CR0_NE; /* always turn on the native mechanism to report FPU errors (old style uses interrupts) */
798 }
799 /* Always enable caching. */
800 val &= ~(X86_CR0_CD|X86_CR0_NW);
801
802 /*
803 * Note: WP is not relevant in nested paging mode as we catch accesses on the (guest) physical level.
804 * Note: In nested paging mode, the guest is allowed to run with paging disabled; the guest-physical to host-physical
805 * translation will remain active.
806 */
807 if (!pVM->hwaccm.s.fNestedPaging)
808 {
809 val |= X86_CR0_PG; /* Paging is always enabled; even when the guest is running in real mode or PE without paging. */
810 val |= X86_CR0_WP; /* Must set this as we rely on protecting various pages and supervisor writes must be caught. */
811 }
812 pVMCB->guest.u64CR0 = val;
813 }
814 /* CR2 as well */
815 pVMCB->guest.u64CR2 = pCtx->cr2;
816
817 if (pVCpu->hwaccm.s.fContextUseFlags & HWACCM_CHANGED_GUEST_CR3)
818 {
819 /* Save our shadow CR3 register. */
820 if (pVM->hwaccm.s.fNestedPaging)
821 {
822 PGMMODE enmShwPagingMode;
823
824#if HC_ARCH_BITS == 32
825 if (CPUMIsGuestInLongModeEx(pCtx))
826 enmShwPagingMode = PGMMODE_AMD64_NX;
827 else
828#endif
829 enmShwPagingMode = PGMGetHostMode(pVM);
830
831 pVMCB->ctrl.u64NestedPagingCR3 = PGMGetNestedCR3(pVCpu, enmShwPagingMode);
832 Assert(pVMCB->ctrl.u64NestedPagingCR3);
833 pVMCB->guest.u64CR3 = pCtx->cr3;
834 }
835 else
836 {
837 pVMCB->guest.u64CR3 = PGMGetHyperCR3(pVCpu);
838 Assert(pVMCB->guest.u64CR3 || VMCPU_FF_ISPENDING(pVCpu, VMCPU_FF_PGM_SYNC_CR3 | VMCPU_FF_PGM_SYNC_CR3_NON_GLOBAL));
839 }
840 }
841
842 if (pVCpu->hwaccm.s.fContextUseFlags & HWACCM_CHANGED_GUEST_CR4)
843 {
844 val = pCtx->cr4;
845 if (!pVM->hwaccm.s.fNestedPaging)
846 {
847 switch (pVCpu->hwaccm.s.enmShadowMode)
848 {
849 case PGMMODE_REAL:
850 case PGMMODE_PROTECTED: /* Protected mode, no paging. */
851 AssertFailed();
852 return VERR_PGM_UNSUPPORTED_SHADOW_PAGING_MODE;
853
854 case PGMMODE_32_BIT: /* 32-bit paging. */
855 val &= ~X86_CR4_PAE;
856 break;
857
858 case PGMMODE_PAE: /* PAE paging. */
859 case PGMMODE_PAE_NX: /* PAE paging with NX enabled. */
860 /** Must use PAE paging as we could use physical memory > 4 GB */
861 val |= X86_CR4_PAE;
862 break;
863
864 case PGMMODE_AMD64: /* 64-bit AMD paging (long mode). */
865 case PGMMODE_AMD64_NX: /* 64-bit AMD paging (long mode) with NX enabled. */
866#ifdef VBOX_ENABLE_64_BITS_GUESTS
867 break;
868#else
869 AssertFailed();
870 return VERR_PGM_UNSUPPORTED_SHADOW_PAGING_MODE;
871#endif
872
873 default: /* shut up gcc */
874 AssertFailed();
875 return VERR_PGM_UNSUPPORTED_SHADOW_PAGING_MODE;
876 }
877 }
878 pVMCB->guest.u64CR4 = val;
879 }
880
881 /* Debug registers. */
882 if (pVCpu->hwaccm.s.fContextUseFlags & HWACCM_CHANGED_GUEST_DEBUG)
883 {
884 pCtx->dr[6] |= X86_DR6_INIT_VAL; /* set all reserved bits to 1. */
885 pCtx->dr[6] &= ~RT_BIT(12); /* must be zero. */
886
887 pCtx->dr[7] &= 0xffffffff; /* upper 32 bits reserved */
888 pCtx->dr[7] &= ~(RT_BIT(11) | RT_BIT(12) | RT_BIT(14) | RT_BIT(15)); /* must be zero */
889 pCtx->dr[7] |= 0x400; /* must be one */
890
891 pVMCB->guest.u64DR7 = pCtx->dr[7];
892 pVMCB->guest.u64DR6 = pCtx->dr[6];
893
894#ifdef DEBUG
895 /* Sync the hypervisor debug state now if any breakpoint is armed. */
896 if ( CPUMGetHyperDR7(pVCpu) & (X86_DR7_ENABLED_MASK|X86_DR7_GD)
897 && !CPUMIsHyperDebugStateActive(pVCpu)
898 && !DBGFIsStepping(pVCpu))
899 {
900 /* Save the host and load the hypervisor debug state. */
901 int rc = CPUMR0LoadHyperDebugState(pVM, pVCpu, pCtx, false /* exclude DR6 */);
902 AssertRC(rc);
903
904 /* DRx intercepts remain enabled. */
905
906 /* Override dr6 & dr7 with the hypervisor values. */
907 pVMCB->guest.u64DR7 = CPUMGetHyperDR7(pVCpu);
908 pVMCB->guest.u64DR6 = CPUMGetHyperDR6(pVCpu);
909 }
910 else
911#endif
912 /* Sync the debug state now if any breakpoint is armed. */
913 if ( (pCtx->dr[7] & (X86_DR7_ENABLED_MASK|X86_DR7_GD))
914 && !CPUMIsGuestDebugStateActive(pVCpu)
915 && !DBGFIsStepping(pVCpu))
916 {
917 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatDRxArmed);
918
919 /* Disable drx move intercepts. */
920 pVMCB->ctrl.u16InterceptRdDRx = 0;
921 pVMCB->ctrl.u16InterceptWrDRx = 0;
922
923 /* Save the host and load the guest debug state. */
924 int rc = CPUMR0LoadGuestDebugState(pVM, pVCpu, pCtx, false /* exclude DR6 */);
925 AssertRC(rc);
926 }
927 }
928
929 /* EIP, ESP and EFLAGS */
930 pVMCB->guest.u64RIP = pCtx->rip;
931 pVMCB->guest.u64RSP = pCtx->rsp;
932 pVMCB->guest.u64RFlags = pCtx->eflags.u32;
933
934 /* Set CPL */
935 pVMCB->guest.u8CPL = pCtx->ss.Attr.n.u2Dpl;
936
937 /* RAX/EAX too, as VMRUN uses RAX as an implicit parameter. */
938 pVMCB->guest.u64RAX = pCtx->rax;
939
940 /* vmrun will fail without MSR_K6_EFER_SVME. */
941 pVMCB->guest.u64EFER = pCtx->msrEFER | MSR_K6_EFER_SVME;
942
943 /* 64 bits guest mode? */
944 if (CPUMIsGuestInLongModeEx(pCtx))
945 {
946#if !defined(VBOX_ENABLE_64_BITS_GUESTS)
947 return VERR_PGM_UNSUPPORTED_SHADOW_PAGING_MODE;
948#elif HC_ARCH_BITS == 32 && !defined(VBOX_WITH_HYBRID_32BIT_KERNEL)
949 pVCpu->hwaccm.s.svm.pfnVMRun = SVMR0VMSwitcherRun64;
950#else
951# ifdef VBOX_WITH_HYBRID_32BIT_KERNEL
952 if (!pVM->hwaccm.s.fAllow64BitGuests)
953 return VERR_PGM_UNSUPPORTED_SHADOW_PAGING_MODE;
954# endif
955 pVCpu->hwaccm.s.svm.pfnVMRun = SVMR0VMRun64;
956#endif
957 /* Unconditionally update these as wrmsr might have changed them. (HWACCM_CHANGED_GUEST_SEGMENT_REGS will not be set) */
958 pVMCB->guest.FS.u64Base = pCtx->fs.u64Base;
959 pVMCB->guest.GS.u64Base = pCtx->gs.u64Base;
960 }
961 else
962 {
963 /* Filter out the MSR_K6_LME bit or else AMD-V expects amd64 shadow paging. */
964 pVMCB->guest.u64EFER &= ~MSR_K6_EFER_LME;
965
966 pVCpu->hwaccm.s.svm.pfnVMRun = SVMR0VMRun;
967 }
968
969 /* TSC offset. */
970 if (TMCpuTickCanUseRealTSC(pVCpu, &pVMCB->ctrl.u64TSCOffset))
971 {
972 uint64_t u64CurTSC = ASMReadTSC();
973 if (u64CurTSC + pVMCB->ctrl.u64TSCOffset >= TMCpuTickGetLastSeen(pVCpu))
974 {
975 pVMCB->ctrl.u32InterceptCtrl1 &= ~SVM_CTRL1_INTERCEPT_RDTSC;
976 pVMCB->ctrl.u32InterceptCtrl2 &= ~SVM_CTRL2_INTERCEPT_RDTSCP;
977 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatTSCOffset);
978 }
979 else
980 {
981 /* Fall back to rdtsc emulation as we would otherwise pass decreasing tsc values to the guest. */
982 LogFlow(("TSC %RX64 offset %RX64 time=%RX64 last=%RX64 (diff=%RX64, virt_tsc=%RX64)\n", u64CurTSC,
983 pVMCB->ctrl.u64TSCOffset, u64CurTSC + pVMCB->ctrl.u64TSCOffset, TMCpuTickGetLastSeen(pVCpu),
984 TMCpuTickGetLastSeen(pVCpu) - u64CurTSC - pVMCB->ctrl.u64TSCOffset, TMCpuTickGet(pVCpu)));
985 pVMCB->ctrl.u32InterceptCtrl1 |= SVM_CTRL1_INTERCEPT_RDTSC;
986 pVMCB->ctrl.u32InterceptCtrl2 |= SVM_CTRL2_INTERCEPT_RDTSCP;
987 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatTSCInterceptOverFlow);
988 }
989 }
990 else
991 {
992 pVMCB->ctrl.u32InterceptCtrl1 |= SVM_CTRL1_INTERCEPT_RDTSC;
993 pVMCB->ctrl.u32InterceptCtrl2 |= SVM_CTRL2_INTERCEPT_RDTSCP;
994 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatTSCIntercept);
995 }
996
997 /* Sync the various MSRs for 64-bit mode. */
998 pVMCB->guest.u64STAR = pCtx->msrSTAR; /* legacy syscall eip, cs & ss */
999 pVMCB->guest.u64LSTAR = pCtx->msrLSTAR; /* 64-bit mode syscall rip */
1000 pVMCB->guest.u64CSTAR = pCtx->msrCSTAR; /* compatibility mode syscall rip */
1001 pVMCB->guest.u64SFMASK = pCtx->msrSFMASK; /* syscall flag mask */
1002 pVMCB->guest.u64KernelGSBase = pCtx->msrKERNELGSBASE; /* SWAPGS exchange value */
1003
1004#ifdef DEBUG
1005 /* Intercept X86_XCPT_DB if stepping is enabled */
1006 if ( DBGFIsStepping(pVCpu)
1007 || CPUMIsHyperDebugStateActive(pVCpu))
1008 pVMCB->ctrl.u32InterceptException |= RT_BIT(X86_XCPT_DB);
1009 else
1010 pVMCB->ctrl.u32InterceptException &= ~RT_BIT(X86_XCPT_DB);
1011#endif
1012
1013 /* Done. */
1014 pVCpu->hwaccm.s.fContextUseFlags &= ~HWACCM_CHANGED_ALL_GUEST;
1015
1016 return VINF_SUCCESS;
1017}
1018
1019
1020/**
1021 * Setup TLB for ASID.
1022 *
1023 * @param pVM Pointer to the VM.
1024 * @param pVCpu Pointer to the VMCPU.
1025 */
1026static void hmR0SvmSetupTLB(PVM pVM, PVMCPU pVCpu)
1027{
1028 PHMGLOBLCPUINFO pCpu;
1029
1030 AssertPtr(pVM);
1031 AssertPtr(pVCpu);
1032
1033 SVM_VMCB *pVMCB = (SVM_VMCB *)pVCpu->hwaccm.s.svm.pVMCB;
1034 pCpu = HWACCMR0GetCurrentCpu();
1035
1036 /*
1037 * Force a TLB flush for the first world switch if the current CPU differs from the one we ran on last.
1038 * This can happen both for start & resume due to long jumps back to ring-3.
1039 * If the TLB flush count changed, another VM (VCPU rather) has hit the ASID limit while flushing the TLB,
1040 * so we cannot reuse the ASIDs without flushing.
1041 */
1042 bool fNewASID = false;
1043 if ( pVCpu->hwaccm.s.idLastCpu != pCpu->idCpu
1044 || pVCpu->hwaccm.s.cTLBFlushes != pCpu->cTLBFlushes)
1045 {
1046 pVCpu->hwaccm.s.fForceTLBFlush = true;
1047 fNewASID = true;
1048 }
1049
1050 /*
1051 * Set TLB flush state as checked until we return from the world switch.
1052 */
1053 ASMAtomicWriteBool(&pVCpu->hwaccm.s.fCheckedTLBFlush, true);
1054
1055 /*
1056 * Check for TLB shootdown flushes.
1057 */
1058 if (VMCPU_FF_TESTANDCLEAR(pVCpu, VMCPU_FF_TLB_FLUSH))
1059 pVCpu->hwaccm.s.fForceTLBFlush = true;
1060
1061 pVCpu->hwaccm.s.idLastCpu = pCpu->idCpu;
1062 pVMCB->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_NOTHING;
1063
1064 if (RT_UNLIKELY(pVM->hwaccm.s.svm.fAlwaysFlushTLB))
1065 {
1066 /*
1067 * This is the AMD erratum 170. We need to flush the entire TLB for each world switch. Sad.
1068 */
1069 pCpu->uCurrentASID = 1;
1070 pVCpu->hwaccm.s.uCurrentASID = 1;
1071 pVCpu->hwaccm.s.cTLBFlushes = pCpu->cTLBFlushes;
1072 pVMCB->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_ENTIRE;
1073 }
1074 else if (pVCpu->hwaccm.s.fForceTLBFlush)
1075 {
1076 if (fNewASID)
1077 {
1078 ++pCpu->uCurrentASID;
1079 bool fHitASIDLimit = false;
1080 if (pCpu->uCurrentASID >= pVM->hwaccm.s.uMaxASID)
1081 {
1082 pCpu->uCurrentASID = 1; /* start at 1; host uses 0 */
1083 pCpu->cTLBFlushes++;
1084 fHitASIDLimit = true;
1085
1086 if (pVM->hwaccm.s.svm.u32Features & AMD_CPUID_SVM_FEATURE_EDX_FLUSH_BY_ASID)
1087 {
1088 pVMCB->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_SINGLE_CONTEXT;
1089 pCpu->fFlushASIDBeforeUse = true;
1090 }
1091 else
1092 {
1093 pVMCB->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_ENTIRE;
1094 pCpu->fFlushASIDBeforeUse = false;
1095 }
1096 }
1097
1098 if ( !fHitASIDLimit
1099 && pCpu->fFlushASIDBeforeUse)
1100 {
1101 if (pVM->hwaccm.s.svm.u32Features & AMD_CPUID_SVM_FEATURE_EDX_FLUSH_BY_ASID)
1102 pVMCB->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_SINGLE_CONTEXT;
1103 else
1104 {
1105 pVMCB->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_ENTIRE;
1106 pCpu->fFlushASIDBeforeUse = false;
1107 }
1108 }
1109
1110 pVCpu->hwaccm.s.uCurrentASID = pCpu->uCurrentASID;
1111 pVCpu->hwaccm.s.cTLBFlushes = pCpu->cTLBFlushes;
1112 }
1113 else
1114 {
1115 if (pVM->hwaccm.s.svm.u32Features & AMD_CPUID_SVM_FEATURE_EDX_FLUSH_BY_ASID)
1116 pVMCB->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_SINGLE_CONTEXT;
1117 else
1118 pVMCB->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_ENTIRE;
1119 }
1120
1121 pVCpu->hwaccm.s.fForceTLBFlush = false;
1122 }
1123 else
1124 {
1125 /** @todo We never set VMCPU_FF_TLB_SHOOTDOWN anywhere so this path should
1126 * not be executed. See hwaccmQueueInvlPage() where it is commented
1127 * out. Support individual entry flushing someday. */
1128 if (VMCPU_FF_ISPENDING(pVCpu, VMCPU_FF_TLB_SHOOTDOWN))
1129 {
1130 /* Deal with pending TLB shootdown actions which were queued when we were not executing code. */
1131 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatTlbShootdown);
1132 for (unsigned i = 0; i < pVCpu->hwaccm.s.TlbShootdown.cPages; i++)
1133 SVMR0InvlpgA(pVCpu->hwaccm.s.TlbShootdown.aPages[i], pVMCB->ctrl.TLBCtrl.n.u32ASID);
1134 }
1135 }
1136
1137 pVCpu->hwaccm.s.TlbShootdown.cPages = 0;
1138 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_TLB_SHOOTDOWN);
1139
1140 /* Update VMCB with the ASID. */
1141 pVMCB->ctrl.TLBCtrl.n.u32ASID = pVCpu->hwaccm.s.uCurrentASID;
1142
1143 AssertMsg(pVCpu->hwaccm.s.cTLBFlushes == pCpu->cTLBFlushes,
1144 ("Flush count mismatch for cpu %d (%x vs %x)\n", pCpu->idCpu, pVCpu->hwaccm.s.cTLBFlushes, pCpu->cTLBFlushes));
1145 AssertMsg(pCpu->uCurrentASID >= 1 && pCpu->uCurrentASID < pVM->hwaccm.s.uMaxASID,
1146 ("cpu%d uCurrentASID = %x\n", pCpu->idCpu, pCpu->uCurrentASID));
1147 AssertMsg(pVCpu->hwaccm.s.uCurrentASID >= 1 && pVCpu->hwaccm.s.uCurrentASID < pVM->hwaccm.s.uMaxASID,
1148 ("cpu%d VM uCurrentASID = %x\n", pCpu->idCpu, pVCpu->hwaccm.s.uCurrentASID));
1149
1150#ifdef VBOX_WITH_STATISTICS
1151 if (pVMCB->ctrl.TLBCtrl.n.u8TLBFlush == SVM_TLB_FLUSH_NOTHING)
1152 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatNoFlushTLBWorldSwitch);
1153 else if ( pVMCB->ctrl.TLBCtrl.n.u8TLBFlush == SVM_TLB_FLUSH_SINGLE_CONTEXT
1154 || pVMCB->ctrl.TLBCtrl.n.u8TLBFlush == SVM_TLB_FLUSH_SINGLE_CONTEXT_RETAIN_GLOBALS)
1155 {
1156 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatFlushASID);
1157 }
1158 else
1159 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatFlushTLBWorldSwitch);
1160#endif
1161}
1162
1163
1164/**
1165 * Runs guest code in an AMD-V VM.
1166 *
1167 * @returns VBox status code.
1168 * @param pVM Pointer to the VM.
1169 * @param pVCpu Pointer to the VMCPU.
1170 * @param pCtx Pointer to the guest CPU context.
1171 */
1172VMMR0DECL(int) SVMR0RunGuestCode(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
1173{
1174 STAM_PROFILE_ADV_START(&pVCpu->hwaccm.s.StatEntry, x);
1175 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hwaccm.s.StatExit1);
1176 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hwaccm.s.StatExit2);
1177
1178 VBOXSTRICTRC rc = VINF_SUCCESS;
1179 int rc2;
1180 uint64_t exitCode = (uint64_t)SVM_EXIT_INVALID;
1181 SVM_VMCB *pVMCB = NULL;
1182 bool fSyncTPR = false;
1183 unsigned cResume = 0;
1184 uint8_t u8LastTPR = 0; /* Initialized for potentially stupid compilers. */
1185 uint32_t u32HostExtFeatures = 0;
1186 PHMGLOBLCPUINFO pCpu = 0;
1187 RTCCUINTREG uOldEFlags = ~(RTCCUINTREG)0;
1188#ifdef VBOX_STRICT
1189 RTCPUID idCpuCheck;
1190#endif
1191#ifdef VBOX_HIGH_RES_TIMERS_HACK_IN_RING0
1192 uint64_t u64LastTime = RTTimeMilliTS();
1193#endif
1194
1195 pVMCB = (SVM_VMCB *)pVCpu->hwaccm.s.svm.pVMCB;
1196 AssertMsgReturn(pVMCB, ("Invalid pVMCB\n"), VERR_HMSVM_INVALID_PVMCB);
1197
1198 /*
1199 * We can jump to this point to resume execution after determining that a VM-exit is innocent.
1200 */
1201ResumeExecution:
1202 if (!STAM_PROFILE_ADV_IS_RUNNING(&pVCpu->hwaccm.s.StatEntry))
1203 STAM_PROFILE_ADV_STOP_START(&pVCpu->hwaccm.s.StatExit2, &pVCpu->hwaccm.s.StatEntry, x);
1204 Assert(!HWACCMR0SuspendPending());
1205
1206 /*
1207 * Safety precaution; looping for too long here can have a very bad effect on the host.
1208 */
1209 if (RT_UNLIKELY(++cResume > pVM->hwaccm.s.cMaxResumeLoops))
1210 {
1211 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitMaxResume);
1212 rc = VINF_EM_RAW_INTERRUPT;
1213 goto end;
1214 }
1215
1216 /*
1217 * Check for IRQ inhibition due to instruction fusing (sti, mov ss).
1218 */
1219 if (VMCPU_FF_ISSET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
1220 {
1221 Log(("VM_FF_INHIBIT_INTERRUPTS at %RGv successor %RGv\n", (RTGCPTR)pCtx->rip, EMGetInhibitInterruptsPC(pVCpu)));
1222 if (pCtx->rip != EMGetInhibitInterruptsPC(pVCpu))
1223 {
1224 /*
1225 * Note: we intentionally don't clear VM_FF_INHIBIT_INTERRUPTS here.
1226 * Before we are able to execute this instruction in raw mode (iret to guest code) an external interrupt might
1227 * force a world switch again. Possibly allowing a guest interrupt to be dispatched in the process. This could
1228 * break the guest. Sounds very unlikely, but such timing sensitive problems are not as rare as you might think.
1229 */
1230 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
1231 /* Irq inhibition is no longer active; clear the corresponding SVM state. */
1232 pVMCB->ctrl.u64IntShadow = 0;
1233 }
1234 }
1235 else
1236 {
1237 /* Irq inhibition is no longer active; clear the corresponding SVM state. */
1238 pVMCB->ctrl.u64IntShadow = 0;
1239 }
1240
1241#ifdef VBOX_HIGH_RES_TIMERS_HACK_IN_RING0
1242 if (RT_UNLIKELY((cResume & 0xf) == 0))
1243 {
1244 uint64_t u64CurTime = RTTimeMilliTS();
1245
1246 if (RT_UNLIKELY(u64CurTime > u64LastTime))
1247 {
1248 u64LastTime = u64CurTime;
1249 TMTimerPollVoid(pVM, pVCpu);
1250 }
1251 }
1252#endif
1253
1254 /*
1255 * Check for pending actions that force us to go back to ring-3.
1256 */
1257 if ( VM_FF_ISPENDING(pVM, VM_FF_HWACCM_TO_R3_MASK | VM_FF_REQUEST | VM_FF_PGM_POOL_FLUSH_PENDING | VM_FF_PDM_DMA)
1258 || VMCPU_FF_ISPENDING(pVCpu,
1259 VMCPU_FF_HWACCM_TO_R3_MASK
1260 | VMCPU_FF_PGM_SYNC_CR3
1261 | VMCPU_FF_PGM_SYNC_CR3_NON_GLOBAL
1262 | VMCPU_FF_REQUEST))
1263 {
1264 /* Check if a sync operation is pending. */
1265 if (VMCPU_FF_ISPENDING(pVCpu, VMCPU_FF_PGM_SYNC_CR3 | VMCPU_FF_PGM_SYNC_CR3_NON_GLOBAL))
1266 {
1267 rc = PGMSyncCR3(pVCpu, pCtx->cr0, pCtx->cr3, pCtx->cr4, VMCPU_FF_ISSET(pVCpu, VMCPU_FF_PGM_SYNC_CR3));
1268 AssertRC(VBOXSTRICTRC_VAL(rc));
1269 if (rc != VINF_SUCCESS)
1270 {
1271 Log(("Pending pool sync is forcing us back to ring 3; rc=%d\n", VBOXSTRICTRC_VAL(rc)));
1272 goto end;
1273 }
1274 }
1275
1276#ifdef DEBUG
1277 /* Intercept X86_XCPT_DB if stepping is enabled */
1278 if (!DBGFIsStepping(pVCpu))
1279#endif
1280 {
1281 if ( VM_FF_ISPENDING(pVM, VM_FF_HWACCM_TO_R3_MASK)
1282 || VMCPU_FF_ISPENDING(pVCpu, VMCPU_FF_HWACCM_TO_R3_MASK))
1283 {
1284 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatSwitchToR3);
1285 rc = RT_UNLIKELY(VM_FF_ISPENDING(pVM, VM_FF_PGM_NO_MEMORY)) ? VINF_EM_NO_MEMORY : VINF_EM_RAW_TO_R3;
1286 goto end;
1287 }
1288 }
1289
1290 /* Pending request packets might contain actions that need immediate attention, such as pending hardware interrupts. */
1291 if ( VM_FF_ISPENDING(pVM, VM_FF_REQUEST)
1292 || VMCPU_FF_ISPENDING(pVCpu, VMCPU_FF_REQUEST))
1293 {
1294 rc = VINF_EM_PENDING_REQUEST;
1295 goto end;
1296 }
1297
1298 /* Check if a pgm pool flush is in progress. */
1299 if (VM_FF_ISPENDING(pVM, VM_FF_PGM_POOL_FLUSH_PENDING))
1300 {
1301 rc = VINF_PGM_POOL_FLUSH_PENDING;
1302 goto end;
1303 }
1304
1305 /* Check if DMA work is pending (2nd+ run). */
1306 if (VM_FF_ISPENDING(pVM, VM_FF_PDM_DMA) && cResume > 1)
1307 {
1308 rc = VINF_EM_RAW_TO_R3;
1309 goto end;
1310 }
1311 }
1312
1313#ifdef VBOX_WITH_VMMR0_DISABLE_PREEMPTION
1314 /*
1315 * Exit to ring-3 preemption/work is pending.
1316 *
1317 * Interrupts are disabled before the call to make sure we don't miss any interrupt
1318 * that would flag preemption (IPI, timer tick, ++). (Would've been nice to do this
1319 * further down, but hmR0SvmCheckPendingInterrupt makes that impossible.)
1320 *
1321 * Note! Interrupts must be disabled done *before* we check for TLB flushes; TLB
1322 * shootdowns rely on this.
1323 */
1324 uOldEFlags = ASMIntDisableFlags();
1325 if (RTThreadPreemptIsPending(NIL_RTTHREAD))
1326 {
1327 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitPreemptPending);
1328 rc = VINF_EM_RAW_INTERRUPT;
1329 goto end;
1330 }
1331 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_EXEC);
1332#endif
1333
1334 /*
1335 * When external interrupts are pending, we should exit the VM when IF is set.
1336 * Note: *After* VM_FF_INHIBIT_INTERRUPTS check!!
1337 */
1338 rc = hmR0SvmCheckPendingInterrupt(pVM, pVCpu, pVMCB, pCtx);
1339 if (RT_FAILURE(rc))
1340 goto end;
1341
1342 /*
1343 * TPR caching using CR8 is only available in 64-bit mode or with 32-bit guests when X86_CPUID_AMD_FEATURE_ECX_CR8L is
1344 * supported.
1345 * Note: we can't do this in LoddGuestState as PDMApicGetTPR can jump back to ring 3 (lock)! (no longer true)
1346 */
1347 /** @todo query and update the TPR only when it could have been changed (mmio access)
1348 */
1349 if (pVM->hwaccm.s.fHasIoApic)
1350 {
1351 /* TPR caching in CR8 */
1352 bool fPending;
1353 rc2 = PDMApicGetTPR(pVCpu, &u8LastTPR, &fPending);
1354 AssertRC(rc2);
1355
1356 if (pVM->hwaccm.s.fTPRPatchingActive)
1357 {
1358 /* Our patch code uses LSTAR for TPR caching. */
1359 pCtx->msrLSTAR = u8LastTPR;
1360
1361 if (fPending)
1362 {
1363 /* A TPR change could activate a pending interrupt, so catch lstar writes. */
1364 hmR0SvmSetMSRPermission(pVCpu, MSR_K8_LSTAR, true, false);
1365 }
1366 else
1367 {
1368 /*
1369 * No interrupts are pending, so we don't need to be explicitely notified.
1370 * There are enough world switches for detecting pending interrupts.
1371 */
1372 hmR0SvmSetMSRPermission(pVCpu, MSR_K8_LSTAR, true, true);
1373 }
1374 }
1375 else
1376 {
1377 /* cr8 bits 3-0 correspond to bits 7-4 of the task priority mmio register. */
1378 pVMCB->ctrl.IntCtrl.n.u8VTPR = (u8LastTPR >> 4);
1379
1380 if (fPending)
1381 {
1382 /* A TPR change could activate a pending interrupt, so catch cr8 writes. */
1383 pVMCB->ctrl.u16InterceptWrCRx |= RT_BIT(8);
1384 }
1385 else
1386 {
1387 /*
1388 * No interrupts are pending, so we don't need to be explicitly notified.
1389 * There are enough world switches for detecting pending interrupts.
1390 */
1391 pVMCB->ctrl.u16InterceptWrCRx &= ~RT_BIT(8);
1392 }
1393 }
1394 fSyncTPR = !fPending;
1395 }
1396
1397 /* All done! Let's start VM execution. */
1398
1399 /* Enable nested paging if necessary (disabled each time after #VMEXIT). */
1400 pVMCB->ctrl.NestedPaging.n.u1NestedPaging = pVM->hwaccm.s.fNestedPaging;
1401
1402#ifdef LOG_ENABLED
1403 pCpu = HWACCMR0GetCurrentCpu();
1404 if (pVCpu->hwaccm.s.idLastCpu != pCpu->idCpu)
1405 LogFlow(("Force TLB flush due to rescheduling to a different cpu (%d vs %d)\n", pVCpu->hwaccm.s.idLastCpu, pCpu->idCpu));
1406 else if (pVCpu->hwaccm.s.cTLBFlushes != pCpu->cTLBFlushes)
1407 LogFlow(("Force TLB flush due to changed TLB flush count (%x vs %x)\n", pVCpu->hwaccm.s.cTLBFlushes, pCpu->cTLBFlushes));
1408 else if (VMCPU_FF_ISSET(pVCpu, VMCPU_FF_TLB_FLUSH))
1409 LogFlow(("Manual TLB flush\n"));
1410#endif
1411
1412 /*
1413 * NOTE: DO NOT DO ANYTHING AFTER THIS POINT THAT MIGHT JUMP BACK TO RING 3!
1414 * (until the actual world switch)
1415 */
1416#ifdef VBOX_STRICT
1417 idCpuCheck = RTMpCpuId();
1418#endif
1419 VMMR0LogFlushDisable(pVCpu);
1420
1421 /*
1422 * Load the guest state; *must* be here as it sets up the shadow CR0 for lazy FPU syncing!
1423 */
1424 rc = SVMR0LoadGuestState(pVM, pVCpu, pCtx);
1425 if (RT_UNLIKELY(rc != VINF_SUCCESS))
1426 {
1427 VMMR0LogFlushEnable(pVCpu);
1428 goto end;
1429 }
1430
1431#ifndef VBOX_WITH_VMMR0_DISABLE_PREEMPTION
1432 /*
1433 * Disable interrupts to make sure a poke will interrupt execution.
1434 * This must be done *before* we check for TLB flushes; TLB shootdowns rely on this.
1435 */
1436 uOldEFlags = ASMIntDisableFlags();
1437 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_EXEC);
1438#endif
1439 STAM_PROFILE_ADV_STOP_START(&pVCpu->hwaccm.s.StatEntry, &pVCpu->hwaccm.s.StatInGC, x);
1440
1441 /* Setup TLB control and ASID in the VMCB. */
1442 hmR0SvmSetupTLB(pVM, pVCpu);
1443
1444 /* In case we execute a goto ResumeExecution later on. */
1445 pVCpu->hwaccm.s.fResumeVM = true;
1446 pVCpu->hwaccm.s.fForceTLBFlush = pVM->hwaccm.s.svm.fAlwaysFlushTLB;
1447
1448 Assert(sizeof(pVCpu->hwaccm.s.svm.pVMCBPhys) == 8);
1449 Assert(pVMCB->ctrl.IntCtrl.n.u1VIrqMasking);
1450 Assert(pVMCB->ctrl.u64IOPMPhysAddr == pVM->hwaccm.s.svm.pIOBitmapPhys);
1451 Assert(pVMCB->ctrl.u64MSRPMPhysAddr == pVCpu->hwaccm.s.svm.pMSRBitmapPhys);
1452 Assert(pVMCB->ctrl.u64LBRVirt == 0);
1453
1454#ifdef VBOX_STRICT
1455 Assert(idCpuCheck == RTMpCpuId());
1456#endif
1457 TMNotifyStartOfExecution(pVCpu);
1458
1459 /*
1460 * Save the current Host TSC_AUX and write the guest TSC_AUX to the host, so that
1461 * RDTSCPs (that don't cause exits) reads the guest MSR. See @bugref{3324}.
1462 */
1463 u32HostExtFeatures = pVM->hwaccm.s.cpuid.u32AMDFeatureEDX;
1464 if ( (u32HostExtFeatures & X86_CPUID_EXT_FEATURE_EDX_RDTSCP)
1465 && !(pVMCB->ctrl.u32InterceptCtrl2 & SVM_CTRL2_INTERCEPT_RDTSCP))
1466 {
1467 pVCpu->hwaccm.s.u64HostTSCAux = ASMRdMsr(MSR_K8_TSC_AUX);
1468 uint64_t u64GuestTSCAux = 0;
1469 rc2 = CPUMQueryGuestMsr(pVCpu, MSR_K8_TSC_AUX, &u64GuestTSCAux);
1470 AssertRC(rc2);
1471 ASMWrMsr(MSR_K8_TSC_AUX, u64GuestTSCAux);
1472 }
1473
1474#ifdef VBOX_WITH_KERNEL_USING_XMM
1475 hwaccmR0SVMRunWrapXMM(pVCpu->hwaccm.s.svm.pVMCBHostPhys, pVCpu->hwaccm.s.svm.pVMCBPhys, pCtx, pVM, pVCpu,
1476 pVCpu->hwaccm.s.svm.pfnVMRun);
1477#else
1478 pVCpu->hwaccm.s.svm.pfnVMRun(pVCpu->hwaccm.s.svm.pVMCBHostPhys, pVCpu->hwaccm.s.svm.pVMCBPhys, pCtx, pVM, pVCpu);
1479#endif
1480 ASMAtomicWriteBool(&pVCpu->hwaccm.s.fCheckedTLBFlush, false);
1481 ASMAtomicIncU32(&pVCpu->hwaccm.s.cWorldSwitchExits);
1482 /* Possibly the last TSC value seen by the guest (too high) (only when we're in TSC offset mode). */
1483 if (!(pVMCB->ctrl.u32InterceptCtrl1 & SVM_CTRL1_INTERCEPT_RDTSC))
1484 {
1485 /* Restore host's TSC_AUX. */
1486 if (u32HostExtFeatures & X86_CPUID_EXT_FEATURE_EDX_RDTSCP)
1487 ASMWrMsr(MSR_K8_TSC_AUX, pVCpu->hwaccm.s.u64HostTSCAux);
1488
1489 TMCpuTickSetLastSeen(pVCpu, ASMReadTSC() +
1490 pVMCB->ctrl.u64TSCOffset - 0x400 /* guestimate of world switch overhead in clock ticks */);
1491 }
1492 TMNotifyEndOfExecution(pVCpu);
1493 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED);
1494 STAM_PROFILE_ADV_STOP_START(&pVCpu->hwaccm.s.StatInGC, &pVCpu->hwaccm.s.StatExit1, x);
1495 ASMSetFlags(uOldEFlags);
1496#ifdef VBOX_WITH_VMMR0_DISABLE_PREEMPTION
1497 uOldEFlags = ~(RTCCUINTREG)0;
1498#endif
1499
1500 /*
1501 * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
1502 * IMPORTANT: WE CAN'T DO ANY LOGGING OR OPERATIONS THAT CAN DO A LONGJMP BACK TO RING-3 *BEFORE* WE'VE SYNCED BACK (MOST OF) THE GUEST STATE
1503 * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
1504 */
1505
1506 /* Reason for the VM exit */
1507 exitCode = pVMCB->ctrl.u64ExitCode;
1508
1509 if (RT_UNLIKELY(exitCode == (uint64_t)SVM_EXIT_INVALID)) /* Invalid guest state. */
1510 {
1511 HWACCMDumpRegs(pVM, pVCpu, pCtx);
1512#ifdef DEBUG
1513 Log(("ctrl.u16InterceptRdCRx %x\n", pVMCB->ctrl.u16InterceptRdCRx));
1514 Log(("ctrl.u16InterceptWrCRx %x\n", pVMCB->ctrl.u16InterceptWrCRx));
1515 Log(("ctrl.u16InterceptRdDRx %x\n", pVMCB->ctrl.u16InterceptRdDRx));
1516 Log(("ctrl.u16InterceptWrDRx %x\n", pVMCB->ctrl.u16InterceptWrDRx));
1517 Log(("ctrl.u32InterceptException %x\n", pVMCB->ctrl.u32InterceptException));
1518 Log(("ctrl.u32InterceptCtrl1 %x\n", pVMCB->ctrl.u32InterceptCtrl1));
1519 Log(("ctrl.u32InterceptCtrl2 %x\n", pVMCB->ctrl.u32InterceptCtrl2));
1520 Log(("ctrl.u64IOPMPhysAddr %RX64\n", pVMCB->ctrl.u64IOPMPhysAddr));
1521 Log(("ctrl.u64MSRPMPhysAddr %RX64\n", pVMCB->ctrl.u64MSRPMPhysAddr));
1522 Log(("ctrl.u64TSCOffset %RX64\n", pVMCB->ctrl.u64TSCOffset));
1523
1524 Log(("ctrl.TLBCtrl.u32ASID %x\n", pVMCB->ctrl.TLBCtrl.n.u32ASID));
1525 Log(("ctrl.TLBCtrl.u8TLBFlush %x\n", pVMCB->ctrl.TLBCtrl.n.u8TLBFlush));
1526 Log(("ctrl.TLBCtrl.u24Reserved %x\n", pVMCB->ctrl.TLBCtrl.n.u24Reserved));
1527
1528 Log(("ctrl.IntCtrl.u8VTPR %x\n", pVMCB->ctrl.IntCtrl.n.u8VTPR));
1529 Log(("ctrl.IntCtrl.u1VIrqValid %x\n", pVMCB->ctrl.IntCtrl.n.u1VIrqValid));
1530 Log(("ctrl.IntCtrl.u7Reserved %x\n", pVMCB->ctrl.IntCtrl.n.u7Reserved));
1531 Log(("ctrl.IntCtrl.u4VIrqPriority %x\n", pVMCB->ctrl.IntCtrl.n.u4VIrqPriority));
1532 Log(("ctrl.IntCtrl.u1IgnoreTPR %x\n", pVMCB->ctrl.IntCtrl.n.u1IgnoreTPR));
1533 Log(("ctrl.IntCtrl.u3Reserved %x\n", pVMCB->ctrl.IntCtrl.n.u3Reserved));
1534 Log(("ctrl.IntCtrl.u1VIrqMasking %x\n", pVMCB->ctrl.IntCtrl.n.u1VIrqMasking));
1535 Log(("ctrl.IntCtrl.u7Reserved2 %x\n", pVMCB->ctrl.IntCtrl.n.u7Reserved2));
1536 Log(("ctrl.IntCtrl.u8VIrqVector %x\n", pVMCB->ctrl.IntCtrl.n.u8VIrqVector));
1537 Log(("ctrl.IntCtrl.u24Reserved %x\n", pVMCB->ctrl.IntCtrl.n.u24Reserved));
1538
1539 Log(("ctrl.u64IntShadow %RX64\n", pVMCB->ctrl.u64IntShadow));
1540 Log(("ctrl.u64ExitCode %RX64\n", pVMCB->ctrl.u64ExitCode));
1541 Log(("ctrl.u64ExitInfo1 %RX64\n", pVMCB->ctrl.u64ExitInfo1));
1542 Log(("ctrl.u64ExitInfo2 %RX64\n", pVMCB->ctrl.u64ExitInfo2));
1543 Log(("ctrl.ExitIntInfo.u8Vector %x\n", pVMCB->ctrl.ExitIntInfo.n.u8Vector));
1544 Log(("ctrl.ExitIntInfo.u3Type %x\n", pVMCB->ctrl.ExitIntInfo.n.u3Type));
1545 Log(("ctrl.ExitIntInfo.u1ErrorCodeValid %x\n", pVMCB->ctrl.ExitIntInfo.n.u1ErrorCodeValid));
1546 Log(("ctrl.ExitIntInfo.u19Reserved %x\n", pVMCB->ctrl.ExitIntInfo.n.u19Reserved));
1547 Log(("ctrl.ExitIntInfo.u1Valid %x\n", pVMCB->ctrl.ExitIntInfo.n.u1Valid));
1548 Log(("ctrl.ExitIntInfo.u32ErrorCode %x\n", pVMCB->ctrl.ExitIntInfo.n.u32ErrorCode));
1549 Log(("ctrl.NestedPaging %RX64\n", pVMCB->ctrl.NestedPaging.au64));
1550 Log(("ctrl.EventInject.u8Vector %x\n", pVMCB->ctrl.EventInject.n.u8Vector));
1551 Log(("ctrl.EventInject.u3Type %x\n", pVMCB->ctrl.EventInject.n.u3Type));
1552 Log(("ctrl.EventInject.u1ErrorCodeValid %x\n", pVMCB->ctrl.EventInject.n.u1ErrorCodeValid));
1553 Log(("ctrl.EventInject.u19Reserved %x\n", pVMCB->ctrl.EventInject.n.u19Reserved));
1554 Log(("ctrl.EventInject.u1Valid %x\n", pVMCB->ctrl.EventInject.n.u1Valid));
1555 Log(("ctrl.EventInject.u32ErrorCode %x\n", pVMCB->ctrl.EventInject.n.u32ErrorCode));
1556
1557 Log(("ctrl.u64NestedPagingCR3 %RX64\n", pVMCB->ctrl.u64NestedPagingCR3));
1558 Log(("ctrl.u64LBRVirt %RX64\n", pVMCB->ctrl.u64LBRVirt));
1559
1560 Log(("guest.CS.u16Sel %04X\n", pVMCB->guest.CS.u16Sel));
1561 Log(("guest.CS.u16Attr %04X\n", pVMCB->guest.CS.u16Attr));
1562 Log(("guest.CS.u32Limit %X\n", pVMCB->guest.CS.u32Limit));
1563 Log(("guest.CS.u64Base %RX64\n", pVMCB->guest.CS.u64Base));
1564 Log(("guest.DS.u16Sel %04X\n", pVMCB->guest.DS.u16Sel));
1565 Log(("guest.DS.u16Attr %04X\n", pVMCB->guest.DS.u16Attr));
1566 Log(("guest.DS.u32Limit %X\n", pVMCB->guest.DS.u32Limit));
1567 Log(("guest.DS.u64Base %RX64\n", pVMCB->guest.DS.u64Base));
1568 Log(("guest.ES.u16Sel %04X\n", pVMCB->guest.ES.u16Sel));
1569 Log(("guest.ES.u16Attr %04X\n", pVMCB->guest.ES.u16Attr));
1570 Log(("guest.ES.u32Limit %X\n", pVMCB->guest.ES.u32Limit));
1571 Log(("guest.ES.u64Base %RX64\n", pVMCB->guest.ES.u64Base));
1572 Log(("guest.FS.u16Sel %04X\n", pVMCB->guest.FS.u16Sel));
1573 Log(("guest.FS.u16Attr %04X\n", pVMCB->guest.FS.u16Attr));
1574 Log(("guest.FS.u32Limit %X\n", pVMCB->guest.FS.u32Limit));
1575 Log(("guest.FS.u64Base %RX64\n", pVMCB->guest.FS.u64Base));
1576 Log(("guest.GS.u16Sel %04X\n", pVMCB->guest.GS.u16Sel));
1577 Log(("guest.GS.u16Attr %04X\n", pVMCB->guest.GS.u16Attr));
1578 Log(("guest.GS.u32Limit %X\n", pVMCB->guest.GS.u32Limit));
1579 Log(("guest.GS.u64Base %RX64\n", pVMCB->guest.GS.u64Base));
1580
1581 Log(("guest.GDTR.u32Limit %X\n", pVMCB->guest.GDTR.u32Limit));
1582 Log(("guest.GDTR.u64Base %RX64\n", pVMCB->guest.GDTR.u64Base));
1583
1584 Log(("guest.LDTR.u16Sel %04X\n", pVMCB->guest.LDTR.u16Sel));
1585 Log(("guest.LDTR.u16Attr %04X\n", pVMCB->guest.LDTR.u16Attr));
1586 Log(("guest.LDTR.u32Limit %X\n", pVMCB->guest.LDTR.u32Limit));
1587 Log(("guest.LDTR.u64Base %RX64\n", pVMCB->guest.LDTR.u64Base));
1588
1589 Log(("guest.IDTR.u32Limit %X\n", pVMCB->guest.IDTR.u32Limit));
1590 Log(("guest.IDTR.u64Base %RX64\n", pVMCB->guest.IDTR.u64Base));
1591
1592 Log(("guest.TR.u16Sel %04X\n", pVMCB->guest.TR.u16Sel));
1593 Log(("guest.TR.u16Attr %04X\n", pVMCB->guest.TR.u16Attr));
1594 Log(("guest.TR.u32Limit %X\n", pVMCB->guest.TR.u32Limit));
1595 Log(("guest.TR.u64Base %RX64\n", pVMCB->guest.TR.u64Base));
1596
1597 Log(("guest.u8CPL %X\n", pVMCB->guest.u8CPL));
1598 Log(("guest.u64CR0 %RX64\n", pVMCB->guest.u64CR0));
1599 Log(("guest.u64CR2 %RX64\n", pVMCB->guest.u64CR2));
1600 Log(("guest.u64CR3 %RX64\n", pVMCB->guest.u64CR3));
1601 Log(("guest.u64CR4 %RX64\n", pVMCB->guest.u64CR4));
1602 Log(("guest.u64DR6 %RX64\n", pVMCB->guest.u64DR6));
1603 Log(("guest.u64DR7 %RX64\n", pVMCB->guest.u64DR7));
1604
1605 Log(("guest.u64RIP %RX64\n", pVMCB->guest.u64RIP));
1606 Log(("guest.u64RSP %RX64\n", pVMCB->guest.u64RSP));
1607 Log(("guest.u64RAX %RX64\n", pVMCB->guest.u64RAX));
1608 Log(("guest.u64RFlags %RX64\n", pVMCB->guest.u64RFlags));
1609
1610 Log(("guest.u64SysEnterCS %RX64\n", pVMCB->guest.u64SysEnterCS));
1611 Log(("guest.u64SysEnterEIP %RX64\n", pVMCB->guest.u64SysEnterEIP));
1612 Log(("guest.u64SysEnterESP %RX64\n", pVMCB->guest.u64SysEnterESP));
1613
1614 Log(("guest.u64EFER %RX64\n", pVMCB->guest.u64EFER));
1615 Log(("guest.u64STAR %RX64\n", pVMCB->guest.u64STAR));
1616 Log(("guest.u64LSTAR %RX64\n", pVMCB->guest.u64LSTAR));
1617 Log(("guest.u64CSTAR %RX64\n", pVMCB->guest.u64CSTAR));
1618 Log(("guest.u64SFMASK %RX64\n", pVMCB->guest.u64SFMASK));
1619 Log(("guest.u64KernelGSBase %RX64\n", pVMCB->guest.u64KernelGSBase));
1620 Log(("guest.u64GPAT %RX64\n", pVMCB->guest.u64GPAT));
1621 Log(("guest.u64DBGCTL %RX64\n", pVMCB->guest.u64DBGCTL));
1622 Log(("guest.u64BR_FROM %RX64\n", pVMCB->guest.u64BR_FROM));
1623 Log(("guest.u64BR_TO %RX64\n", pVMCB->guest.u64BR_TO));
1624 Log(("guest.u64LASTEXCPFROM %RX64\n", pVMCB->guest.u64LASTEXCPFROM));
1625 Log(("guest.u64LASTEXCPTO %RX64\n", pVMCB->guest.u64LASTEXCPTO));
1626#endif
1627 rc = VERR_SVM_UNABLE_TO_START_VM;
1628 VMMR0LogFlushEnable(pVCpu);
1629 goto end;
1630 }
1631
1632 /* Let's first sync back EIP, ESP, and EFLAGS. */
1633 pCtx->rip = pVMCB->guest.u64RIP;
1634 pCtx->rsp = pVMCB->guest.u64RSP;
1635 pCtx->eflags.u32 = pVMCB->guest.u64RFlags;
1636 /* eax is saved/restore across the vmrun instruction */
1637 pCtx->rax = pVMCB->guest.u64RAX;
1638
1639 /*
1640 * Save all the MSRs that can be changed by the guest without causing a world switch.
1641 * FS & GS base are saved with SVM_READ_SELREG.
1642 */
1643 pCtx->msrSTAR = pVMCB->guest.u64STAR; /* legacy syscall eip, cs & ss */
1644 pCtx->msrLSTAR = pVMCB->guest.u64LSTAR; /* 64-bit mode syscall rip */
1645 pCtx->msrCSTAR = pVMCB->guest.u64CSTAR; /* compatibility mode syscall rip */
1646 pCtx->msrSFMASK = pVMCB->guest.u64SFMASK; /* syscall flag mask */
1647 pCtx->msrKERNELGSBASE = pVMCB->guest.u64KernelGSBase; /* swapgs exchange value */
1648 pCtx->SysEnter.cs = pVMCB->guest.u64SysEnterCS;
1649 pCtx->SysEnter.eip = pVMCB->guest.u64SysEnterEIP;
1650 pCtx->SysEnter.esp = pVMCB->guest.u64SysEnterESP;
1651
1652 /* Can be updated behind our back in the nested paging case. */
1653 pCtx->cr2 = pVMCB->guest.u64CR2;
1654
1655 /* Guest CPU context: ES, CS, SS, DS, FS, GS. */
1656 SVM_READ_SELREG(SS, ss);
1657 SVM_READ_SELREG(CS, cs);
1658 SVM_READ_SELREG(DS, ds);
1659 SVM_READ_SELREG(ES, es);
1660 SVM_READ_SELREG(FS, fs);
1661 SVM_READ_SELREG(GS, gs);
1662
1663 /*
1664 * Correct the hidden CS granularity flag. Haven't seen it being wrong in any other
1665 * register (yet).
1666 */
1667 if ( !pCtx->cs.Attr.n.u1Granularity
1668 && pCtx->cs.Attr.n.u1Present
1669 && pCtx->cs.u32Limit > UINT32_C(0xfffff))
1670 {
1671 Assert((pCtx->cs.u32Limit & 0xfff) == 0xfff);
1672 pCtx->cs.Attr.n.u1Granularity = 1;
1673 }
1674#define SVM_ASSERT_SEL_GRANULARITY(reg) \
1675 AssertMsg( !pCtx->reg.Attr.n.u1Present \
1676 || ( pCtx->reg.Attr.n.u1Granularity \
1677 ? (pCtx->reg.u32Limit & 0xfff) == 0xfff \
1678 : pCtx->reg.u32Limit <= 0xfffff), \
1679 ("%#x %#x %#llx\n", pCtx->reg.u32Limit, pCtx->reg.Attr.u, pCtx->reg.u64Base))
1680 SVM_ASSERT_SEL_GRANULARITY(ss);
1681 SVM_ASSERT_SEL_GRANULARITY(cs);
1682 SVM_ASSERT_SEL_GRANULARITY(ds);
1683 SVM_ASSERT_SEL_GRANULARITY(es);
1684 SVM_ASSERT_SEL_GRANULARITY(fs);
1685 SVM_ASSERT_SEL_GRANULARITY(gs);
1686#undef SVM_ASSERT_SEL_GRANULARITY
1687
1688 /*
1689 * Correct the hidden SS DPL field. It can be wrong on certain CPUs
1690 * sometimes (seen it on AMD Fusion CPUs with 64-bit guests). The CPU
1691 * always uses the CPL field in the VMCB instead of the DPL in the hidden
1692 * SS (chapter AMD spec. 15.5.1 Basic operation).
1693 */
1694 Assert(!(pVMCB->guest.u8CPL & ~0x3));
1695 pCtx->ss.Attr.n.u2Dpl = pVMCB->guest.u8CPL & 0x3;
1696
1697 /*
1698 * Remaining guest CPU context: TR, IDTR, GDTR, LDTR;
1699 * must sync everything otherwise we can get out of sync when jumping back to ring-3.
1700 */
1701 SVM_READ_SELREG(LDTR, ldtr);
1702 SVM_READ_SELREG(TR, tr);
1703
1704 pCtx->gdtr.cbGdt = pVMCB->guest.GDTR.u32Limit;
1705 pCtx->gdtr.pGdt = pVMCB->guest.GDTR.u64Base;
1706
1707 pCtx->idtr.cbIdt = pVMCB->guest.IDTR.u32Limit;
1708 pCtx->idtr.pIdt = pVMCB->guest.IDTR.u64Base;
1709
1710 /*
1711 * No reason to sync back the CRx and DRx registers as they cannot be changed by the guest
1712 * unless in the nested paging case where CR3 can be changed by the guest.
1713 */
1714 if ( pVM->hwaccm.s.fNestedPaging
1715 && pCtx->cr3 != pVMCB->guest.u64CR3)
1716 {
1717 CPUMSetGuestCR3(pVCpu, pVMCB->guest.u64CR3);
1718 PGMUpdateCR3(pVCpu, pVMCB->guest.u64CR3);
1719 }
1720
1721 /* Note! NOW IT'S SAFE FOR LOGGING! */
1722 VMMR0LogFlushEnable(pVCpu);
1723
1724 /* Take care of instruction fusing (sti, mov ss) (see AMD spec. 15.20.5 Interrupt Shadows) */
1725 if (pVMCB->ctrl.u64IntShadow & SVM_INTERRUPT_SHADOW_ACTIVE)
1726 {
1727 Log(("uInterruptState %x rip=%RGv\n", pVMCB->ctrl.u64IntShadow, (RTGCPTR)pCtx->rip));
1728 EMSetInhibitInterruptsPC(pVCpu, pCtx->rip);
1729 }
1730 else
1731 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
1732
1733 Log2(("exitCode = %x\n", exitCode));
1734
1735 /* Sync back DR6 as it could have been changed by hitting breakpoints. */
1736 pCtx->dr[6] = pVMCB->guest.u64DR6;
1737 /* DR7.GD can be cleared by debug exceptions, so sync it back as well. */
1738 pCtx->dr[7] = pVMCB->guest.u64DR7;
1739
1740 /* Check if an injected event was interrupted prematurely. */
1741 pVCpu->hwaccm.s.Event.intInfo = pVMCB->ctrl.ExitIntInfo.au64[0];
1742 if ( pVMCB->ctrl.ExitIntInfo.n.u1Valid
1743 /* we don't care about 'int xx' as the instruction will be restarted. */
1744 && pVMCB->ctrl.ExitIntInfo.n.u3Type != SVM_EVENT_SOFTWARE_INT)
1745 {
1746 Log(("Pending inject %RX64 at %RGv exit=%08x\n", pVCpu->hwaccm.s.Event.intInfo, (RTGCPTR)pCtx->rip, exitCode));
1747
1748#ifdef LOG_ENABLED
1749 SVM_EVENT Event;
1750 Event.au64[0] = pVCpu->hwaccm.s.Event.intInfo;
1751
1752 if ( exitCode == SVM_EXIT_EXCEPTION_E
1753 && Event.n.u8Vector == 0xE)
1754 {
1755 Log(("Double fault!\n"));
1756 }
1757#endif
1758
1759 pVCpu->hwaccm.s.Event.fPending = true;
1760 /* Error code present? (redundant) */
1761 if (pVMCB->ctrl.ExitIntInfo.n.u1ErrorCodeValid)
1762 pVCpu->hwaccm.s.Event.errCode = pVMCB->ctrl.ExitIntInfo.n.u32ErrorCode;
1763 else
1764 pVCpu->hwaccm.s.Event.errCode = 0;
1765 }
1766#ifdef VBOX_WITH_STATISTICS
1767 if (exitCode == SVM_EXIT_NPF)
1768 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitReasonNPF);
1769 else
1770 STAM_COUNTER_INC(&pVCpu->hwaccm.s.paStatExitReasonR0[exitCode & MASK_EXITREASON_STAT]);
1771#endif
1772
1773 /* Sync back the TPR if it was changed. */
1774 if (fSyncTPR)
1775 {
1776 if (pVM->hwaccm.s.fTPRPatchingActive)
1777 {
1778 if ((pCtx->msrLSTAR & 0xff) != u8LastTPR)
1779 {
1780 /* Our patch code uses LSTAR for TPR caching. */
1781 rc2 = PDMApicSetTPR(pVCpu, pCtx->msrLSTAR & 0xff);
1782 AssertRC(rc2);
1783 }
1784 }
1785 else
1786 {
1787 if ((uint8_t)(u8LastTPR >> 4) != pVMCB->ctrl.IntCtrl.n.u8VTPR)
1788 {
1789 /* cr8 bits 3-0 correspond to bits 7-4 of the task priority mmio register. */
1790 rc2 = PDMApicSetTPR(pVCpu, pVMCB->ctrl.IntCtrl.n.u8VTPR << 4);
1791 AssertRC(rc2);
1792 }
1793 }
1794 }
1795
1796#ifdef DBGFTRACE_ENABLED /** @todo DTrace */
1797 RTTraceBufAddMsgF(pVM->CTX_SUFF(hTraceBuf), "vmexit %08x at %04:%08RX64 %RX64 %RX64 %RX64",
1798 exitCode, pCtx->cs.Sel, pCtx->rip,
1799 pVMCB->ctrl.u64ExitInfo1, pVMCB->ctrl.u64ExitInfo2, pVMCB->ctrl.ExitIntInfo.au64[0]);
1800#endif
1801#if ARCH_BITS == 64 /* for the time being */
1802 VBOXVMM_R0_HMSVM_VMEXIT(pVCpu, pCtx, exitCode, pVMCB->ctrl.u64ExitInfo1, pVMCB->ctrl.u64ExitInfo2,
1803 pVMCB->ctrl.ExitIntInfo.au64[0], UINT64_MAX);
1804#endif
1805 STAM_PROFILE_ADV_STOP_START(&pVCpu->hwaccm.s.StatExit1, &pVCpu->hwaccm.s.StatExit2, x);
1806
1807 /* Deal with the reason of the VM-exit. */
1808 switch (exitCode)
1809 {
1810 case SVM_EXIT_EXCEPTION_0: case SVM_EXIT_EXCEPTION_1: case SVM_EXIT_EXCEPTION_2: case SVM_EXIT_EXCEPTION_3:
1811 case SVM_EXIT_EXCEPTION_4: case SVM_EXIT_EXCEPTION_5: case SVM_EXIT_EXCEPTION_6: case SVM_EXIT_EXCEPTION_7:
1812 case SVM_EXIT_EXCEPTION_8: case SVM_EXIT_EXCEPTION_9: case SVM_EXIT_EXCEPTION_A: case SVM_EXIT_EXCEPTION_B:
1813 case SVM_EXIT_EXCEPTION_C: case SVM_EXIT_EXCEPTION_D: case SVM_EXIT_EXCEPTION_E: case SVM_EXIT_EXCEPTION_F:
1814 case SVM_EXIT_EXCEPTION_10: case SVM_EXIT_EXCEPTION_11: case SVM_EXIT_EXCEPTION_12: case SVM_EXIT_EXCEPTION_13:
1815 case SVM_EXIT_EXCEPTION_14: case SVM_EXIT_EXCEPTION_15: case SVM_EXIT_EXCEPTION_16: case SVM_EXIT_EXCEPTION_17:
1816 case SVM_EXIT_EXCEPTION_18: case SVM_EXIT_EXCEPTION_19: case SVM_EXIT_EXCEPTION_1A: case SVM_EXIT_EXCEPTION_1B:
1817 case SVM_EXIT_EXCEPTION_1C: case SVM_EXIT_EXCEPTION_1D: case SVM_EXIT_EXCEPTION_1E: case SVM_EXIT_EXCEPTION_1F:
1818 {
1819 /* Pending trap. */
1820 SVM_EVENT Event;
1821 uint32_t vector = exitCode - SVM_EXIT_EXCEPTION_0;
1822
1823 Log2(("Hardware/software interrupt %d\n", vector));
1824 switch (vector)
1825 {
1826 case X86_XCPT_DB:
1827 {
1828 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitGuestDB);
1829
1830 /* Note that we don't support guest and host-initiated debugging at the same time. */
1831 Assert(DBGFIsStepping(pVCpu) || CPUMIsHyperDebugStateActive(pVCpu));
1832
1833 rc = DBGFRZTrap01Handler(pVM, pVCpu, CPUMCTX2CORE(pCtx), pCtx->dr[6]);
1834 if (rc == VINF_EM_RAW_GUEST_TRAP)
1835 {
1836 Log(("Trap %x (debug) at %016RX64\n", vector, pCtx->rip));
1837
1838 /* Reinject the exception. */
1839 Event.au64[0] = 0;
1840 Event.n.u3Type = SVM_EVENT_EXCEPTION; /* trap or fault */
1841 Event.n.u1Valid = 1;
1842 Event.n.u8Vector = X86_XCPT_DB;
1843
1844 hmR0SvmInjectEvent(pVCpu, pVMCB, pCtx, &Event);
1845 goto ResumeExecution;
1846 }
1847 /* Return to ring 3 to deal with the debug exit code. */
1848 Log(("Debugger hardware BP at %04x:%RGv (rc=%Rrc)\n", pCtx->cs.Sel, pCtx->rip, VBOXSTRICTRC_VAL(rc)));
1849 break;
1850 }
1851
1852 case X86_XCPT_NM:
1853 {
1854 Log(("#NM fault at %RGv\n", (RTGCPTR)pCtx->rip));
1855
1856 /** @todo don't intercept #NM exceptions anymore when we've activated the guest FPU state. */
1857 /* If we sync the FPU/XMM state on-demand, then we can continue execution as if nothing has happened. */
1858 rc = CPUMR0LoadGuestFPU(pVM, pVCpu, pCtx);
1859 if (rc == VINF_SUCCESS)
1860 {
1861 Assert(CPUMIsGuestFPUStateActive(pVCpu));
1862 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitShadowNM);
1863
1864 /* Continue execution. */
1865 pVCpu->hwaccm.s.fContextUseFlags |= HWACCM_CHANGED_GUEST_CR0;
1866
1867 goto ResumeExecution;
1868 }
1869
1870 Log(("Forward #NM fault to the guest\n"));
1871 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitGuestNM);
1872
1873 Event.au64[0] = 0;
1874 Event.n.u3Type = SVM_EVENT_EXCEPTION;
1875 Event.n.u1Valid = 1;
1876 Event.n.u8Vector = X86_XCPT_NM;
1877
1878 hmR0SvmInjectEvent(pVCpu, pVMCB, pCtx, &Event);
1879 goto ResumeExecution;
1880 }
1881
1882 case X86_XCPT_PF: /* Page fault */
1883 {
1884 uint32_t errCode = pVMCB->ctrl.u64ExitInfo1; /* EXITINFO1 = error code */
1885 RTGCUINTPTR uFaultAddress = pVMCB->ctrl.u64ExitInfo2; /* EXITINFO2 = fault address */
1886
1887#ifdef VBOX_ALWAYS_TRAP_PF
1888 if (pVM->hwaccm.s.fNestedPaging)
1889 {
1890 /*
1891 * A genuine pagefault. Forward the trap to the guest by injecting the exception and resuming execution.
1892 */
1893 Log(("Guest page fault at %04X:%RGv cr2=%RGv error code %x rsp=%RGv\n", pCtx->cs, (RTGCPTR)pCtx->rip,
1894 uFaultAddress, errCode, (RTGCPTR)pCtx->rsp));
1895 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitGuestPF);
1896
1897 /* Now we must update CR2. */
1898 pCtx->cr2 = uFaultAddress;
1899
1900 Event.au64[0] = 0;
1901 Event.n.u3Type = SVM_EVENT_EXCEPTION;
1902 Event.n.u1Valid = 1;
1903 Event.n.u8Vector = X86_XCPT_PF;
1904 Event.n.u1ErrorCodeValid = 1;
1905 Event.n.u32ErrorCode = errCode;
1906
1907 hmR0SvmInjectEvent(pVCpu, pVMCB, pCtx, &Event);
1908 goto ResumeExecution;
1909 }
1910#endif
1911 Assert(!pVM->hwaccm.s.fNestedPaging);
1912
1913#ifdef VBOX_HWACCM_WITH_GUEST_PATCHING
1914 /* Shortcut for APIC TPR reads and writes; 32 bits guests only */
1915 if ( pVM->hwaccm.s.fTRPPatchingAllowed
1916 && (uFaultAddress & 0xfff) == 0x080
1917 && !(errCode & X86_TRAP_PF_P) /* not present */
1918 && CPUMGetGuestCPL(pVCpu) == 0
1919 && !CPUMIsGuestInLongModeEx(pCtx)
1920 && pVM->hwaccm.s.cPatches < RT_ELEMENTS(pVM->hwaccm.s.aPatches))
1921 {
1922 RTGCPHYS GCPhysApicBase, GCPhys;
1923 PDMApicGetBase(pVM, &GCPhysApicBase); /** @todo cache this */
1924 GCPhysApicBase &= PAGE_BASE_GC_MASK;
1925
1926 rc = PGMGstGetPage(pVCpu, (RTGCPTR)uFaultAddress, NULL, &GCPhys);
1927 if ( rc == VINF_SUCCESS
1928 && GCPhys == GCPhysApicBase)
1929 {
1930 /* Only attempt to patch the instruction once. */
1931 PHWACCMTPRPATCH pPatch = (PHWACCMTPRPATCH)RTAvloU32Get(&pVM->hwaccm.s.PatchTree, (AVLOU32KEY)pCtx->eip);
1932 if (!pPatch)
1933 {
1934 rc = VINF_EM_HWACCM_PATCH_TPR_INSTR;
1935 break;
1936 }
1937 }
1938 }
1939#endif
1940
1941 Log2(("Page fault at %RGv cr2=%RGv error code %x\n", (RTGCPTR)pCtx->rip, uFaultAddress, errCode));
1942 /* Exit qualification contains the linear address of the page fault. */
1943 TRPMAssertTrap(pVCpu, X86_XCPT_PF, TRPM_TRAP);
1944 TRPMSetErrorCode(pVCpu, errCode);
1945 TRPMSetFaultAddress(pVCpu, uFaultAddress);
1946
1947 /* Forward it to our trap handler first, in case our shadow pages are out of sync. */
1948 rc = PGMTrap0eHandler(pVCpu, errCode, CPUMCTX2CORE(pCtx), (RTGCPTR)uFaultAddress);
1949 Log2(("PGMTrap0eHandler %RGv returned %Rrc\n", (RTGCPTR)pCtx->rip, VBOXSTRICTRC_VAL(rc)));
1950 if (rc == VINF_SUCCESS)
1951 {
1952 /* We've successfully synced our shadow pages, so let's just continue execution. */
1953 Log2(("Shadow page fault at %RGv cr2=%RGv error code %x\n", (RTGCPTR)pCtx->rip, uFaultAddress, errCode));
1954 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitShadowPF);
1955
1956 TRPMResetTrap(pVCpu);
1957 goto ResumeExecution;
1958 }
1959 else if (rc == VINF_EM_RAW_GUEST_TRAP)
1960 {
1961 /*
1962 * A genuine pagefault. Forward the trap to the guest by injecting the exception and resuming execution.
1963 */
1964 Log2(("Forward page fault to the guest\n"));
1965 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitGuestPF);
1966 /* The error code might have been changed. */
1967 errCode = TRPMGetErrorCode(pVCpu);
1968
1969 TRPMResetTrap(pVCpu);
1970
1971 /* Now we must update CR2. */
1972 pCtx->cr2 = uFaultAddress;
1973
1974 Event.au64[0] = 0;
1975 Event.n.u3Type = SVM_EVENT_EXCEPTION;
1976 Event.n.u1Valid = 1;
1977 Event.n.u8Vector = X86_XCPT_PF;
1978 Event.n.u1ErrorCodeValid = 1;
1979 Event.n.u32ErrorCode = errCode;
1980
1981 hmR0SvmInjectEvent(pVCpu, pVMCB, pCtx, &Event);
1982 goto ResumeExecution;
1983 }
1984#ifdef VBOX_STRICT
1985 if (rc != VINF_EM_RAW_EMULATE_INSTR && rc != VINF_EM_RAW_EMULATE_IO_BLOCK)
1986 LogFlow(("PGMTrap0eHandler failed with %d\n", VBOXSTRICTRC_VAL(rc)));
1987#endif
1988 /* Need to go back to the recompiler to emulate the instruction. */
1989 TRPMResetTrap(pVCpu);
1990 break;
1991 }
1992
1993 case X86_XCPT_MF: /* Floating point exception. */
1994 {
1995 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitGuestMF);
1996 if (!(pCtx->cr0 & X86_CR0_NE))
1997 {
1998 /* old style FPU error reporting needs some extra work. */
1999 /** @todo don't fall back to the recompiler, but do it manually. */
2000 rc = VINF_EM_RAW_EMULATE_INSTR;
2001 break;
2002 }
2003 Log(("Trap %x at %RGv\n", vector, (RTGCPTR)pCtx->rip));
2004
2005 Event.au64[0] = 0;
2006 Event.n.u3Type = SVM_EVENT_EXCEPTION;
2007 Event.n.u1Valid = 1;
2008 Event.n.u8Vector = X86_XCPT_MF;
2009
2010 hmR0SvmInjectEvent(pVCpu, pVMCB, pCtx, &Event);
2011 goto ResumeExecution;
2012 }
2013
2014#ifdef VBOX_STRICT
2015 case X86_XCPT_BP: /* Breakpoint. */
2016 case X86_XCPT_GP: /* General protection failure exception.*/
2017 case X86_XCPT_UD: /* Unknown opcode exception. */
2018 case X86_XCPT_DE: /* Divide error. */
2019 case X86_XCPT_SS: /* Stack segment exception. */
2020 case X86_XCPT_NP: /* Segment not present exception. */
2021 {
2022 Event.au64[0] = 0;
2023 Event.n.u3Type = SVM_EVENT_EXCEPTION;
2024 Event.n.u1Valid = 1;
2025 Event.n.u8Vector = vector;
2026
2027 switch (vector)
2028 {
2029 case X86_XCPT_GP:
2030 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitGuestGP);
2031 Event.n.u1ErrorCodeValid = 1;
2032 Event.n.u32ErrorCode = pVMCB->ctrl.u64ExitInfo1; /* EXITINFO1 = error code */
2033 break;
2034 case X86_XCPT_BP:
2035 /** Saves the wrong EIP on the stack (pointing to the int3 instead of the next instruction. */
2036 break;
2037 case X86_XCPT_DE:
2038 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitGuestDE);
2039 break;
2040 case X86_XCPT_UD:
2041 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitGuestUD);
2042 break;
2043 case X86_XCPT_SS:
2044 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitGuestSS);
2045 Event.n.u1ErrorCodeValid = 1;
2046 Event.n.u32ErrorCode = pVMCB->ctrl.u64ExitInfo1; /* EXITINFO1 = error code */
2047 break;
2048 case X86_XCPT_NP:
2049 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitGuestNP);
2050 Event.n.u1ErrorCodeValid = 1;
2051 Event.n.u32ErrorCode = pVMCB->ctrl.u64ExitInfo1; /* EXITINFO1 = error code */
2052 break;
2053 }
2054 Log(("Trap %x at %04x:%RGv esi=%x\n", vector, pCtx->cs.Sel, (RTGCPTR)pCtx->rip, pCtx->esi));
2055 hmR0SvmInjectEvent(pVCpu, pVMCB, pCtx, &Event);
2056 goto ResumeExecution;
2057 }
2058#endif
2059 default:
2060 AssertMsgFailed(("Unexpected vm-exit caused by exception %x\n", vector));
2061 rc = VERR_HMSVM_UNEXPECTED_XCPT_EXIT;
2062 break;
2063
2064 } /* switch (vector) */
2065 break;
2066 }
2067
2068 case SVM_EXIT_NPF:
2069 {
2070 /* EXITINFO1 contains fault errorcode; EXITINFO2 contains the guest physical address causing the fault. */
2071 uint32_t errCode = pVMCB->ctrl.u64ExitInfo1; /* EXITINFO1 = error code */
2072 RTGCPHYS GCPhysFault = pVMCB->ctrl.u64ExitInfo2; /* EXITINFO2 = fault address */
2073 PGMMODE enmShwPagingMode;
2074
2075 Assert(pVM->hwaccm.s.fNestedPaging);
2076 LogFlow(("Nested page fault at %RGv cr2=%RGp error code %x\n", (RTGCPTR)pCtx->rip, GCPhysFault, errCode));
2077
2078#ifdef VBOX_HWACCM_WITH_GUEST_PATCHING
2079 /* Shortcut for APIC TPR reads and writes; 32 bits guests only */
2080 if ( pVM->hwaccm.s.fTRPPatchingAllowed
2081 && (GCPhysFault & PAGE_OFFSET_MASK) == 0x080
2082 && ( !(errCode & X86_TRAP_PF_P) /* not present */
2083 || (errCode & (X86_TRAP_PF_P | X86_TRAP_PF_RSVD)) == (X86_TRAP_PF_P | X86_TRAP_PF_RSVD) /* mmio optimization */)
2084 && CPUMGetGuestCPL(pVCpu) == 0
2085 && !CPUMIsGuestInLongModeEx(pCtx)
2086 && pVM->hwaccm.s.cPatches < RT_ELEMENTS(pVM->hwaccm.s.aPatches))
2087 {
2088 RTGCPHYS GCPhysApicBase;
2089 PDMApicGetBase(pVM, &GCPhysApicBase); /** @todo cache this */
2090 GCPhysApicBase &= PAGE_BASE_GC_MASK;
2091
2092 if (GCPhysFault == GCPhysApicBase + 0x80)
2093 {
2094 /* Only attempt to patch the instruction once. */
2095 PHWACCMTPRPATCH pPatch = (PHWACCMTPRPATCH)RTAvloU32Get(&pVM->hwaccm.s.PatchTree, (AVLOU32KEY)pCtx->eip);
2096 if (!pPatch)
2097 {
2098 rc = VINF_EM_HWACCM_PATCH_TPR_INSTR;
2099 break;
2100 }
2101 }
2102 }
2103#endif
2104
2105 /* Handle the pagefault trap for the nested shadow table. */
2106#if HC_ARCH_BITS == 32 /** @todo shadow this in a variable. */
2107 if (CPUMIsGuestInLongModeEx(pCtx))
2108 enmShwPagingMode = PGMMODE_AMD64_NX;
2109 else
2110#endif
2111 enmShwPagingMode = PGMGetHostMode(pVM);
2112
2113 /* MMIO optimization */
2114 Assert((errCode & (X86_TRAP_PF_RSVD | X86_TRAP_PF_P)) != X86_TRAP_PF_RSVD);
2115 if ((errCode & (X86_TRAP_PF_RSVD | X86_TRAP_PF_P)) == (X86_TRAP_PF_RSVD | X86_TRAP_PF_P))
2116 {
2117 rc = PGMR0Trap0eHandlerNPMisconfig(pVM, pVCpu, enmShwPagingMode, CPUMCTX2CORE(pCtx), GCPhysFault, errCode);
2118
2119 /*
2120 * If we succeed, resume execution.
2121 * Or, if fail in interpreting the instruction because we couldn't get the guest physical address
2122 * of the page containing the instruction via the guest's page tables (we would invalidate the guest page
2123 * in the host TLB), resume execution which would cause a guest page fault to let the guest handle this
2124 * weird case. See @bugref{6043}.
2125 */
2126 if ( rc == VINF_SUCCESS
2127 || rc == VERR_PAGE_TABLE_NOT_PRESENT
2128 || rc == VERR_PAGE_NOT_PRESENT)
2129 {
2130 Log2(("PGMR0Trap0eHandlerNPMisconfig(,,,%RGp) at %RGv -> resume\n", GCPhysFault, (RTGCPTR)pCtx->rip));
2131 goto ResumeExecution;
2132 }
2133 Log2(("PGMR0Trap0eHandlerNPMisconfig(,,,%RGp) at %RGv -> resume\n", GCPhysFault, (RTGCPTR)pCtx->rip));
2134 break;
2135 }
2136
2137 /* Exit qualification contains the linear address of the page fault. */
2138 TRPMAssertTrap(pVCpu, X86_XCPT_PF, TRPM_TRAP);
2139 TRPMSetErrorCode(pVCpu, errCode);
2140 TRPMSetFaultAddress(pVCpu, GCPhysFault);
2141
2142 rc = PGMR0Trap0eHandlerNestedPaging(pVM, pVCpu, enmShwPagingMode, errCode, CPUMCTX2CORE(pCtx), GCPhysFault);
2143 Log2(("PGMR0Trap0eHandlerNestedPaging %RGv returned %Rrc\n", (RTGCPTR)pCtx->rip, VBOXSTRICTRC_VAL(rc)));
2144
2145 /*
2146 * Same case as PGMR0Trap0eHandlerNPMisconfig(). See comment above, @bugref{6043}.
2147 */
2148 if ( rc == VINF_SUCCESS
2149 || rc == VERR_PAGE_TABLE_NOT_PRESENT
2150 || rc == VERR_PAGE_NOT_PRESENT)
2151 {
2152 /* We've successfully synced our shadow pages, so let's just continue execution. */
2153 Log2(("Shadow page fault at %RGv cr2=%RGp error code %x\n", (RTGCPTR)pCtx->rip, GCPhysFault, errCode));
2154 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitShadowPF);
2155
2156 TRPMResetTrap(pVCpu);
2157 goto ResumeExecution;
2158 }
2159
2160#ifdef VBOX_STRICT
2161 if (rc != VINF_EM_RAW_EMULATE_INSTR)
2162 LogFlow(("PGMTrap0eHandlerNestedPaging failed with %d\n", VBOXSTRICTRC_VAL(rc)));
2163#endif
2164 /* Need to go back to the recompiler to emulate the instruction. */
2165 TRPMResetTrap(pVCpu);
2166 break;
2167 }
2168
2169 case SVM_EXIT_VINTR:
2170 /* A virtual interrupt is about to be delivered, which means IF=1. */
2171 Log(("SVM_EXIT_VINTR IF=%d\n", pCtx->eflags.Bits.u1IF));
2172 pVMCB->ctrl.IntCtrl.n.u1VIrqValid = 0;
2173 pVMCB->ctrl.IntCtrl.n.u8VIrqVector = 0;
2174 goto ResumeExecution;
2175
2176 case SVM_EXIT_FERR_FREEZE:
2177 case SVM_EXIT_INTR:
2178 case SVM_EXIT_NMI:
2179 case SVM_EXIT_SMI:
2180 case SVM_EXIT_INIT:
2181 /* External interrupt; leave to allow it to be dispatched again. */
2182 rc = VINF_EM_RAW_INTERRUPT;
2183 break;
2184
2185 case SVM_EXIT_WBINVD:
2186 case SVM_EXIT_INVD: /* Guest software attempted to execute INVD. */
2187 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitInvd);
2188 /* Skip instruction and continue directly. */
2189 pCtx->rip += 2; /* Note! hardcoded opcode size! */
2190 /* Continue execution.*/
2191 goto ResumeExecution;
2192
2193 case SVM_EXIT_CPUID: /* Guest software attempted to execute CPUID. */
2194 {
2195 Log2(("SVM: Cpuid at %RGv for %x\n", (RTGCPTR)pCtx->rip, pCtx->eax));
2196 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitCpuid);
2197 rc = EMInterpretCpuId(pVM, pVCpu, CPUMCTX2CORE(pCtx));
2198 if (rc == VINF_SUCCESS)
2199 {
2200 /* Update EIP and continue execution. */
2201 pCtx->rip += 2; /* Note! hardcoded opcode size! */
2202 goto ResumeExecution;
2203 }
2204 AssertMsgFailed(("EMU: cpuid failed with %Rrc\n", VBOXSTRICTRC_VAL(rc)));
2205 rc = VINF_EM_RAW_EMULATE_INSTR;
2206 break;
2207 }
2208
2209 case SVM_EXIT_RDTSC: /* Guest software attempted to execute RDTSC. */
2210 {
2211 Log2(("SVM: Rdtsc\n"));
2212 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitRdtsc);
2213 rc = EMInterpretRdtsc(pVM, pVCpu, CPUMCTX2CORE(pCtx));
2214 if (rc == VINF_SUCCESS)
2215 {
2216 /* Update EIP and continue execution. */
2217 pCtx->rip += 2; /* Note! hardcoded opcode size! */
2218 goto ResumeExecution;
2219 }
2220 rc = VINF_EM_RAW_EMULATE_INSTR;
2221 break;
2222 }
2223
2224 case SVM_EXIT_RDPMC: /* Guest software attempted to execute RDPMC. */
2225 {
2226 Log2(("SVM: Rdpmc %x\n", pCtx->ecx));
2227 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitRdpmc);
2228 rc = EMInterpretRdpmc(pVM, pVCpu, CPUMCTX2CORE(pCtx));
2229 if (rc == VINF_SUCCESS)
2230 {
2231 /* Update EIP and continue execution. */
2232 pCtx->rip += 2; /* Note! hardcoded opcode size! */
2233 goto ResumeExecution;
2234 }
2235 rc = VINF_EM_RAW_EMULATE_INSTR;
2236 break;
2237 }
2238
2239 case SVM_EXIT_RDTSCP: /* Guest software attempted to execute RDTSCP. */
2240 {
2241 Log2(("SVM: Rdtscp\n"));
2242 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitRdtscp);
2243 rc = EMInterpretRdtscp(pVM, pVCpu, pCtx);
2244 if (rc == VINF_SUCCESS)
2245 {
2246 /* Update EIP and continue execution. */
2247 pCtx->rip += 3; /* Note! hardcoded opcode size! */
2248 goto ResumeExecution;
2249 }
2250 AssertMsgFailed(("EMU: rdtscp failed with %Rrc\n", VBOXSTRICTRC_VAL(rc)));
2251 rc = VINF_EM_RAW_EMULATE_INSTR;
2252 break;
2253 }
2254
2255 case SVM_EXIT_INVLPG: /* Guest software attempted to execute INVLPG. */
2256 {
2257 Log2(("SVM: invlpg\n"));
2258 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitInvlpg);
2259
2260 Assert(!pVM->hwaccm.s.fNestedPaging);
2261
2262 /* Truly a pita. Why can't SVM give the same information as VT-x? */
2263 rc = hmR0SvmInterpretInvlpg(pVM, pVCpu, CPUMCTX2CORE(pCtx));
2264 if (rc == VINF_SUCCESS)
2265 {
2266 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatFlushPageInvlpg);
2267 goto ResumeExecution; /* eip already updated */
2268 }
2269 break;
2270 }
2271
2272 case SVM_EXIT_WRITE_CR0: case SVM_EXIT_WRITE_CR1: case SVM_EXIT_WRITE_CR2: case SVM_EXIT_WRITE_CR3:
2273 case SVM_EXIT_WRITE_CR4: case SVM_EXIT_WRITE_CR5: case SVM_EXIT_WRITE_CR6: case SVM_EXIT_WRITE_CR7:
2274 case SVM_EXIT_WRITE_CR8: case SVM_EXIT_WRITE_CR9: case SVM_EXIT_WRITE_CR10: case SVM_EXIT_WRITE_CR11:
2275 case SVM_EXIT_WRITE_CR12: case SVM_EXIT_WRITE_CR13: case SVM_EXIT_WRITE_CR14: case SVM_EXIT_WRITE_CR15:
2276 {
2277 Log2(("SVM: %RGv mov cr%d, \n", (RTGCPTR)pCtx->rip, exitCode - SVM_EXIT_WRITE_CR0));
2278 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitCRxWrite[exitCode - SVM_EXIT_WRITE_CR0]);
2279 rc = EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0);
2280
2281 switch (exitCode - SVM_EXIT_WRITE_CR0)
2282 {
2283 case 0:
2284 pVCpu->hwaccm.s.fContextUseFlags |= HWACCM_CHANGED_GUEST_CR0;
2285 break;
2286 case 2:
2287 break;
2288 case 3:
2289 Assert(!pVM->hwaccm.s.fNestedPaging);
2290 pVCpu->hwaccm.s.fContextUseFlags |= HWACCM_CHANGED_GUEST_CR3;
2291 break;
2292 case 4:
2293 pVCpu->hwaccm.s.fContextUseFlags |= HWACCM_CHANGED_GUEST_CR4;
2294 break;
2295 case 8:
2296 break;
2297 default:
2298 AssertFailed();
2299 }
2300 if (rc == VINF_SUCCESS)
2301 {
2302 /* EIP has been updated already. */
2303 /* Only resume if successful. */
2304 goto ResumeExecution;
2305 }
2306 Assert(rc == VERR_EM_INTERPRETER || rc == VINF_PGM_CHANGE_MODE || rc == VINF_PGM_SYNC_CR3);
2307 break;
2308 }
2309
2310 case SVM_EXIT_READ_CR0: case SVM_EXIT_READ_CR1: case SVM_EXIT_READ_CR2: case SVM_EXIT_READ_CR3:
2311 case SVM_EXIT_READ_CR4: case SVM_EXIT_READ_CR5: case SVM_EXIT_READ_CR6: case SVM_EXIT_READ_CR7:
2312 case SVM_EXIT_READ_CR8: case SVM_EXIT_READ_CR9: case SVM_EXIT_READ_CR10: case SVM_EXIT_READ_CR11:
2313 case SVM_EXIT_READ_CR12: case SVM_EXIT_READ_CR13: case SVM_EXIT_READ_CR14: case SVM_EXIT_READ_CR15:
2314 {
2315 Log2(("SVM: %RGv mov x, cr%d\n", (RTGCPTR)pCtx->rip, exitCode - SVM_EXIT_READ_CR0));
2316 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitCRxRead[exitCode - SVM_EXIT_READ_CR0]);
2317 rc = EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0);
2318 if (rc == VINF_SUCCESS)
2319 {
2320 /* EIP has been updated already. */
2321 /* Only resume if successful. */
2322 goto ResumeExecution;
2323 }
2324 Assert(rc == VERR_EM_INTERPRETER || rc == VINF_PGM_CHANGE_MODE || rc == VINF_PGM_SYNC_CR3);
2325 break;
2326 }
2327
2328 case SVM_EXIT_WRITE_DR0: case SVM_EXIT_WRITE_DR1: case SVM_EXIT_WRITE_DR2: case SVM_EXIT_WRITE_DR3:
2329 case SVM_EXIT_WRITE_DR4: case SVM_EXIT_WRITE_DR5: case SVM_EXIT_WRITE_DR6: case SVM_EXIT_WRITE_DR7:
2330 case SVM_EXIT_WRITE_DR8: case SVM_EXIT_WRITE_DR9: case SVM_EXIT_WRITE_DR10: case SVM_EXIT_WRITE_DR11:
2331 case SVM_EXIT_WRITE_DR12: case SVM_EXIT_WRITE_DR13: case SVM_EXIT_WRITE_DR14: case SVM_EXIT_WRITE_DR15:
2332 {
2333 Log2(("SVM: %RGv mov dr%d, x\n", (RTGCPTR)pCtx->rip, exitCode - SVM_EXIT_WRITE_DR0));
2334 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitDRxWrite);
2335
2336 if ( !DBGFIsStepping(pVCpu)
2337 && !CPUMIsHyperDebugStateActive(pVCpu))
2338 {
2339 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatDRxContextSwitch);
2340
2341 /* Disable drx move intercepts. */
2342 pVMCB->ctrl.u16InterceptRdDRx = 0;
2343 pVMCB->ctrl.u16InterceptWrDRx = 0;
2344
2345 /* Save the host and load the guest debug state. */
2346 rc2 = CPUMR0LoadGuestDebugState(pVM, pVCpu, pCtx, false /* exclude DR6 */);
2347 AssertRC(rc2);
2348 goto ResumeExecution;
2349 }
2350
2351 rc = EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0);
2352 if (rc == VINF_SUCCESS)
2353 {
2354 /* EIP has been updated already. */
2355 pVCpu->hwaccm.s.fContextUseFlags |= HWACCM_CHANGED_GUEST_DEBUG;
2356
2357 /* Only resume if successful. */
2358 goto ResumeExecution;
2359 }
2360 Assert(rc == VERR_EM_INTERPRETER || rc == VINF_PGM_CHANGE_MODE || rc == VINF_PGM_SYNC_CR3);
2361 break;
2362 }
2363
2364 case SVM_EXIT_READ_DR0: case SVM_EXIT_READ_DR1: case SVM_EXIT_READ_DR2: case SVM_EXIT_READ_DR3:
2365 case SVM_EXIT_READ_DR4: case SVM_EXIT_READ_DR5: case SVM_EXIT_READ_DR6: case SVM_EXIT_READ_DR7:
2366 case SVM_EXIT_READ_DR8: case SVM_EXIT_READ_DR9: case SVM_EXIT_READ_DR10: case SVM_EXIT_READ_DR11:
2367 case SVM_EXIT_READ_DR12: case SVM_EXIT_READ_DR13: case SVM_EXIT_READ_DR14: case SVM_EXIT_READ_DR15:
2368 {
2369 Log2(("SVM: %RGv mov x, dr%d\n", (RTGCPTR)pCtx->rip, exitCode - SVM_EXIT_READ_DR0));
2370 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitDRxRead);
2371
2372 if (!DBGFIsStepping(pVCpu))
2373 {
2374 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatDRxContextSwitch);
2375
2376 /* Disable DRx move intercepts. */
2377 pVMCB->ctrl.u16InterceptRdDRx = 0;
2378 pVMCB->ctrl.u16InterceptWrDRx = 0;
2379
2380 /* Save the host and load the guest debug state. */
2381 rc2 = CPUMR0LoadGuestDebugState(pVM, pVCpu, pCtx, false /* exclude DR6 */);
2382 AssertRC(rc2);
2383 goto ResumeExecution;
2384 }
2385
2386 rc = EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0);
2387 if (rc == VINF_SUCCESS)
2388 {
2389 /* EIP has been updated already. */
2390 /* Only resume if successful. */
2391 goto ResumeExecution;
2392 }
2393 Assert(rc == VERR_EM_INTERPRETER || rc == VINF_PGM_CHANGE_MODE || rc == VINF_PGM_SYNC_CR3);
2394 break;
2395 }
2396
2397 /* Note: We'll get a #GP if the IO instruction isn't allowed (IOPL or TSS bitmap); no need to double check. */
2398 case SVM_EXIT_IOIO: /* I/O instruction. */
2399 {
2400 SVM_IOIO_EXIT IoExitInfo;
2401
2402 IoExitInfo.au32[0] = pVMCB->ctrl.u64ExitInfo1;
2403 unsigned uIdx = (IoExitInfo.au32[0] >> 4) & 0x7;
2404 uint32_t uIOSize = g_aIOSize[uIdx];
2405 uint32_t uAndVal = g_aIOOpAnd[uIdx];
2406 if (RT_UNLIKELY(!uIOSize))
2407 {
2408 AssertFailed(); /* should be fatal. */
2409 rc = VINF_EM_RAW_EMULATE_INSTR; /** @todo r=ramshankar: would this really fall back to the recompiler and work? */
2410 break;
2411 }
2412
2413 if (IoExitInfo.n.u1STR)
2414 {
2415 /* ins/outs */
2416 PDISCPUSTATE pDis = &pVCpu->hwaccm.s.DisState;
2417
2418 /* Disassemble manually to deal with segment prefixes. */
2419 rc = EMInterpretDisasCurrent(pVM, pVCpu, pDis, NULL);
2420 if (rc == VINF_SUCCESS)
2421 {
2422 if (IoExitInfo.n.u1Type == 0)
2423 {
2424 Log2(("IOMInterpretOUTSEx %RGv %x size=%d\n", (RTGCPTR)pCtx->rip, IoExitInfo.n.u16Port, uIOSize));
2425 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitIOStringWrite);
2426 rc = IOMInterpretOUTSEx(pVM, CPUMCTX2CORE(pCtx), IoExitInfo.n.u16Port, pDis->fPrefix,
2427 (DISCPUMODE)pDis->uAddrMode, uIOSize);
2428 }
2429 else
2430 {
2431 Log2(("IOMInterpretINSEx %RGv %x size=%d\n", (RTGCPTR)pCtx->rip, IoExitInfo.n.u16Port, uIOSize));
2432 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitIOStringRead);
2433 rc = IOMInterpretINSEx(pVM, CPUMCTX2CORE(pCtx), IoExitInfo.n.u16Port, pDis->fPrefix,
2434 (DISCPUMODE)pDis->uAddrMode, uIOSize);
2435 }
2436 }
2437 else
2438 rc = VINF_EM_RAW_EMULATE_INSTR;
2439 }
2440 else
2441 {
2442 /* Normal in/out */
2443 Assert(!IoExitInfo.n.u1REP);
2444
2445 if (IoExitInfo.n.u1Type == 0)
2446 {
2447 Log2(("IOMIOPortWrite %RGv %x %x size=%d\n", (RTGCPTR)pCtx->rip, IoExitInfo.n.u16Port, pCtx->eax & uAndVal,
2448 uIOSize));
2449 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitIOWrite);
2450 rc = IOMIOPortWrite(pVM, IoExitInfo.n.u16Port, pCtx->eax & uAndVal, uIOSize);
2451 if (rc == VINF_IOM_R3_IOPORT_WRITE)
2452 {
2453 HWACCMR0SavePendingIOPortWrite(pVCpu, pCtx->rip, pVMCB->ctrl.u64ExitInfo2, IoExitInfo.n.u16Port,
2454 uAndVal, uIOSize);
2455 }
2456 }
2457 else
2458 {
2459 uint32_t u32Val = 0;
2460
2461 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitIORead);
2462 rc = IOMIOPortRead(pVM, IoExitInfo.n.u16Port, &u32Val, uIOSize);
2463 if (IOM_SUCCESS(rc))
2464 {
2465 /* Write back to the EAX register. */
2466 pCtx->eax = (pCtx->eax & ~uAndVal) | (u32Val & uAndVal);
2467 Log2(("IOMIOPortRead %RGv %x %x size=%d\n", (RTGCPTR)pCtx->rip, IoExitInfo.n.u16Port, u32Val & uAndVal,
2468 uIOSize));
2469 }
2470 else if (rc == VINF_IOM_R3_IOPORT_READ)
2471 {
2472 HWACCMR0SavePendingIOPortRead(pVCpu, pCtx->rip, pVMCB->ctrl.u64ExitInfo2, IoExitInfo.n.u16Port,
2473 uAndVal, uIOSize);
2474 }
2475 }
2476 }
2477
2478 /*
2479 * Handled the I/O return codes.
2480 * (The unhandled cases end up with rc == VINF_EM_RAW_EMULATE_INSTR.)
2481 */
2482 if (IOM_SUCCESS(rc))
2483 {
2484 /* Update EIP and continue execution. */
2485 pCtx->rip = pVMCB->ctrl.u64ExitInfo2; /* RIP/EIP of the next instruction is saved in EXITINFO2. */
2486 if (RT_LIKELY(rc == VINF_SUCCESS))
2487 {
2488 /* If any IO breakpoints are armed, then we should check if a debug trap needs to be generated. */
2489 if (pCtx->dr[7] & X86_DR7_ENABLED_MASK)
2490 {
2491 /* IO operation lookup arrays. */
2492 static uint32_t const aIOSize[4] = { 1, 2, 0, 4 };
2493
2494 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatDRxIOCheck);
2495 for (unsigned i = 0; i < 4; i++)
2496 {
2497 unsigned uBPLen = aIOSize[X86_DR7_GET_LEN(pCtx->dr[7], i)];
2498
2499 if ( (IoExitInfo.n.u16Port >= pCtx->dr[i] && IoExitInfo.n.u16Port < pCtx->dr[i] + uBPLen)
2500 && (pCtx->dr[7] & (X86_DR7_L(i) | X86_DR7_G(i)))
2501 && (pCtx->dr[7] & X86_DR7_RW(i, X86_DR7_RW_IO)) == X86_DR7_RW(i, X86_DR7_RW_IO))
2502 {
2503 SVM_EVENT Event;
2504
2505 Assert(CPUMIsGuestDebugStateActive(pVCpu));
2506
2507 /* Clear all breakpoint status flags and set the one we just hit. */
2508 pCtx->dr[6] &= ~(X86_DR6_B0|X86_DR6_B1|X86_DR6_B2|X86_DR6_B3);
2509 pCtx->dr[6] |= (uint64_t)RT_BIT(i);
2510
2511 /*
2512 * Note: AMD64 Architecture Programmer's Manual 13.1:
2513 * Bits 15:13 of the DR6 register is never cleared by the processor and must be cleared
2514 * by software after the contents have been read.
2515 */
2516 pVMCB->guest.u64DR6 = pCtx->dr[6];
2517
2518 /* X86_DR7_GD will be cleared if drx accesses should be trapped inside the guest. */
2519 pCtx->dr[7] &= ~X86_DR7_GD;
2520
2521 /* Paranoia. */
2522 pCtx->dr[7] &= 0xffffffff; /* upper 32 bits reserved */
2523 pCtx->dr[7] &= ~(RT_BIT(11) | RT_BIT(12) | RT_BIT(14) | RT_BIT(15)); /* must be zero */
2524 pCtx->dr[7] |= 0x400; /* must be one */
2525
2526 pVMCB->guest.u64DR7 = pCtx->dr[7];
2527
2528 /* Inject the exception. */
2529 Log(("Inject IO debug trap at %RGv\n", (RTGCPTR)pCtx->rip));
2530
2531 Event.au64[0] = 0;
2532 Event.n.u3Type = SVM_EVENT_EXCEPTION; /* trap or fault */
2533 Event.n.u1Valid = 1;
2534 Event.n.u8Vector = X86_XCPT_DB;
2535
2536 hmR0SvmInjectEvent(pVCpu, pVMCB, pCtx, &Event);
2537 goto ResumeExecution;
2538 }
2539 }
2540 }
2541 goto ResumeExecution;
2542 }
2543 Log2(("EM status from IO at %RGv %x size %d: %Rrc\n", (RTGCPTR)pCtx->rip, IoExitInfo.n.u16Port, uIOSize,
2544 VBOXSTRICTRC_VAL(rc)));
2545 break;
2546 }
2547
2548#ifdef VBOX_STRICT
2549 if (rc == VINF_IOM_R3_IOPORT_READ)
2550 Assert(IoExitInfo.n.u1Type != 0);
2551 else if (rc == VINF_IOM_R3_IOPORT_WRITE)
2552 Assert(IoExitInfo.n.u1Type == 0);
2553 else
2554 {
2555 AssertMsg( RT_FAILURE(rc)
2556 || rc == VINF_EM_RAW_EMULATE_INSTR
2557 || rc == VINF_EM_RAW_GUEST_TRAP
2558 || rc == VINF_TRPM_XCPT_DISPATCHED, ("%Rrc\n", VBOXSTRICTRC_VAL(rc)));
2559 }
2560#endif
2561 Log2(("Failed IO at %RGv %x size %d\n", (RTGCPTR)pCtx->rip, IoExitInfo.n.u16Port, uIOSize));
2562 break;
2563 }
2564
2565 case SVM_EXIT_HLT:
2566 /* Check if external interrupts are pending; if so, don't switch back. */
2567 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitHlt);
2568 pCtx->rip++; /* skip hlt */
2569 if (EMShouldContinueAfterHalt(pVCpu, pCtx))
2570 goto ResumeExecution;
2571
2572 rc = VINF_EM_HALT;
2573 break;
2574
2575 case SVM_EXIT_MWAIT_UNCOND:
2576 Log2(("SVM: mwait\n"));
2577 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitMwait);
2578 rc = EMInterpretMWait(pVM, pVCpu, CPUMCTX2CORE(pCtx));
2579 if ( rc == VINF_EM_HALT
2580 || rc == VINF_SUCCESS)
2581 {
2582 /* Update EIP and continue execution. */
2583 pCtx->rip += 3; /* Note: hardcoded opcode size assumption! */
2584
2585 /* Check if external interrupts are pending; if so, don't switch back. */
2586 if ( rc == VINF_SUCCESS
2587 || ( rc == VINF_EM_HALT
2588 && EMShouldContinueAfterHalt(pVCpu, pCtx))
2589 )
2590 goto ResumeExecution;
2591 }
2592 AssertMsg(rc == VERR_EM_INTERPRETER || rc == VINF_EM_HALT, ("EMU: mwait failed with %Rrc\n", VBOXSTRICTRC_VAL(rc)));
2593 break;
2594
2595 case SVM_EXIT_MONITOR:
2596 {
2597 Log2(("SVM: monitor\n"));
2598
2599 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitMonitor);
2600 rc = EMInterpretMonitor(pVM, pVCpu, CPUMCTX2CORE(pCtx));
2601 if (rc == VINF_SUCCESS)
2602 {
2603 /* Update EIP and continue execution. */
2604 pCtx->rip += 3; /* Note: hardcoded opcode size assumption! */
2605 goto ResumeExecution;
2606 }
2607 AssertMsg(rc == VERR_EM_INTERPRETER, ("EMU: monitor failed with %Rrc\n", VBOXSTRICTRC_VAL(rc)));
2608 break;
2609 }
2610
2611 case SVM_EXIT_VMMCALL:
2612 rc = hmR0SvmEmulateTprVMMCall(pVM, pVCpu, pCtx);
2613 if (rc == VINF_SUCCESS)
2614 {
2615 goto ResumeExecution; /* rip already updated. */
2616 }
2617 /* no break */
2618
2619 case SVM_EXIT_RSM:
2620 case SVM_EXIT_INVLPGA:
2621 case SVM_EXIT_VMRUN:
2622 case SVM_EXIT_VMLOAD:
2623 case SVM_EXIT_VMSAVE:
2624 case SVM_EXIT_STGI:
2625 case SVM_EXIT_CLGI:
2626 case SVM_EXIT_SKINIT:
2627 {
2628 /* Unsupported instructions. */
2629 SVM_EVENT Event;
2630
2631 Event.au64[0] = 0;
2632 Event.n.u3Type = SVM_EVENT_EXCEPTION;
2633 Event.n.u1Valid = 1;
2634 Event.n.u8Vector = X86_XCPT_UD;
2635
2636 Log(("Forced #UD trap at %RGv\n", (RTGCPTR)pCtx->rip));
2637 hmR0SvmInjectEvent(pVCpu, pVMCB, pCtx, &Event);
2638 goto ResumeExecution;
2639 }
2640
2641 /* Emulate in ring-3. */
2642 case SVM_EXIT_MSR:
2643 {
2644 /* When an interrupt is pending, we'll let MSR_K8_LSTAR writes fault in our TPR patch code. */
2645 if ( pVM->hwaccm.s.fTPRPatchingActive
2646 && pCtx->ecx == MSR_K8_LSTAR
2647 && pVMCB->ctrl.u64ExitInfo1 == 1 /* wrmsr */)
2648 {
2649 if ((pCtx->eax & 0xff) != u8LastTPR)
2650 {
2651 Log(("SVM: Faulting MSR_K8_LSTAR write with new TPR value %x\n", pCtx->eax & 0xff));
2652
2653 /* Our patch code uses LSTAR for TPR caching. */
2654 rc2 = PDMApicSetTPR(pVCpu, pCtx->eax & 0xff);
2655 AssertRC(rc2);
2656 }
2657
2658 /* Skip the instruction and continue. */
2659 pCtx->rip += 2; /* wrmsr = [0F 30] */
2660
2661 /* Only resume if successful. */
2662 goto ResumeExecution;
2663 }
2664
2665 /*
2666 * The Intel spec. claims there's an REX version of RDMSR that's slightly different,
2667 * so we play safe by completely disassembling the instruction.
2668 */
2669 STAM_COUNTER_INC((pVMCB->ctrl.u64ExitInfo1 == 0) ? &pVCpu->hwaccm.s.StatExitRdmsr : &pVCpu->hwaccm.s.StatExitWrmsr);
2670 Log(("SVM: %s\n", (pVMCB->ctrl.u64ExitInfo1 == 0) ? "rdmsr" : "wrmsr"));
2671 rc = EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0);
2672 if (rc == VINF_SUCCESS)
2673 {
2674 /* EIP has been updated already. */
2675 /* Only resume if successful. */
2676 goto ResumeExecution;
2677 }
2678 AssertMsg(rc == VERR_EM_INTERPRETER, ("EMU: %s failed with %Rrc\n", (pVMCB->ctrl.u64ExitInfo1 == 0) ? "rdmsr" : "wrmsr",
2679 VBOXSTRICTRC_VAL(rc)));
2680 break;
2681 }
2682
2683 case SVM_EXIT_TASK_SWITCH: /* too complicated to emulate, so fall back to the recompiler */
2684 Log(("SVM_EXIT_TASK_SWITCH: exit2=%RX64\n", pVMCB->ctrl.u64ExitInfo2));
2685 if ( !(pVMCB->ctrl.u64ExitInfo2 & (SVM_EXIT2_TASK_SWITCH_IRET | SVM_EXIT2_TASK_SWITCH_JMP))
2686 && pVCpu->hwaccm.s.Event.fPending)
2687 {
2688 SVM_EVENT Event;
2689 Event.au64[0] = pVCpu->hwaccm.s.Event.intInfo;
2690
2691 /* Caused by an injected interrupt. */
2692 pVCpu->hwaccm.s.Event.fPending = false;
2693 switch (Event.n.u3Type)
2694 {
2695 case SVM_EVENT_EXTERNAL_IRQ:
2696 case SVM_EVENT_NMI:
2697 Log(("SVM_EXIT_TASK_SWITCH: reassert trap %d\n", Event.n.u8Vector));
2698 Assert(!Event.n.u1ErrorCodeValid);
2699 rc2 = TRPMAssertTrap(pVCpu, Event.n.u8Vector, TRPM_HARDWARE_INT);
2700 AssertRC(rc2);
2701 break;
2702
2703 default:
2704 /* Exceptions and software interrupts can just be restarted. */
2705 break;
2706 }
2707 }
2708 rc = VERR_EM_INTERPRETER;
2709 break;
2710
2711 case SVM_EXIT_PAUSE:
2712 case SVM_EXIT_MWAIT_ARMED:
2713 rc = VERR_EM_INTERPRETER;
2714 break;
2715
2716 case SVM_EXIT_SHUTDOWN:
2717 rc = VINF_EM_RESET; /* Triple fault equals a reset. */
2718 break;
2719
2720 case SVM_EXIT_IDTR_READ:
2721 case SVM_EXIT_GDTR_READ:
2722 case SVM_EXIT_LDTR_READ:
2723 case SVM_EXIT_TR_READ:
2724 case SVM_EXIT_IDTR_WRITE:
2725 case SVM_EXIT_GDTR_WRITE:
2726 case SVM_EXIT_LDTR_WRITE:
2727 case SVM_EXIT_TR_WRITE:
2728 case SVM_EXIT_CR0_SEL_WRITE:
2729 default:
2730 /* Unexpected exit codes. */
2731 rc = VERR_HMSVM_UNEXPECTED_EXIT;
2732 AssertMsgFailed(("Unexpected exit code %x\n", exitCode)); /* Can't happen. */
2733 break;
2734 }
2735
2736end:
2737
2738 /*
2739 * We are now going back to ring-3, so clear the forced action flag.
2740 */
2741 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_TO_R3);
2742
2743 /*
2744 * Signal changes to the recompiler.
2745 */
2746 CPUMSetChangedFlags(pVCpu,
2747 CPUM_CHANGED_SYSENTER_MSR
2748 | CPUM_CHANGED_LDTR
2749 | CPUM_CHANGED_GDTR
2750 | CPUM_CHANGED_IDTR
2751 | CPUM_CHANGED_TR
2752 | CPUM_CHANGED_HIDDEN_SEL_REGS);
2753
2754 /*
2755 * If we executed vmrun and an external IRQ was pending, then we don't have to do a full sync the next time.
2756 */
2757 if (exitCode == SVM_EXIT_INTR)
2758 {
2759 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatPendingHostIrq);
2760 /* On the next entry we'll only sync the host context. */
2761 pVCpu->hwaccm.s.fContextUseFlags |= HWACCM_CHANGED_HOST_CONTEXT;
2762 }
2763 else
2764 {
2765 /* On the next entry we'll sync everything. */
2766 /** @todo we can do better than this */
2767 /* Not in the VINF_PGM_CHANGE_MODE though! */
2768 pVCpu->hwaccm.s.fContextUseFlags |= HWACCM_CHANGED_ALL;
2769 }
2770
2771 /* Translate into a less severe return code */
2772 if (rc == VERR_EM_INTERPRETER)
2773 rc = VINF_EM_RAW_EMULATE_INSTR;
2774
2775 /* Just set the correct state here instead of trying to catch every goto above. */
2776 VMCPU_CMPXCHG_STATE(pVCpu, VMCPUSTATE_STARTED, VMCPUSTATE_STARTED_EXEC);
2777
2778#ifdef VBOX_WITH_VMMR0_DISABLE_PREEMPTION
2779 /* Restore interrupts if we exitted after disabling them. */
2780 if (uOldEFlags != ~(RTCCUINTREG)0)
2781 ASMSetFlags(uOldEFlags);
2782#endif
2783
2784 STAM_PROFILE_ADV_STOP(&pVCpu->hwaccm.s.StatExit2, x);
2785 STAM_PROFILE_ADV_STOP(&pVCpu->hwaccm.s.StatExit1, x);
2786 STAM_PROFILE_ADV_STOP(&pVCpu->hwaccm.s.StatEntry, x);
2787 return VBOXSTRICTRC_TODO(rc);
2788}
2789
2790
2791/**
2792 * Emulate simple mov tpr instruction.
2793 *
2794 * @returns VBox status code.
2795 * @param pVM Pointer to the VM.
2796 * @param pVCpu Pointer to the VMCPU.
2797 * @param pCtx Pointer to the guest CPU context.
2798 */
2799static int hmR0SvmEmulateTprVMMCall(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
2800{
2801 int rc;
2802
2803 LogFlow(("Emulated VMMCall TPR access replacement at %RGv\n", pCtx->rip));
2804
2805 for (;;)
2806 {
2807 bool fPending;
2808 uint8_t u8Tpr;
2809
2810 PHWACCMTPRPATCH pPatch = (PHWACCMTPRPATCH)RTAvloU32Get(&pVM->hwaccm.s.PatchTree, (AVLOU32KEY)pCtx->eip);
2811 if (!pPatch)
2812 break;
2813
2814 switch (pPatch->enmType)
2815 {
2816 case HWACCMTPRINSTR_READ:
2817 /* TPR caching in CR8 */
2818 rc = PDMApicGetTPR(pVCpu, &u8Tpr, &fPending);
2819 AssertRC(rc);
2820
2821 rc = DISWriteReg32(CPUMCTX2CORE(pCtx), pPatch->uDstOperand, u8Tpr);
2822 AssertRC(rc);
2823
2824 LogFlow(("Emulated read successfully\n"));
2825 pCtx->rip += pPatch->cbOp;
2826 break;
2827
2828 case HWACCMTPRINSTR_WRITE_REG:
2829 case HWACCMTPRINSTR_WRITE_IMM:
2830 /* Fetch the new TPR value */
2831 if (pPatch->enmType == HWACCMTPRINSTR_WRITE_REG)
2832 {
2833 uint32_t val;
2834
2835 rc = DISFetchReg32(CPUMCTX2CORE(pCtx), pPatch->uSrcOperand, &val);
2836 AssertRC(rc);
2837 u8Tpr = val;
2838 }
2839 else
2840 u8Tpr = (uint8_t)pPatch->uSrcOperand;
2841
2842 rc = PDMApicSetTPR(pVCpu, u8Tpr);
2843 AssertRC(rc);
2844 LogFlow(("Emulated write successfully\n"));
2845 pCtx->rip += pPatch->cbOp;
2846 break;
2847
2848 default:
2849 AssertMsgFailedReturn(("Unexpected type %d\n", pPatch->enmType), VERR_HMSVM_UNEXPECTED_PATCH_TYPE);
2850 }
2851 }
2852 return VINF_SUCCESS;
2853}
2854
2855
2856/**
2857 * Enters the AMD-V session.
2858 *
2859 * @returns VBox status code.
2860 * @param pVM Pointer to the VM.
2861 * @param pVCpu Pointer to the VMCPU.
2862 * @param pCpu Pointer to the CPU info struct.
2863 */
2864VMMR0DECL(int) SVMR0Enter(PVM pVM, PVMCPU pVCpu, PHMGLOBLCPUINFO pCpu)
2865{
2866 Assert(pVM->hwaccm.s.svm.fSupported);
2867
2868 LogFlow(("SVMR0Enter cpu%d last=%d asid=%d\n", pCpu->idCpu, pVCpu->hwaccm.s.idLastCpu, pVCpu->hwaccm.s.uCurrentASID));
2869 pVCpu->hwaccm.s.fResumeVM = false;
2870
2871 /* Force to reload LDTR, so we'll execute VMLoad to load additional guest state. */
2872 pVCpu->hwaccm.s.fContextUseFlags |= HWACCM_CHANGED_GUEST_LDTR;
2873
2874 return VINF_SUCCESS;
2875}
2876
2877
2878/**
2879 * Leaves the AMD-V session.
2880 *
2881 * @returns VBox status code.
2882 * @param pVM Pointer to the VM.
2883 * @param pVCpu Pointer to the VMCPU.
2884 * @param pCtx Pointer to the guest CPU context.
2885 */
2886VMMR0DECL(int) SVMR0Leave(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
2887{
2888 SVM_VMCB *pVMCB = (SVM_VMCB *)pVCpu->hwaccm.s.svm.pVMCB;
2889
2890 Assert(pVM->hwaccm.s.svm.fSupported);
2891
2892#ifdef DEBUG
2893 if (CPUMIsHyperDebugStateActive(pVCpu))
2894 {
2895 CPUMR0LoadHostDebugState(pVM, pVCpu);
2896 }
2897 else
2898#endif
2899 /* Save the guest debug state if necessary. */
2900 if (CPUMIsGuestDebugStateActive(pVCpu))
2901 {
2902 CPUMR0SaveGuestDebugState(pVM, pVCpu, pCtx, false /* skip DR6 */);
2903
2904 /* Intercept all DRx reads and writes again. Changed later on. */
2905 pVMCB->ctrl.u16InterceptRdDRx = 0xFFFF;
2906 pVMCB->ctrl.u16InterceptWrDRx = 0xFFFF;
2907
2908 /* Resync the debug registers the next time. */
2909 pVCpu->hwaccm.s.fContextUseFlags |= HWACCM_CHANGED_GUEST_DEBUG;
2910 }
2911 else
2912 Assert(pVMCB->ctrl.u16InterceptRdDRx == 0xFFFF && pVMCB->ctrl.u16InterceptWrDRx == 0xFFFF);
2913
2914 return VINF_SUCCESS;
2915}
2916
2917
2918/**
2919 * Worker for Interprets INVLPG.
2920 *
2921 * @return VBox status code.
2922 * @param pVCpu Pointer to the VMCPU.
2923 * @param pCpu Pointer to the CPU info struct.
2924 * @param pRegFrame Pointer to the register frame.
2925 */
2926static int hmR0svmInterpretInvlPgEx(PVMCPU pVCpu, PDISCPUSTATE pCpu, PCPUMCTXCORE pRegFrame)
2927{
2928 DISQPVPARAMVAL param1;
2929 RTGCPTR addr;
2930
2931 int rc = DISQueryParamVal(pRegFrame, pCpu, &pCpu->Param1, &param1, DISQPVWHICH_SRC);
2932 if (RT_FAILURE(rc))
2933 return VERR_EM_INTERPRETER;
2934
2935 switch (param1.type)
2936 {
2937 case DISQPV_TYPE_IMMEDIATE:
2938 case DISQPV_TYPE_ADDRESS:
2939 if (!(param1.flags & (DISQPV_FLAG_32 | DISQPV_FLAG_64)))
2940 return VERR_EM_INTERPRETER;
2941 addr = param1.val.val64;
2942 break;
2943
2944 default:
2945 return VERR_EM_INTERPRETER;
2946 }
2947
2948 /** @todo is addr always a flat linear address or ds based
2949 * (in absence of segment override prefixes)????
2950 */
2951 rc = PGMInvalidatePage(pVCpu, addr);
2952 if (RT_SUCCESS(rc))
2953 return VINF_SUCCESS;
2954
2955 AssertRC(rc);
2956 return rc;
2957}
2958
2959
2960/**
2961 * Interprets INVLPG.
2962 *
2963 * @returns VBox status code.
2964 * @retval VINF_* Scheduling instructions.
2965 * @retval VERR_EM_INTERPRETER Something we can't cope with.
2966 * @retval VERR_* Fatal errors.
2967 *
2968 * @param pVM Pointer to the VM.
2969 * @param pRegFrame Pointer to the register frame.
2970 *
2971 * @remarks Updates the EIP if an instruction was executed successfully.
2972 */
2973static int hmR0SvmInterpretInvlpg(PVM pVM, PVMCPU pVCpu, PCPUMCTXCORE pRegFrame)
2974{
2975 /*
2976 * Only allow 32 & 64 bit code.
2977 */
2978 if (CPUMGetGuestCodeBits(pVCpu) != 16)
2979 {
2980 PDISSTATE pDis = &pVCpu->hwaccm.s.DisState;
2981 int rc = EMInterpretDisasCurrent(pVM, pVCpu, pDis, NULL);
2982 if (RT_SUCCESS(rc) && pDis->pCurInstr->uOpcode == OP_INVLPG)
2983 {
2984 rc = hmR0svmInterpretInvlPgEx(pVCpu, pDis, pRegFrame);
2985 if (RT_SUCCESS(rc))
2986 pRegFrame->rip += pDis->cbInstr; /* Move on to the next instruction. */
2987 return rc;
2988 }
2989 }
2990 return VERR_EM_INTERPRETER;
2991}
2992
2993
2994/**
2995 * Invalidates a guest page by guest virtual address.
2996 *
2997 * @returns VBox status code.
2998 * @param pVM Pointer to the VM.
2999 * @param pVCpu Pointer to the VMCPU.
3000 * @param GCVirt Guest virtual address of the page to invalidate.
3001 */
3002VMMR0DECL(int) SVMR0InvalidatePage(PVM pVM, PVMCPU pVCpu, RTGCPTR GCVirt)
3003{
3004 bool fFlushPending = pVM->hwaccm.s.svm.fAlwaysFlushTLB | VMCPU_FF_ISSET(pVCpu, VMCPU_FF_TLB_FLUSH);
3005
3006 /* Skip it if a TLB flush is already pending. */
3007 if (!fFlushPending)
3008 {
3009 SVM_VMCB *pVMCB;
3010
3011 Log2(("SVMR0InvalidatePage %RGv\n", GCVirt));
3012 AssertReturn(pVM, VERR_INVALID_PARAMETER);
3013 Assert(pVM->hwaccm.s.svm.fSupported);
3014
3015 pVMCB = (SVM_VMCB *)pVCpu->hwaccm.s.svm.pVMCB;
3016 AssertMsgReturn(pVMCB, ("Invalid pVMCB\n"), VERR_HMSVM_INVALID_PVMCB);
3017
3018#if HC_ARCH_BITS == 32
3019 /* If we get a flush in 64 bits guest mode, then force a full TLB flush. Invlpga takes only 32 bits addresses. */
3020 if (CPUMIsGuestInLongMode(pVCpu))
3021 VMCPU_FF_SET(pVCpu, VMCPU_FF_TLB_FLUSH);
3022 else
3023#endif
3024 SVMR0InvlpgA(GCVirt, pVMCB->ctrl.TLBCtrl.n.u32ASID);
3025 }
3026 return VINF_SUCCESS;
3027}
3028
3029
3030#if 0 /* obsolete, but left here for clarification. */
3031/**
3032 * Invalidates a guest page by physical address.
3033 *
3034 * @returns VBox status code.
3035 * @param pVM Pointer to the VM.
3036 * @param pVCpu Pointer to the VMCPU.
3037 * @param GCPhys Guest physical address of the page to invalidate.
3038 */
3039VMMR0DECL(int) SVMR0InvalidatePhysPage(PVM pVM, PVMCPU pVCpu, RTGCPHYS GCPhys)
3040{
3041 Assert(pVM->hwaccm.s.fNestedPaging);
3042 /* invlpga only invalidates TLB entries for guest virtual addresses; we have no choice but to force a TLB flush here. */
3043 VMCPU_FF_SET(pVCpu, VMCPU_FF_TLB_FLUSH);
3044 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatFlushTLBInvlpga);
3045 return VINF_SUCCESS;
3046}
3047#endif
3048
3049
3050#if HC_ARCH_BITS == 32 && defined(VBOX_ENABLE_64_BITS_GUESTS) && !defined(VBOX_WITH_HYBRID_32BIT_KERNEL)
3051/**
3052 * Prepares for and executes VMRUN (64-bit guests from a 32-bit host).
3053 *
3054 * @returns VBox status code.
3055 * @param pVMCBHostPhys Physical address of host VMCB.
3056 * @param pVMCBPhys Physical address of the VMCB.
3057 * @param pCtx Pointer to the guest CPU context.
3058 * @param pVM Pointer to the VM.
3059 * @param pVCpu Pointer to the VMCPU.
3060 */
3061DECLASM(int) SVMR0VMSwitcherRun64(RTHCPHYS pVMCBHostPhys, RTHCPHYS pVMCBPhys, PCPUMCTX pCtx, PVM pVM, PVMCPU pVCpu)
3062{
3063 uint32_t aParam[4];
3064
3065 aParam[0] = (uint32_t)(pVMCBHostPhys); /* Param 1: pVMCBHostPhys - Lo. */
3066 aParam[1] = (uint32_t)(pVMCBHostPhys >> 32); /* Param 1: pVMCBHostPhys - Hi. */
3067 aParam[2] = (uint32_t)(pVMCBPhys); /* Param 2: pVMCBPhys - Lo. */
3068 aParam[3] = (uint32_t)(pVMCBPhys >> 32); /* Param 2: pVMCBPhys - Hi. */
3069
3070 return SVMR0Execute64BitsHandler(pVM, pVCpu, pCtx, pVM->hwaccm.s.pfnSVMGCVMRun64, 4, &aParam[0]);
3071}
3072
3073
3074/**
3075 * Executes the specified handler in 64-bit mode.
3076 *
3077 * @returns VBox status code.
3078 * @param pVM Pointer to the VM.
3079 * @param pVCpu Pointer to the VMCPU.
3080 * @param pCtx Pointer to the guest CPU context.
3081 * @param pfnHandler Pointer to the RC handler function.
3082 * @param cbParam Number of parameters.
3083 * @param paParam Array of 32-bit parameters.
3084 */
3085VMMR0DECL(int) SVMR0Execute64BitsHandler(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, RTRCPTR pfnHandler, uint32_t cbParam,
3086 uint32_t *paParam)
3087{
3088 int rc;
3089 RTHCUINTREG uOldEFlags;
3090
3091 Assert(pfnHandler);
3092
3093 /* Disable interrupts. */
3094 uOldEFlags = ASMIntDisableFlags();
3095
3096#ifdef VBOX_WITH_VMMR0_DISABLE_LAPIC_NMI
3097 RTCPUID idHostCpu = RTMpCpuId();
3098 CPUMR0SetLApic(pVM, idHostCpu);
3099#endif
3100
3101 CPUMSetHyperESP(pVCpu, VMMGetStackRC(pVCpu));
3102 CPUMSetHyperEIP(pVCpu, pfnHandler);
3103 for (int i = (int)cbParam - 1; i >= 0; i--)
3104 CPUMPushHyper(pVCpu, paParam[i]);
3105
3106 STAM_PROFILE_ADV_START(&pVCpu->hwaccm.s.StatWorldSwitch3264, z);
3107 /* Call switcher. */
3108 rc = pVM->hwaccm.s.pfnHost32ToGuest64R0(pVM, RT_OFFSETOF(VM, aCpus[pVCpu->idCpu].cpum) - RT_OFFSETOF(VM, cpum));
3109 STAM_PROFILE_ADV_STOP(&pVCpu->hwaccm.s.StatWorldSwitch3264, z);
3110
3111 ASMSetFlags(uOldEFlags);
3112 return rc;
3113}
3114
3115#endif /* HC_ARCH_BITS == 32 && defined(VBOX_ENABLE_64_BITS_GUESTS) */
3116
Note: See TracBrowser for help on using the repository browser.

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