VirtualBox

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

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

VMMR0/HWSVMR0: lookup table for IOIO intercepts' operand size.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 122.7 KB
Line 
1/* $Id: HWSVMR0.cpp 42900 2012-08-21 10:30:08Z 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 pVMCB->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_ENTIRE;
1072 }
1073 else if (pVCpu->hwaccm.s.fForceTLBFlush)
1074 {
1075 if (fNewASID)
1076 {
1077 ++pCpu->uCurrentASID;
1078 bool fHitASIDLimit = false;
1079 if (pCpu->uCurrentASID >= pVM->hwaccm.s.uMaxASID)
1080 {
1081 pCpu->uCurrentASID = 1; /* start at 1; host uses 0 */
1082 pCpu->cTLBFlushes++;
1083 fHitASIDLimit = true;
1084
1085 if (pVM->hwaccm.s.svm.u32Features & AMD_CPUID_SVM_FEATURE_EDX_FLUSH_BY_ASID)
1086 {
1087 pVMCB->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_SINGLE_CONTEXT;
1088 pCpu->fFlushASIDBeforeUse = true;
1089 }
1090 else
1091 {
1092 pVMCB->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_ENTIRE;
1093 pCpu->fFlushASIDBeforeUse = false;
1094 }
1095 }
1096
1097 if ( !fHitASIDLimit
1098 && pCpu->fFlushASIDBeforeUse)
1099 {
1100 if (pVM->hwaccm.s.svm.u32Features & AMD_CPUID_SVM_FEATURE_EDX_FLUSH_BY_ASID)
1101 pVMCB->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_SINGLE_CONTEXT;
1102 else
1103 {
1104 pVMCB->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_ENTIRE;
1105 pCpu->fFlushASIDBeforeUse = false;
1106 }
1107 }
1108
1109 pVCpu->hwaccm.s.uCurrentASID = pCpu->uCurrentASID;
1110 pVCpu->hwaccm.s.cTLBFlushes = pCpu->cTLBFlushes;
1111 }
1112 else
1113 {
1114 if (pVM->hwaccm.s.svm.u32Features & AMD_CPUID_SVM_FEATURE_EDX_FLUSH_BY_ASID)
1115 pVMCB->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_SINGLE_CONTEXT;
1116 else
1117 pVMCB->ctrl.TLBCtrl.n.u8TLBFlush = SVM_TLB_FLUSH_ENTIRE;
1118 }
1119
1120 pVCpu->hwaccm.s.fForceTLBFlush = false;
1121 }
1122 else
1123 {
1124 /** @todo We never set VMCPU_FF_TLB_SHOOTDOWN anywhere so this path should
1125 * not be executed. See hwaccmQueueInvlPage() where it is commented
1126 * out. Support individual entry flushing someday. */
1127 if (VMCPU_FF_ISPENDING(pVCpu, VMCPU_FF_TLB_SHOOTDOWN))
1128 {
1129 /* Deal with pending TLB shootdown actions which were queued when we were not executing code. */
1130 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatTlbShootdown);
1131 for (unsigned i = 0; i < pVCpu->hwaccm.s.TlbShootdown.cPages; i++)
1132 SVMR0InvlpgA(pVCpu->hwaccm.s.TlbShootdown.aPages[i], pVMCB->ctrl.TLBCtrl.n.u32ASID);
1133 }
1134 }
1135
1136 pVCpu->hwaccm.s.TlbShootdown.cPages = 0;
1137 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_TLB_SHOOTDOWN);
1138
1139 /* Update VMCB with the ASID. */
1140 pVMCB->ctrl.TLBCtrl.n.u32ASID = pVCpu->hwaccm.s.uCurrentASID;
1141
1142 AssertMsg(pVCpu->hwaccm.s.cTLBFlushes == pCpu->cTLBFlushes,
1143 ("Flush count mismatch for cpu %d (%x vs %x)\n", pCpu->idCpu, pVCpu->hwaccm.s.cTLBFlushes, pCpu->cTLBFlushes));
1144 AssertMsg(pCpu->uCurrentASID >= 1 && pCpu->uCurrentASID < pVM->hwaccm.s.uMaxASID,
1145 ("cpu%d uCurrentASID = %x\n", pCpu->idCpu, pCpu->uCurrentASID));
1146 AssertMsg(pVCpu->hwaccm.s.uCurrentASID >= 1 && pVCpu->hwaccm.s.uCurrentASID < pVM->hwaccm.s.uMaxASID,
1147 ("cpu%d VM uCurrentASID = %x\n", pCpu->idCpu, pVCpu->hwaccm.s.uCurrentASID));
1148
1149#ifdef VBOX_WITH_STATISTICS
1150 if (pVMCB->ctrl.TLBCtrl.n.u8TLBFlush == SVM_TLB_FLUSH_NOTHING)
1151 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatNoFlushTLBWorldSwitch);
1152 else if ( pVMCB->ctrl.TLBCtrl.n.u8TLBFlush == SVM_TLB_FLUSH_SINGLE_CONTEXT
1153 || pVMCB->ctrl.TLBCtrl.n.u8TLBFlush == SVM_TLB_FLUSH_SINGLE_CONTEXT_RETAIN_GLOBALS)
1154 {
1155 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatFlushASID);
1156 }
1157 else
1158 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatFlushTLBWorldSwitch);
1159#endif
1160}
1161
1162
1163/**
1164 * Runs guest code in an AMD-V VM.
1165 *
1166 * @returns VBox status code.
1167 * @param pVM Pointer to the VM.
1168 * @param pVCpu Pointer to the VMCPU.
1169 * @param pCtx Pointer to the guest CPU context.
1170 */
1171VMMR0DECL(int) SVMR0RunGuestCode(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
1172{
1173 STAM_PROFILE_ADV_START(&pVCpu->hwaccm.s.StatEntry, x);
1174 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hwaccm.s.StatExit1);
1175 STAM_PROFILE_ADV_SET_STOPPED(&pVCpu->hwaccm.s.StatExit2);
1176
1177 VBOXSTRICTRC rc = VINF_SUCCESS;
1178 int rc2;
1179 uint64_t exitCode = (uint64_t)SVM_EXIT_INVALID;
1180 SVM_VMCB *pVMCB = NULL;
1181 bool fSyncTPR = false;
1182 unsigned cResume = 0;
1183 uint8_t u8LastTPR = 0; /* Initialized for potentially stupid compilers. */
1184 uint32_t u32HostExtFeatures = 0;
1185 PHMGLOBLCPUINFO pCpu = 0;
1186 RTCCUINTREG uOldEFlags = ~(RTCCUINTREG)0;
1187#ifdef VBOX_STRICT
1188 RTCPUID idCpuCheck;
1189#endif
1190#ifdef VBOX_HIGH_RES_TIMERS_HACK_IN_RING0
1191 uint64_t u64LastTime = RTTimeMilliTS();
1192#endif
1193
1194 pVMCB = (SVM_VMCB *)pVCpu->hwaccm.s.svm.pVMCB;
1195 AssertMsgReturn(pVMCB, ("Invalid pVMCB\n"), VERR_HMSVM_INVALID_PVMCB);
1196
1197 /*
1198 * We can jump to this point to resume execution after determining that a VM-exit is innocent.
1199 */
1200ResumeExecution:
1201 if (!STAM_PROFILE_ADV_IS_RUNNING(&pVCpu->hwaccm.s.StatEntry))
1202 STAM_PROFILE_ADV_STOP_START(&pVCpu->hwaccm.s.StatExit2, &pVCpu->hwaccm.s.StatEntry, x);
1203 Assert(!HWACCMR0SuspendPending());
1204
1205 /*
1206 * Safety precaution; looping for too long here can have a very bad effect on the host.
1207 */
1208 if (RT_UNLIKELY(++cResume > pVM->hwaccm.s.cMaxResumeLoops))
1209 {
1210 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitMaxResume);
1211 rc = VINF_EM_RAW_INTERRUPT;
1212 goto end;
1213 }
1214
1215 /*
1216 * Check for IRQ inhibition due to instruction fusing (sti, mov ss).
1217 */
1218 if (VMCPU_FF_ISSET(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS))
1219 {
1220 Log(("VM_FF_INHIBIT_INTERRUPTS at %RGv successor %RGv\n", (RTGCPTR)pCtx->rip, EMGetInhibitInterruptsPC(pVCpu)));
1221 if (pCtx->rip != EMGetInhibitInterruptsPC(pVCpu))
1222 {
1223 /*
1224 * Note: we intentionally don't clear VM_FF_INHIBIT_INTERRUPTS here.
1225 * Before we are able to execute this instruction in raw mode (iret to guest code) an external interrupt might
1226 * force a world switch again. Possibly allowing a guest interrupt to be dispatched in the process. This could
1227 * break the guest. Sounds very unlikely, but such timing sensitive problems are not as rare as you might think.
1228 */
1229 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
1230 /* Irq inhibition is no longer active; clear the corresponding SVM state. */
1231 pVMCB->ctrl.u64IntShadow = 0;
1232 }
1233 }
1234 else
1235 {
1236 /* Irq inhibition is no longer active; clear the corresponding SVM state. */
1237 pVMCB->ctrl.u64IntShadow = 0;
1238 }
1239
1240#ifdef VBOX_HIGH_RES_TIMERS_HACK_IN_RING0
1241 if (RT_UNLIKELY((cResume & 0xf) == 0))
1242 {
1243 uint64_t u64CurTime = RTTimeMilliTS();
1244
1245 if (RT_UNLIKELY(u64CurTime > u64LastTime))
1246 {
1247 u64LastTime = u64CurTime;
1248 TMTimerPollVoid(pVM, pVCpu);
1249 }
1250 }
1251#endif
1252
1253 /*
1254 * Check for pending actions that force us to go back to ring-3.
1255 */
1256 if ( VM_FF_ISPENDING(pVM, VM_FF_HWACCM_TO_R3_MASK | VM_FF_REQUEST | VM_FF_PGM_POOL_FLUSH_PENDING | VM_FF_PDM_DMA)
1257 || VMCPU_FF_ISPENDING(pVCpu,
1258 VMCPU_FF_HWACCM_TO_R3_MASK
1259 | VMCPU_FF_PGM_SYNC_CR3
1260 | VMCPU_FF_PGM_SYNC_CR3_NON_GLOBAL
1261 | VMCPU_FF_REQUEST))
1262 {
1263 /* Check if a sync operation is pending. */
1264 if (VMCPU_FF_ISPENDING(pVCpu, VMCPU_FF_PGM_SYNC_CR3 | VMCPU_FF_PGM_SYNC_CR3_NON_GLOBAL))
1265 {
1266 rc = PGMSyncCR3(pVCpu, pCtx->cr0, pCtx->cr3, pCtx->cr4, VMCPU_FF_ISSET(pVCpu, VMCPU_FF_PGM_SYNC_CR3));
1267 AssertRC(VBOXSTRICTRC_VAL(rc));
1268 if (rc != VINF_SUCCESS)
1269 {
1270 Log(("Pending pool sync is forcing us back to ring 3; rc=%d\n", VBOXSTRICTRC_VAL(rc)));
1271 goto end;
1272 }
1273 }
1274
1275#ifdef DEBUG
1276 /* Intercept X86_XCPT_DB if stepping is enabled */
1277 if (!DBGFIsStepping(pVCpu))
1278#endif
1279 {
1280 if ( VM_FF_ISPENDING(pVM, VM_FF_HWACCM_TO_R3_MASK)
1281 || VMCPU_FF_ISPENDING(pVCpu, VMCPU_FF_HWACCM_TO_R3_MASK))
1282 {
1283 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatSwitchToR3);
1284 rc = RT_UNLIKELY(VM_FF_ISPENDING(pVM, VM_FF_PGM_NO_MEMORY)) ? VINF_EM_NO_MEMORY : VINF_EM_RAW_TO_R3;
1285 goto end;
1286 }
1287 }
1288
1289 /* Pending request packets might contain actions that need immediate attention, such as pending hardware interrupts. */
1290 if ( VM_FF_ISPENDING(pVM, VM_FF_REQUEST)
1291 || VMCPU_FF_ISPENDING(pVCpu, VMCPU_FF_REQUEST))
1292 {
1293 rc = VINF_EM_PENDING_REQUEST;
1294 goto end;
1295 }
1296
1297 /* Check if a pgm pool flush is in progress. */
1298 if (VM_FF_ISPENDING(pVM, VM_FF_PGM_POOL_FLUSH_PENDING))
1299 {
1300 rc = VINF_PGM_POOL_FLUSH_PENDING;
1301 goto end;
1302 }
1303
1304 /* Check if DMA work is pending (2nd+ run). */
1305 if (VM_FF_ISPENDING(pVM, VM_FF_PDM_DMA) && cResume > 1)
1306 {
1307 rc = VINF_EM_RAW_TO_R3;
1308 goto end;
1309 }
1310 }
1311
1312#ifdef VBOX_WITH_VMMR0_DISABLE_PREEMPTION
1313 /*
1314 * Exit to ring-3 preemption/work is pending.
1315 *
1316 * Interrupts are disabled before the call to make sure we don't miss any interrupt
1317 * that would flag preemption (IPI, timer tick, ++). (Would've been nice to do this
1318 * further down, but hmR0SvmCheckPendingInterrupt makes that impossible.)
1319 *
1320 * Note! Interrupts must be disabled done *before* we check for TLB flushes; TLB
1321 * shootdowns rely on this.
1322 */
1323 uOldEFlags = ASMIntDisableFlags();
1324 if (RTThreadPreemptIsPending(NIL_RTTHREAD))
1325 {
1326 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitPreemptPending);
1327 rc = VINF_EM_RAW_INTERRUPT;
1328 goto end;
1329 }
1330 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_EXEC);
1331#endif
1332
1333 /*
1334 * When external interrupts are pending, we should exit the VM when IF is set.
1335 * Note: *After* VM_FF_INHIBIT_INTERRUPTS check!!
1336 */
1337 rc = hmR0SvmCheckPendingInterrupt(pVM, pVCpu, pVMCB, pCtx);
1338 if (RT_FAILURE(rc))
1339 goto end;
1340
1341 /*
1342 * TPR caching using CR8 is only available in 64-bit mode or with 32-bit guests when X86_CPUID_AMD_FEATURE_ECX_CR8L is
1343 * supported.
1344 * Note: we can't do this in LoddGuestState as PDMApicGetTPR can jump back to ring 3 (lock)! (no longer true)
1345 */
1346 /** @todo query and update the TPR only when it could have been changed (mmio access)
1347 */
1348 if (pVM->hwaccm.s.fHasIoApic)
1349 {
1350 /* TPR caching in CR8 */
1351 bool fPending;
1352 rc2 = PDMApicGetTPR(pVCpu, &u8LastTPR, &fPending);
1353 AssertRC(rc2);
1354
1355 if (pVM->hwaccm.s.fTPRPatchingActive)
1356 {
1357 /* Our patch code uses LSTAR for TPR caching. */
1358 pCtx->msrLSTAR = u8LastTPR;
1359
1360 if (fPending)
1361 {
1362 /* A TPR change could activate a pending interrupt, so catch lstar writes. */
1363 hmR0SvmSetMSRPermission(pVCpu, MSR_K8_LSTAR, true, false);
1364 }
1365 else
1366 {
1367 /*
1368 * No interrupts are pending, so we don't need to be explicitely notified.
1369 * There are enough world switches for detecting pending interrupts.
1370 */
1371 hmR0SvmSetMSRPermission(pVCpu, MSR_K8_LSTAR, true, true);
1372 }
1373 }
1374 else
1375 {
1376 /* cr8 bits 3-0 correspond to bits 7-4 of the task priority mmio register. */
1377 pVMCB->ctrl.IntCtrl.n.u8VTPR = (u8LastTPR >> 4);
1378
1379 if (fPending)
1380 {
1381 /* A TPR change could activate a pending interrupt, so catch cr8 writes. */
1382 pVMCB->ctrl.u16InterceptWrCRx |= RT_BIT(8);
1383 }
1384 else
1385 {
1386 /*
1387 * No interrupts are pending, so we don't need to be explicitly notified.
1388 * There are enough world switches for detecting pending interrupts.
1389 */
1390 pVMCB->ctrl.u16InterceptWrCRx &= ~RT_BIT(8);
1391 }
1392 }
1393 fSyncTPR = !fPending;
1394 }
1395
1396 /* All done! Let's start VM execution. */
1397
1398 /* Enable nested paging if necessary (disabled each time after #VMEXIT). */
1399 pVMCB->ctrl.NestedPaging.n.u1NestedPaging = pVM->hwaccm.s.fNestedPaging;
1400
1401#ifdef LOG_ENABLED
1402 pCpu = HWACCMR0GetCurrentCpu();
1403 if (pVCpu->hwaccm.s.idLastCpu != pCpu->idCpu)
1404 LogFlow(("Force TLB flush due to rescheduling to a different cpu (%d vs %d)\n", pVCpu->hwaccm.s.idLastCpu, pCpu->idCpu));
1405 else if (pVCpu->hwaccm.s.cTLBFlushes != pCpu->cTLBFlushes)
1406 LogFlow(("Force TLB flush due to changed TLB flush count (%x vs %x)\n", pVCpu->hwaccm.s.cTLBFlushes, pCpu->cTLBFlushes));
1407 else if (VMCPU_FF_ISSET(pVCpu, VMCPU_FF_TLB_FLUSH))
1408 LogFlow(("Manual TLB flush\n"));
1409#endif
1410
1411 /*
1412 * NOTE: DO NOT DO ANYTHING AFTER THIS POINT THAT MIGHT JUMP BACK TO RING 3!
1413 * (until the actual world switch)
1414 */
1415#ifdef VBOX_STRICT
1416 idCpuCheck = RTMpCpuId();
1417#endif
1418 VMMR0LogFlushDisable(pVCpu);
1419
1420 /*
1421 * Load the guest state; *must* be here as it sets up the shadow CR0 for lazy FPU syncing!
1422 */
1423 rc = SVMR0LoadGuestState(pVM, pVCpu, pCtx);
1424 if (RT_UNLIKELY(rc != VINF_SUCCESS))
1425 {
1426 VMMR0LogFlushEnable(pVCpu);
1427 goto end;
1428 }
1429
1430#ifndef VBOX_WITH_VMMR0_DISABLE_PREEMPTION
1431 /*
1432 * Disable interrupts to make sure a poke will interrupt execution.
1433 * This must be done *before* we check for TLB flushes; TLB shootdowns rely on this.
1434 */
1435 uOldEFlags = ASMIntDisableFlags();
1436 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED_EXEC);
1437#endif
1438 STAM_PROFILE_ADV_STOP_START(&pVCpu->hwaccm.s.StatEntry, &pVCpu->hwaccm.s.StatInGC, x);
1439
1440 /* Setup TLB control and ASID in the VMCB. */
1441 hmR0SvmSetupTLB(pVM, pVCpu);
1442
1443 /* In case we execute a goto ResumeExecution later on. */
1444 pVCpu->hwaccm.s.fResumeVM = true;
1445 pVCpu->hwaccm.s.fForceTLBFlush = pVM->hwaccm.s.svm.fAlwaysFlushTLB;
1446
1447 Assert(sizeof(pVCpu->hwaccm.s.svm.pVMCBPhys) == 8);
1448 Assert(pVMCB->ctrl.IntCtrl.n.u1VIrqMasking);
1449 Assert(pVMCB->ctrl.u64IOPMPhysAddr == pVM->hwaccm.s.svm.pIOBitmapPhys);
1450 Assert(pVMCB->ctrl.u64MSRPMPhysAddr == pVCpu->hwaccm.s.svm.pMSRBitmapPhys);
1451 Assert(pVMCB->ctrl.u64LBRVirt == 0);
1452
1453#ifdef VBOX_STRICT
1454 Assert(idCpuCheck == RTMpCpuId());
1455#endif
1456 TMNotifyStartOfExecution(pVCpu);
1457
1458 /*
1459 * Save the current Host TSC_AUX and write the guest TSC_AUX to the host, so that
1460 * RDTSCPs (that don't cause exits) reads the guest MSR. See @bugref{3324}.
1461 */
1462 u32HostExtFeatures = pVM->hwaccm.s.cpuid.u32AMDFeatureEDX;
1463 if ( (u32HostExtFeatures & X86_CPUID_EXT_FEATURE_EDX_RDTSCP)
1464 && !(pVMCB->ctrl.u32InterceptCtrl2 & SVM_CTRL2_INTERCEPT_RDTSCP))
1465 {
1466 pVCpu->hwaccm.s.u64HostTSCAux = ASMRdMsr(MSR_K8_TSC_AUX);
1467 uint64_t u64GuestTSCAux = 0;
1468 rc2 = CPUMQueryGuestMsr(pVCpu, MSR_K8_TSC_AUX, &u64GuestTSCAux);
1469 AssertRC(rc2);
1470 ASMWrMsr(MSR_K8_TSC_AUX, u64GuestTSCAux);
1471 }
1472
1473#ifdef VBOX_WITH_KERNEL_USING_XMM
1474 hwaccmR0SVMRunWrapXMM(pVCpu->hwaccm.s.svm.pVMCBHostPhys, pVCpu->hwaccm.s.svm.pVMCBPhys, pCtx, pVM, pVCpu,
1475 pVCpu->hwaccm.s.svm.pfnVMRun);
1476#else
1477 pVCpu->hwaccm.s.svm.pfnVMRun(pVCpu->hwaccm.s.svm.pVMCBHostPhys, pVCpu->hwaccm.s.svm.pVMCBPhys, pCtx, pVM, pVCpu);
1478#endif
1479 ASMAtomicWriteBool(&pVCpu->hwaccm.s.fCheckedTLBFlush, false);
1480 ASMAtomicIncU32(&pVCpu->hwaccm.s.cWorldSwitchExits);
1481 /* Possibly the last TSC value seen by the guest (too high) (only when we're in TSC offset mode). */
1482 if (!(pVMCB->ctrl.u32InterceptCtrl1 & SVM_CTRL1_INTERCEPT_RDTSC))
1483 {
1484 /* Restore host's TSC_AUX. */
1485 if (u32HostExtFeatures & X86_CPUID_EXT_FEATURE_EDX_RDTSCP)
1486 ASMWrMsr(MSR_K8_TSC_AUX, pVCpu->hwaccm.s.u64HostTSCAux);
1487
1488 TMCpuTickSetLastSeen(pVCpu, ASMReadTSC() +
1489 pVMCB->ctrl.u64TSCOffset - 0x400 /* guestimate of world switch overhead in clock ticks */);
1490 }
1491 TMNotifyEndOfExecution(pVCpu);
1492 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED);
1493 STAM_PROFILE_ADV_STOP_START(&pVCpu->hwaccm.s.StatInGC, &pVCpu->hwaccm.s.StatExit1, x);
1494 ASMSetFlags(uOldEFlags);
1495#ifdef VBOX_WITH_VMMR0_DISABLE_PREEMPTION
1496 uOldEFlags = ~(RTCCUINTREG)0;
1497#endif
1498
1499 /*
1500 * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
1501 * 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
1502 * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
1503 */
1504
1505 /* Reason for the VM exit */
1506 exitCode = pVMCB->ctrl.u64ExitCode;
1507
1508 if (RT_UNLIKELY(exitCode == (uint64_t)SVM_EXIT_INVALID)) /* Invalid guest state. */
1509 {
1510 HWACCMDumpRegs(pVM, pVCpu, pCtx);
1511#ifdef DEBUG
1512 Log(("ctrl.u16InterceptRdCRx %x\n", pVMCB->ctrl.u16InterceptRdCRx));
1513 Log(("ctrl.u16InterceptWrCRx %x\n", pVMCB->ctrl.u16InterceptWrCRx));
1514 Log(("ctrl.u16InterceptRdDRx %x\n", pVMCB->ctrl.u16InterceptRdDRx));
1515 Log(("ctrl.u16InterceptWrDRx %x\n", pVMCB->ctrl.u16InterceptWrDRx));
1516 Log(("ctrl.u32InterceptException %x\n", pVMCB->ctrl.u32InterceptException));
1517 Log(("ctrl.u32InterceptCtrl1 %x\n", pVMCB->ctrl.u32InterceptCtrl1));
1518 Log(("ctrl.u32InterceptCtrl2 %x\n", pVMCB->ctrl.u32InterceptCtrl2));
1519 Log(("ctrl.u64IOPMPhysAddr %RX64\n", pVMCB->ctrl.u64IOPMPhysAddr));
1520 Log(("ctrl.u64MSRPMPhysAddr %RX64\n", pVMCB->ctrl.u64MSRPMPhysAddr));
1521 Log(("ctrl.u64TSCOffset %RX64\n", pVMCB->ctrl.u64TSCOffset));
1522
1523 Log(("ctrl.TLBCtrl.u32ASID %x\n", pVMCB->ctrl.TLBCtrl.n.u32ASID));
1524 Log(("ctrl.TLBCtrl.u8TLBFlush %x\n", pVMCB->ctrl.TLBCtrl.n.u8TLBFlush));
1525 Log(("ctrl.TLBCtrl.u24Reserved %x\n", pVMCB->ctrl.TLBCtrl.n.u24Reserved));
1526
1527 Log(("ctrl.IntCtrl.u8VTPR %x\n", pVMCB->ctrl.IntCtrl.n.u8VTPR));
1528 Log(("ctrl.IntCtrl.u1VIrqValid %x\n", pVMCB->ctrl.IntCtrl.n.u1VIrqValid));
1529 Log(("ctrl.IntCtrl.u7Reserved %x\n", pVMCB->ctrl.IntCtrl.n.u7Reserved));
1530 Log(("ctrl.IntCtrl.u4VIrqPriority %x\n", pVMCB->ctrl.IntCtrl.n.u4VIrqPriority));
1531 Log(("ctrl.IntCtrl.u1IgnoreTPR %x\n", pVMCB->ctrl.IntCtrl.n.u1IgnoreTPR));
1532 Log(("ctrl.IntCtrl.u3Reserved %x\n", pVMCB->ctrl.IntCtrl.n.u3Reserved));
1533 Log(("ctrl.IntCtrl.u1VIrqMasking %x\n", pVMCB->ctrl.IntCtrl.n.u1VIrqMasking));
1534 Log(("ctrl.IntCtrl.u7Reserved2 %x\n", pVMCB->ctrl.IntCtrl.n.u7Reserved2));
1535 Log(("ctrl.IntCtrl.u8VIrqVector %x\n", pVMCB->ctrl.IntCtrl.n.u8VIrqVector));
1536 Log(("ctrl.IntCtrl.u24Reserved %x\n", pVMCB->ctrl.IntCtrl.n.u24Reserved));
1537
1538 Log(("ctrl.u64IntShadow %RX64\n", pVMCB->ctrl.u64IntShadow));
1539 Log(("ctrl.u64ExitCode %RX64\n", pVMCB->ctrl.u64ExitCode));
1540 Log(("ctrl.u64ExitInfo1 %RX64\n", pVMCB->ctrl.u64ExitInfo1));
1541 Log(("ctrl.u64ExitInfo2 %RX64\n", pVMCB->ctrl.u64ExitInfo2));
1542 Log(("ctrl.ExitIntInfo.u8Vector %x\n", pVMCB->ctrl.ExitIntInfo.n.u8Vector));
1543 Log(("ctrl.ExitIntInfo.u3Type %x\n", pVMCB->ctrl.ExitIntInfo.n.u3Type));
1544 Log(("ctrl.ExitIntInfo.u1ErrorCodeValid %x\n", pVMCB->ctrl.ExitIntInfo.n.u1ErrorCodeValid));
1545 Log(("ctrl.ExitIntInfo.u19Reserved %x\n", pVMCB->ctrl.ExitIntInfo.n.u19Reserved));
1546 Log(("ctrl.ExitIntInfo.u1Valid %x\n", pVMCB->ctrl.ExitIntInfo.n.u1Valid));
1547 Log(("ctrl.ExitIntInfo.u32ErrorCode %x\n", pVMCB->ctrl.ExitIntInfo.n.u32ErrorCode));
1548 Log(("ctrl.NestedPaging %RX64\n", pVMCB->ctrl.NestedPaging.au64));
1549 Log(("ctrl.EventInject.u8Vector %x\n", pVMCB->ctrl.EventInject.n.u8Vector));
1550 Log(("ctrl.EventInject.u3Type %x\n", pVMCB->ctrl.EventInject.n.u3Type));
1551 Log(("ctrl.EventInject.u1ErrorCodeValid %x\n", pVMCB->ctrl.EventInject.n.u1ErrorCodeValid));
1552 Log(("ctrl.EventInject.u19Reserved %x\n", pVMCB->ctrl.EventInject.n.u19Reserved));
1553 Log(("ctrl.EventInject.u1Valid %x\n", pVMCB->ctrl.EventInject.n.u1Valid));
1554 Log(("ctrl.EventInject.u32ErrorCode %x\n", pVMCB->ctrl.EventInject.n.u32ErrorCode));
1555
1556 Log(("ctrl.u64NestedPagingCR3 %RX64\n", pVMCB->ctrl.u64NestedPagingCR3));
1557 Log(("ctrl.u64LBRVirt %RX64\n", pVMCB->ctrl.u64LBRVirt));
1558
1559 Log(("guest.CS.u16Sel %04X\n", pVMCB->guest.CS.u16Sel));
1560 Log(("guest.CS.u16Attr %04X\n", pVMCB->guest.CS.u16Attr));
1561 Log(("guest.CS.u32Limit %X\n", pVMCB->guest.CS.u32Limit));
1562 Log(("guest.CS.u64Base %RX64\n", pVMCB->guest.CS.u64Base));
1563 Log(("guest.DS.u16Sel %04X\n", pVMCB->guest.DS.u16Sel));
1564 Log(("guest.DS.u16Attr %04X\n", pVMCB->guest.DS.u16Attr));
1565 Log(("guest.DS.u32Limit %X\n", pVMCB->guest.DS.u32Limit));
1566 Log(("guest.DS.u64Base %RX64\n", pVMCB->guest.DS.u64Base));
1567 Log(("guest.ES.u16Sel %04X\n", pVMCB->guest.ES.u16Sel));
1568 Log(("guest.ES.u16Attr %04X\n", pVMCB->guest.ES.u16Attr));
1569 Log(("guest.ES.u32Limit %X\n", pVMCB->guest.ES.u32Limit));
1570 Log(("guest.ES.u64Base %RX64\n", pVMCB->guest.ES.u64Base));
1571 Log(("guest.FS.u16Sel %04X\n", pVMCB->guest.FS.u16Sel));
1572 Log(("guest.FS.u16Attr %04X\n", pVMCB->guest.FS.u16Attr));
1573 Log(("guest.FS.u32Limit %X\n", pVMCB->guest.FS.u32Limit));
1574 Log(("guest.FS.u64Base %RX64\n", pVMCB->guest.FS.u64Base));
1575 Log(("guest.GS.u16Sel %04X\n", pVMCB->guest.GS.u16Sel));
1576 Log(("guest.GS.u16Attr %04X\n", pVMCB->guest.GS.u16Attr));
1577 Log(("guest.GS.u32Limit %X\n", pVMCB->guest.GS.u32Limit));
1578 Log(("guest.GS.u64Base %RX64\n", pVMCB->guest.GS.u64Base));
1579
1580 Log(("guest.GDTR.u32Limit %X\n", pVMCB->guest.GDTR.u32Limit));
1581 Log(("guest.GDTR.u64Base %RX64\n", pVMCB->guest.GDTR.u64Base));
1582
1583 Log(("guest.LDTR.u16Sel %04X\n", pVMCB->guest.LDTR.u16Sel));
1584 Log(("guest.LDTR.u16Attr %04X\n", pVMCB->guest.LDTR.u16Attr));
1585 Log(("guest.LDTR.u32Limit %X\n", pVMCB->guest.LDTR.u32Limit));
1586 Log(("guest.LDTR.u64Base %RX64\n", pVMCB->guest.LDTR.u64Base));
1587
1588 Log(("guest.IDTR.u32Limit %X\n", pVMCB->guest.IDTR.u32Limit));
1589 Log(("guest.IDTR.u64Base %RX64\n", pVMCB->guest.IDTR.u64Base));
1590
1591 Log(("guest.TR.u16Sel %04X\n", pVMCB->guest.TR.u16Sel));
1592 Log(("guest.TR.u16Attr %04X\n", pVMCB->guest.TR.u16Attr));
1593 Log(("guest.TR.u32Limit %X\n", pVMCB->guest.TR.u32Limit));
1594 Log(("guest.TR.u64Base %RX64\n", pVMCB->guest.TR.u64Base));
1595
1596 Log(("guest.u8CPL %X\n", pVMCB->guest.u8CPL));
1597 Log(("guest.u64CR0 %RX64\n", pVMCB->guest.u64CR0));
1598 Log(("guest.u64CR2 %RX64\n", pVMCB->guest.u64CR2));
1599 Log(("guest.u64CR3 %RX64\n", pVMCB->guest.u64CR3));
1600 Log(("guest.u64CR4 %RX64\n", pVMCB->guest.u64CR4));
1601 Log(("guest.u64DR6 %RX64\n", pVMCB->guest.u64DR6));
1602 Log(("guest.u64DR7 %RX64\n", pVMCB->guest.u64DR7));
1603
1604 Log(("guest.u64RIP %RX64\n", pVMCB->guest.u64RIP));
1605 Log(("guest.u64RSP %RX64\n", pVMCB->guest.u64RSP));
1606 Log(("guest.u64RAX %RX64\n", pVMCB->guest.u64RAX));
1607 Log(("guest.u64RFlags %RX64\n", pVMCB->guest.u64RFlags));
1608
1609 Log(("guest.u64SysEnterCS %RX64\n", pVMCB->guest.u64SysEnterCS));
1610 Log(("guest.u64SysEnterEIP %RX64\n", pVMCB->guest.u64SysEnterEIP));
1611 Log(("guest.u64SysEnterESP %RX64\n", pVMCB->guest.u64SysEnterESP));
1612
1613 Log(("guest.u64EFER %RX64\n", pVMCB->guest.u64EFER));
1614 Log(("guest.u64STAR %RX64\n", pVMCB->guest.u64STAR));
1615 Log(("guest.u64LSTAR %RX64\n", pVMCB->guest.u64LSTAR));
1616 Log(("guest.u64CSTAR %RX64\n", pVMCB->guest.u64CSTAR));
1617 Log(("guest.u64SFMASK %RX64\n", pVMCB->guest.u64SFMASK));
1618 Log(("guest.u64KernelGSBase %RX64\n", pVMCB->guest.u64KernelGSBase));
1619 Log(("guest.u64GPAT %RX64\n", pVMCB->guest.u64GPAT));
1620 Log(("guest.u64DBGCTL %RX64\n", pVMCB->guest.u64DBGCTL));
1621 Log(("guest.u64BR_FROM %RX64\n", pVMCB->guest.u64BR_FROM));
1622 Log(("guest.u64BR_TO %RX64\n", pVMCB->guest.u64BR_TO));
1623 Log(("guest.u64LASTEXCPFROM %RX64\n", pVMCB->guest.u64LASTEXCPFROM));
1624 Log(("guest.u64LASTEXCPTO %RX64\n", pVMCB->guest.u64LASTEXCPTO));
1625#endif
1626 rc = VERR_SVM_UNABLE_TO_START_VM;
1627 VMMR0LogFlushEnable(pVCpu);
1628 goto end;
1629 }
1630
1631 /* Let's first sync back EIP, ESP, and EFLAGS. */
1632 pCtx->rip = pVMCB->guest.u64RIP;
1633 pCtx->rsp = pVMCB->guest.u64RSP;
1634 pCtx->eflags.u32 = pVMCB->guest.u64RFlags;
1635 /* eax is saved/restore across the vmrun instruction */
1636 pCtx->rax = pVMCB->guest.u64RAX;
1637
1638 /*
1639 * Save all the MSRs that can be changed by the guest without causing a world switch.
1640 * FS & GS base are saved with SVM_READ_SELREG.
1641 */
1642 pCtx->msrSTAR = pVMCB->guest.u64STAR; /* legacy syscall eip, cs & ss */
1643 pCtx->msrLSTAR = pVMCB->guest.u64LSTAR; /* 64-bit mode syscall rip */
1644 pCtx->msrCSTAR = pVMCB->guest.u64CSTAR; /* compatibility mode syscall rip */
1645 pCtx->msrSFMASK = pVMCB->guest.u64SFMASK; /* syscall flag mask */
1646 pCtx->msrKERNELGSBASE = pVMCB->guest.u64KernelGSBase; /* swapgs exchange value */
1647 pCtx->SysEnter.cs = pVMCB->guest.u64SysEnterCS;
1648 pCtx->SysEnter.eip = pVMCB->guest.u64SysEnterEIP;
1649 pCtx->SysEnter.esp = pVMCB->guest.u64SysEnterESP;
1650
1651 /* Can be updated behind our back in the nested paging case. */
1652 pCtx->cr2 = pVMCB->guest.u64CR2;
1653
1654 /* Guest CPU context: ES, CS, SS, DS, FS, GS. */
1655 SVM_READ_SELREG(SS, ss);
1656 SVM_READ_SELREG(CS, cs);
1657 SVM_READ_SELREG(DS, ds);
1658 SVM_READ_SELREG(ES, es);
1659 SVM_READ_SELREG(FS, fs);
1660 SVM_READ_SELREG(GS, gs);
1661
1662 /*
1663 * Correct the hidden CS granularity flag. Haven't seen it being wrong in any other
1664 * register (yet).
1665 */
1666 if ( !pCtx->cs.Attr.n.u1Granularity
1667 && pCtx->cs.Attr.n.u1Present
1668 && pCtx->cs.u32Limit > UINT32_C(0xfffff))
1669 {
1670 Assert((pCtx->cs.u32Limit & 0xfff) == 0xfff);
1671 pCtx->cs.Attr.n.u1Granularity = 1;
1672 }
1673#define SVM_ASSERT_SEL_GRANULARITY(reg) \
1674 AssertMsg( !pCtx->reg.Attr.n.u1Present \
1675 || ( pCtx->reg.Attr.n.u1Granularity \
1676 ? (pCtx->reg.u32Limit & 0xfff) == 0xfff \
1677 : pCtx->reg.u32Limit <= 0xfffff), \
1678 ("%#x %#x %#llx\n", pCtx->reg.u32Limit, pCtx->reg.Attr.u, pCtx->reg.u64Base))
1679 SVM_ASSERT_SEL_GRANULARITY(ss);
1680 SVM_ASSERT_SEL_GRANULARITY(cs);
1681 SVM_ASSERT_SEL_GRANULARITY(ds);
1682 SVM_ASSERT_SEL_GRANULARITY(es);
1683 SVM_ASSERT_SEL_GRANULARITY(fs);
1684 SVM_ASSERT_SEL_GRANULARITY(gs);
1685#undef SVM_ASSERT_SEL_GRANULARITY
1686
1687 /*
1688 * Correct the hidden SS DPL field. It can be wrong on certain CPUs
1689 * sometimes (seen it on AMD Fusion CPUs with 64-bit guests). The CPU
1690 * always uses the CPL field in the VMCB instead of the DPL in the hidden
1691 * SS (chapter AMD spec. 15.5.1 Basic operation).
1692 */
1693 Assert(!(pVMCB->guest.u8CPL & ~0x3));
1694 pCtx->ss.Attr.n.u2Dpl = pVMCB->guest.u8CPL & 0x3;
1695
1696 /*
1697 * Remaining guest CPU context: TR, IDTR, GDTR, LDTR;
1698 * must sync everything otherwise we can get out of sync when jumping back to ring-3.
1699 */
1700 SVM_READ_SELREG(LDTR, ldtr);
1701 SVM_READ_SELREG(TR, tr);
1702
1703 pCtx->gdtr.cbGdt = pVMCB->guest.GDTR.u32Limit;
1704 pCtx->gdtr.pGdt = pVMCB->guest.GDTR.u64Base;
1705
1706 pCtx->idtr.cbIdt = pVMCB->guest.IDTR.u32Limit;
1707 pCtx->idtr.pIdt = pVMCB->guest.IDTR.u64Base;
1708
1709 /*
1710 * No reason to sync back the CRx and DRx registers as they cannot be changed by the guest
1711 * unless in the nested paging case where CR3 can be changed by the guest.
1712 */
1713 if ( pVM->hwaccm.s.fNestedPaging
1714 && pCtx->cr3 != pVMCB->guest.u64CR3)
1715 {
1716 CPUMSetGuestCR3(pVCpu, pVMCB->guest.u64CR3);
1717 PGMUpdateCR3(pVCpu, pVMCB->guest.u64CR3);
1718 }
1719
1720 /* Note! NOW IT'S SAFE FOR LOGGING! */
1721 VMMR0LogFlushEnable(pVCpu);
1722
1723 /* Take care of instruction fusing (sti, mov ss) (see AMD spec. 15.20.5 Interrupt Shadows) */
1724 if (pVMCB->ctrl.u64IntShadow & SVM_INTERRUPT_SHADOW_ACTIVE)
1725 {
1726 Log(("uInterruptState %x rip=%RGv\n", pVMCB->ctrl.u64IntShadow, (RTGCPTR)pCtx->rip));
1727 EMSetInhibitInterruptsPC(pVCpu, pCtx->rip);
1728 }
1729 else
1730 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_INHIBIT_INTERRUPTS);
1731
1732 Log2(("exitCode = %x\n", exitCode));
1733
1734 /* Sync back DR6 as it could have been changed by hitting breakpoints. */
1735 pCtx->dr[6] = pVMCB->guest.u64DR6;
1736 /* DR7.GD can be cleared by debug exceptions, so sync it back as well. */
1737 pCtx->dr[7] = pVMCB->guest.u64DR7;
1738
1739 /* Check if an injected event was interrupted prematurely. */
1740 pVCpu->hwaccm.s.Event.intInfo = pVMCB->ctrl.ExitIntInfo.au64[0];
1741 if ( pVMCB->ctrl.ExitIntInfo.n.u1Valid
1742 /* we don't care about 'int xx' as the instruction will be restarted. */
1743 && pVMCB->ctrl.ExitIntInfo.n.u3Type != SVM_EVENT_SOFTWARE_INT)
1744 {
1745 Log(("Pending inject %RX64 at %RGv exit=%08x\n", pVCpu->hwaccm.s.Event.intInfo, (RTGCPTR)pCtx->rip, exitCode));
1746
1747#ifdef LOG_ENABLED
1748 SVM_EVENT Event;
1749 Event.au64[0] = pVCpu->hwaccm.s.Event.intInfo;
1750
1751 if ( exitCode == SVM_EXIT_EXCEPTION_E
1752 && Event.n.u8Vector == 0xE)
1753 {
1754 Log(("Double fault!\n"));
1755 }
1756#endif
1757
1758 pVCpu->hwaccm.s.Event.fPending = true;
1759 /* Error code present? (redundant) */
1760 if (pVMCB->ctrl.ExitIntInfo.n.u1ErrorCodeValid)
1761 pVCpu->hwaccm.s.Event.errCode = pVMCB->ctrl.ExitIntInfo.n.u32ErrorCode;
1762 else
1763 pVCpu->hwaccm.s.Event.errCode = 0;
1764 }
1765#ifdef VBOX_WITH_STATISTICS
1766 if (exitCode == SVM_EXIT_NPF)
1767 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitReasonNPF);
1768 else
1769 STAM_COUNTER_INC(&pVCpu->hwaccm.s.paStatExitReasonR0[exitCode & MASK_EXITREASON_STAT]);
1770#endif
1771
1772 /* Sync back the TPR if it was changed. */
1773 if (fSyncTPR)
1774 {
1775 if (pVM->hwaccm.s.fTPRPatchingActive)
1776 {
1777 if ((pCtx->msrLSTAR & 0xff) != u8LastTPR)
1778 {
1779 /* Our patch code uses LSTAR for TPR caching. */
1780 rc2 = PDMApicSetTPR(pVCpu, pCtx->msrLSTAR & 0xff);
1781 AssertRC(rc2);
1782 }
1783 }
1784 else
1785 {
1786 if ((uint8_t)(u8LastTPR >> 4) != pVMCB->ctrl.IntCtrl.n.u8VTPR)
1787 {
1788 /* cr8 bits 3-0 correspond to bits 7-4 of the task priority mmio register. */
1789 rc2 = PDMApicSetTPR(pVCpu, pVMCB->ctrl.IntCtrl.n.u8VTPR << 4);
1790 AssertRC(rc2);
1791 }
1792 }
1793 }
1794
1795#ifdef DBGFTRACE_ENABLED /** @todo DTrace */
1796 RTTraceBufAddMsgF(pVM->CTX_SUFF(hTraceBuf), "vmexit %08x at %04:%08RX64 %RX64 %RX64 %RX64",
1797 exitCode, pCtx->cs.Sel, pCtx->rip,
1798 pVMCB->ctrl.u64ExitInfo1, pVMCB->ctrl.u64ExitInfo2, pVMCB->ctrl.ExitIntInfo.au64[0]);
1799#endif
1800#if ARCH_BITS == 64 /* for the time being */
1801 VBOXVMM_R0_HMSVM_VMEXIT(pVCpu, pCtx, exitCode, pVMCB->ctrl.u64ExitInfo1, pVMCB->ctrl.u64ExitInfo2,
1802 pVMCB->ctrl.ExitIntInfo.au64[0], UINT64_MAX);
1803#endif
1804 STAM_PROFILE_ADV_STOP_START(&pVCpu->hwaccm.s.StatExit1, &pVCpu->hwaccm.s.StatExit2, x);
1805
1806 /* Deal with the reason of the VM-exit. */
1807 switch (exitCode)
1808 {
1809 case SVM_EXIT_EXCEPTION_0: case SVM_EXIT_EXCEPTION_1: case SVM_EXIT_EXCEPTION_2: case SVM_EXIT_EXCEPTION_3:
1810 case SVM_EXIT_EXCEPTION_4: case SVM_EXIT_EXCEPTION_5: case SVM_EXIT_EXCEPTION_6: case SVM_EXIT_EXCEPTION_7:
1811 case SVM_EXIT_EXCEPTION_8: case SVM_EXIT_EXCEPTION_9: case SVM_EXIT_EXCEPTION_A: case SVM_EXIT_EXCEPTION_B:
1812 case SVM_EXIT_EXCEPTION_C: case SVM_EXIT_EXCEPTION_D: case SVM_EXIT_EXCEPTION_E: case SVM_EXIT_EXCEPTION_F:
1813 case SVM_EXIT_EXCEPTION_10: case SVM_EXIT_EXCEPTION_11: case SVM_EXIT_EXCEPTION_12: case SVM_EXIT_EXCEPTION_13:
1814 case SVM_EXIT_EXCEPTION_14: case SVM_EXIT_EXCEPTION_15: case SVM_EXIT_EXCEPTION_16: case SVM_EXIT_EXCEPTION_17:
1815 case SVM_EXIT_EXCEPTION_18: case SVM_EXIT_EXCEPTION_19: case SVM_EXIT_EXCEPTION_1A: case SVM_EXIT_EXCEPTION_1B:
1816 case SVM_EXIT_EXCEPTION_1C: case SVM_EXIT_EXCEPTION_1D: case SVM_EXIT_EXCEPTION_1E: case SVM_EXIT_EXCEPTION_1F:
1817 {
1818 /* Pending trap. */
1819 SVM_EVENT Event;
1820 uint32_t vector = exitCode - SVM_EXIT_EXCEPTION_0;
1821
1822 Log2(("Hardware/software interrupt %d\n", vector));
1823 switch (vector)
1824 {
1825 case X86_XCPT_DB:
1826 {
1827 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitGuestDB);
1828
1829 /* Note that we don't support guest and host-initiated debugging at the same time. */
1830 Assert(DBGFIsStepping(pVCpu) || CPUMIsHyperDebugStateActive(pVCpu));
1831
1832 rc = DBGFRZTrap01Handler(pVM, pVCpu, CPUMCTX2CORE(pCtx), pCtx->dr[6]);
1833 if (rc == VINF_EM_RAW_GUEST_TRAP)
1834 {
1835 Log(("Trap %x (debug) at %016RX64\n", vector, pCtx->rip));
1836
1837 /* Reinject the exception. */
1838 Event.au64[0] = 0;
1839 Event.n.u3Type = SVM_EVENT_EXCEPTION; /* trap or fault */
1840 Event.n.u1Valid = 1;
1841 Event.n.u8Vector = X86_XCPT_DB;
1842
1843 hmR0SvmInjectEvent(pVCpu, pVMCB, pCtx, &Event);
1844 goto ResumeExecution;
1845 }
1846 /* Return to ring 3 to deal with the debug exit code. */
1847 Log(("Debugger hardware BP at %04x:%RGv (rc=%Rrc)\n", pCtx->cs.Sel, pCtx->rip, VBOXSTRICTRC_VAL(rc)));
1848 break;
1849 }
1850
1851 case X86_XCPT_NM:
1852 {
1853 Log(("#NM fault at %RGv\n", (RTGCPTR)pCtx->rip));
1854
1855 /** @todo don't intercept #NM exceptions anymore when we've activated the guest FPU state. */
1856 /* If we sync the FPU/XMM state on-demand, then we can continue execution as if nothing has happened. */
1857 rc = CPUMR0LoadGuestFPU(pVM, pVCpu, pCtx);
1858 if (rc == VINF_SUCCESS)
1859 {
1860 Assert(CPUMIsGuestFPUStateActive(pVCpu));
1861 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitShadowNM);
1862
1863 /* Continue execution. */
1864 pVCpu->hwaccm.s.fContextUseFlags |= HWACCM_CHANGED_GUEST_CR0;
1865
1866 goto ResumeExecution;
1867 }
1868
1869 Log(("Forward #NM fault to the guest\n"));
1870 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitGuestNM);
1871
1872 Event.au64[0] = 0;
1873 Event.n.u3Type = SVM_EVENT_EXCEPTION;
1874 Event.n.u1Valid = 1;
1875 Event.n.u8Vector = X86_XCPT_NM;
1876
1877 hmR0SvmInjectEvent(pVCpu, pVMCB, pCtx, &Event);
1878 goto ResumeExecution;
1879 }
1880
1881 case X86_XCPT_PF: /* Page fault */
1882 {
1883 uint32_t errCode = pVMCB->ctrl.u64ExitInfo1; /* EXITINFO1 = error code */
1884 RTGCUINTPTR uFaultAddress = pVMCB->ctrl.u64ExitInfo2; /* EXITINFO2 = fault address */
1885
1886#ifdef VBOX_ALWAYS_TRAP_PF
1887 if (pVM->hwaccm.s.fNestedPaging)
1888 {
1889 /*
1890 * A genuine pagefault. Forward the trap to the guest by injecting the exception and resuming execution.
1891 */
1892 Log(("Guest page fault at %04X:%RGv cr2=%RGv error code %x rsp=%RGv\n", pCtx->cs, (RTGCPTR)pCtx->rip,
1893 uFaultAddress, errCode, (RTGCPTR)pCtx->rsp));
1894 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitGuestPF);
1895
1896 /* Now we must update CR2. */
1897 pCtx->cr2 = uFaultAddress;
1898
1899 Event.au64[0] = 0;
1900 Event.n.u3Type = SVM_EVENT_EXCEPTION;
1901 Event.n.u1Valid = 1;
1902 Event.n.u8Vector = X86_XCPT_PF;
1903 Event.n.u1ErrorCodeValid = 1;
1904 Event.n.u32ErrorCode = errCode;
1905
1906 hmR0SvmInjectEvent(pVCpu, pVMCB, pCtx, &Event);
1907 goto ResumeExecution;
1908 }
1909#endif
1910 Assert(!pVM->hwaccm.s.fNestedPaging);
1911
1912#ifdef VBOX_HWACCM_WITH_GUEST_PATCHING
1913 /* Shortcut for APIC TPR reads and writes; 32 bits guests only */
1914 if ( pVM->hwaccm.s.fTRPPatchingAllowed
1915 && (uFaultAddress & 0xfff) == 0x080
1916 && !(errCode & X86_TRAP_PF_P) /* not present */
1917 && CPUMGetGuestCPL(pVCpu) == 0
1918 && !CPUMIsGuestInLongModeEx(pCtx)
1919 && pVM->hwaccm.s.cPatches < RT_ELEMENTS(pVM->hwaccm.s.aPatches))
1920 {
1921 RTGCPHYS GCPhysApicBase, GCPhys;
1922 PDMApicGetBase(pVM, &GCPhysApicBase); /** @todo cache this */
1923 GCPhysApicBase &= PAGE_BASE_GC_MASK;
1924
1925 rc = PGMGstGetPage(pVCpu, (RTGCPTR)uFaultAddress, NULL, &GCPhys);
1926 if ( rc == VINF_SUCCESS
1927 && GCPhys == GCPhysApicBase)
1928 {
1929 /* Only attempt to patch the instruction once. */
1930 PHWACCMTPRPATCH pPatch = (PHWACCMTPRPATCH)RTAvloU32Get(&pVM->hwaccm.s.PatchTree, (AVLOU32KEY)pCtx->eip);
1931 if (!pPatch)
1932 {
1933 rc = VINF_EM_HWACCM_PATCH_TPR_INSTR;
1934 break;
1935 }
1936 }
1937 }
1938#endif
1939
1940 Log2(("Page fault at %RGv cr2=%RGv error code %x\n", (RTGCPTR)pCtx->rip, uFaultAddress, errCode));
1941 /* Exit qualification contains the linear address of the page fault. */
1942 TRPMAssertTrap(pVCpu, X86_XCPT_PF, TRPM_TRAP);
1943 TRPMSetErrorCode(pVCpu, errCode);
1944 TRPMSetFaultAddress(pVCpu, uFaultAddress);
1945
1946 /* Forward it to our trap handler first, in case our shadow pages are out of sync. */
1947 rc = PGMTrap0eHandler(pVCpu, errCode, CPUMCTX2CORE(pCtx), (RTGCPTR)uFaultAddress);
1948 Log2(("PGMTrap0eHandler %RGv returned %Rrc\n", (RTGCPTR)pCtx->rip, VBOXSTRICTRC_VAL(rc)));
1949 if (rc == VINF_SUCCESS)
1950 {
1951 /* We've successfully synced our shadow pages, so let's just continue execution. */
1952 Log2(("Shadow page fault at %RGv cr2=%RGv error code %x\n", (RTGCPTR)pCtx->rip, uFaultAddress, errCode));
1953 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitShadowPF);
1954
1955 TRPMResetTrap(pVCpu);
1956 goto ResumeExecution;
1957 }
1958 else if (rc == VINF_EM_RAW_GUEST_TRAP)
1959 {
1960 /*
1961 * A genuine pagefault. Forward the trap to the guest by injecting the exception and resuming execution.
1962 */
1963 Log2(("Forward page fault to the guest\n"));
1964 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitGuestPF);
1965 /* The error code might have been changed. */
1966 errCode = TRPMGetErrorCode(pVCpu);
1967
1968 TRPMResetTrap(pVCpu);
1969
1970 /* Now we must update CR2. */
1971 pCtx->cr2 = uFaultAddress;
1972
1973 Event.au64[0] = 0;
1974 Event.n.u3Type = SVM_EVENT_EXCEPTION;
1975 Event.n.u1Valid = 1;
1976 Event.n.u8Vector = X86_XCPT_PF;
1977 Event.n.u1ErrorCodeValid = 1;
1978 Event.n.u32ErrorCode = errCode;
1979
1980 hmR0SvmInjectEvent(pVCpu, pVMCB, pCtx, &Event);
1981 goto ResumeExecution;
1982 }
1983#ifdef VBOX_STRICT
1984 if (rc != VINF_EM_RAW_EMULATE_INSTR && rc != VINF_EM_RAW_EMULATE_IO_BLOCK)
1985 LogFlow(("PGMTrap0eHandler failed with %d\n", VBOXSTRICTRC_VAL(rc)));
1986#endif
1987 /* Need to go back to the recompiler to emulate the instruction. */
1988 TRPMResetTrap(pVCpu);
1989 break;
1990 }
1991
1992 case X86_XCPT_MF: /* Floating point exception. */
1993 {
1994 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitGuestMF);
1995 if (!(pCtx->cr0 & X86_CR0_NE))
1996 {
1997 /* old style FPU error reporting needs some extra work. */
1998 /** @todo don't fall back to the recompiler, but do it manually. */
1999 rc = VINF_EM_RAW_EMULATE_INSTR;
2000 break;
2001 }
2002 Log(("Trap %x at %RGv\n", vector, (RTGCPTR)pCtx->rip));
2003
2004 Event.au64[0] = 0;
2005 Event.n.u3Type = SVM_EVENT_EXCEPTION;
2006 Event.n.u1Valid = 1;
2007 Event.n.u8Vector = X86_XCPT_MF;
2008
2009 hmR0SvmInjectEvent(pVCpu, pVMCB, pCtx, &Event);
2010 goto ResumeExecution;
2011 }
2012
2013#ifdef VBOX_STRICT
2014 case X86_XCPT_BP: /* Breakpoint. */
2015 case X86_XCPT_GP: /* General protection failure exception.*/
2016 case X86_XCPT_UD: /* Unknown opcode exception. */
2017 case X86_XCPT_DE: /* Divide error. */
2018 case X86_XCPT_SS: /* Stack segment exception. */
2019 case X86_XCPT_NP: /* Segment not present exception. */
2020 {
2021 Event.au64[0] = 0;
2022 Event.n.u3Type = SVM_EVENT_EXCEPTION;
2023 Event.n.u1Valid = 1;
2024 Event.n.u8Vector = vector;
2025
2026 switch (vector)
2027 {
2028 case X86_XCPT_GP:
2029 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitGuestGP);
2030 Event.n.u1ErrorCodeValid = 1;
2031 Event.n.u32ErrorCode = pVMCB->ctrl.u64ExitInfo1; /* EXITINFO1 = error code */
2032 break;
2033 case X86_XCPT_BP:
2034 /** Saves the wrong EIP on the stack (pointing to the int3 instead of the next instruction. */
2035 break;
2036 case X86_XCPT_DE:
2037 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitGuestDE);
2038 break;
2039 case X86_XCPT_UD:
2040 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitGuestUD);
2041 break;
2042 case X86_XCPT_SS:
2043 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitGuestSS);
2044 Event.n.u1ErrorCodeValid = 1;
2045 Event.n.u32ErrorCode = pVMCB->ctrl.u64ExitInfo1; /* EXITINFO1 = error code */
2046 break;
2047 case X86_XCPT_NP:
2048 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitGuestNP);
2049 Event.n.u1ErrorCodeValid = 1;
2050 Event.n.u32ErrorCode = pVMCB->ctrl.u64ExitInfo1; /* EXITINFO1 = error code */
2051 break;
2052 }
2053 Log(("Trap %x at %04x:%RGv esi=%x\n", vector, pCtx->cs.Sel, (RTGCPTR)pCtx->rip, pCtx->esi));
2054 hmR0SvmInjectEvent(pVCpu, pVMCB, pCtx, &Event);
2055 goto ResumeExecution;
2056 }
2057#endif
2058 default:
2059 AssertMsgFailed(("Unexpected vm-exit caused by exception %x\n", vector));
2060 rc = VERR_HMSVM_UNEXPECTED_XCPT_EXIT;
2061 break;
2062
2063 } /* switch (vector) */
2064 break;
2065 }
2066
2067 case SVM_EXIT_NPF:
2068 {
2069 /* EXITINFO1 contains fault errorcode; EXITINFO2 contains the guest physical address causing the fault. */
2070 uint32_t errCode = pVMCB->ctrl.u64ExitInfo1; /* EXITINFO1 = error code */
2071 RTGCPHYS GCPhysFault = pVMCB->ctrl.u64ExitInfo2; /* EXITINFO2 = fault address */
2072 PGMMODE enmShwPagingMode;
2073
2074 Assert(pVM->hwaccm.s.fNestedPaging);
2075 LogFlow(("Nested page fault at %RGv cr2=%RGp error code %x\n", (RTGCPTR)pCtx->rip, GCPhysFault, errCode));
2076
2077#ifdef VBOX_HWACCM_WITH_GUEST_PATCHING
2078 /* Shortcut for APIC TPR reads and writes; 32 bits guests only */
2079 if ( pVM->hwaccm.s.fTRPPatchingAllowed
2080 && (GCPhysFault & PAGE_OFFSET_MASK) == 0x080
2081 && ( !(errCode & X86_TRAP_PF_P) /* not present */
2082 || (errCode & (X86_TRAP_PF_P | X86_TRAP_PF_RSVD)) == (X86_TRAP_PF_P | X86_TRAP_PF_RSVD) /* mmio optimization */)
2083 && CPUMGetGuestCPL(pVCpu) == 0
2084 && !CPUMIsGuestInLongModeEx(pCtx)
2085 && pVM->hwaccm.s.cPatches < RT_ELEMENTS(pVM->hwaccm.s.aPatches))
2086 {
2087 RTGCPHYS GCPhysApicBase;
2088 PDMApicGetBase(pVM, &GCPhysApicBase); /** @todo cache this */
2089 GCPhysApicBase &= PAGE_BASE_GC_MASK;
2090
2091 if (GCPhysFault == GCPhysApicBase + 0x80)
2092 {
2093 /* Only attempt to patch the instruction once. */
2094 PHWACCMTPRPATCH pPatch = (PHWACCMTPRPATCH)RTAvloU32Get(&pVM->hwaccm.s.PatchTree, (AVLOU32KEY)pCtx->eip);
2095 if (!pPatch)
2096 {
2097 rc = VINF_EM_HWACCM_PATCH_TPR_INSTR;
2098 break;
2099 }
2100 }
2101 }
2102#endif
2103
2104 /* Handle the pagefault trap for the nested shadow table. */
2105#if HC_ARCH_BITS == 32 /** @todo shadow this in a variable. */
2106 if (CPUMIsGuestInLongModeEx(pCtx))
2107 enmShwPagingMode = PGMMODE_AMD64_NX;
2108 else
2109#endif
2110 enmShwPagingMode = PGMGetHostMode(pVM);
2111
2112 /* MMIO optimization */
2113 Assert((errCode & (X86_TRAP_PF_RSVD | X86_TRAP_PF_P)) != X86_TRAP_PF_RSVD);
2114 if ((errCode & (X86_TRAP_PF_RSVD | X86_TRAP_PF_P)) == (X86_TRAP_PF_RSVD | X86_TRAP_PF_P))
2115 {
2116 rc = PGMR0Trap0eHandlerNPMisconfig(pVM, pVCpu, enmShwPagingMode, CPUMCTX2CORE(pCtx), GCPhysFault, errCode);
2117
2118 /*
2119 * If we succeed, resume execution.
2120 * Or, if fail in interpreting the instruction because we couldn't get the guest physical address
2121 * of the page containing the instruction via the guest's page tables (we would invalidate the guest page
2122 * in the host TLB), resume execution which would cause a guest page fault to let the guest handle this
2123 * weird case. See @bugref{6043}.
2124 */
2125 if ( rc == VINF_SUCCESS
2126 || rc == VERR_PAGE_TABLE_NOT_PRESENT
2127 || rc == VERR_PAGE_NOT_PRESENT)
2128 {
2129 Log2(("PGMR0Trap0eHandlerNPMisconfig(,,,%RGp) at %RGv -> resume\n", GCPhysFault, (RTGCPTR)pCtx->rip));
2130 goto ResumeExecution;
2131 }
2132 Log2(("PGMR0Trap0eHandlerNPMisconfig(,,,%RGp) at %RGv -> resume\n", GCPhysFault, (RTGCPTR)pCtx->rip));
2133 break;
2134 }
2135
2136 /* Exit qualification contains the linear address of the page fault. */
2137 TRPMAssertTrap(pVCpu, X86_XCPT_PF, TRPM_TRAP);
2138 TRPMSetErrorCode(pVCpu, errCode);
2139 TRPMSetFaultAddress(pVCpu, GCPhysFault);
2140
2141 rc = PGMR0Trap0eHandlerNestedPaging(pVM, pVCpu, enmShwPagingMode, errCode, CPUMCTX2CORE(pCtx), GCPhysFault);
2142 Log2(("PGMR0Trap0eHandlerNestedPaging %RGv returned %Rrc\n", (RTGCPTR)pCtx->rip, VBOXSTRICTRC_VAL(rc)));
2143
2144 /*
2145 * Same case as PGMR0Trap0eHandlerNPMisconfig(). See comment above, @bugref{6043}.
2146 */
2147 if ( rc == VINF_SUCCESS
2148 || rc == VERR_PAGE_TABLE_NOT_PRESENT
2149 || rc == VERR_PAGE_NOT_PRESENT)
2150 {
2151 /* We've successfully synced our shadow pages, so let's just continue execution. */
2152 Log2(("Shadow page fault at %RGv cr2=%RGp error code %x\n", (RTGCPTR)pCtx->rip, GCPhysFault, errCode));
2153 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitShadowPF);
2154
2155 TRPMResetTrap(pVCpu);
2156 goto ResumeExecution;
2157 }
2158
2159#ifdef VBOX_STRICT
2160 if (rc != VINF_EM_RAW_EMULATE_INSTR)
2161 LogFlow(("PGMTrap0eHandlerNestedPaging failed with %d\n", VBOXSTRICTRC_VAL(rc)));
2162#endif
2163 /* Need to go back to the recompiler to emulate the instruction. */
2164 TRPMResetTrap(pVCpu);
2165 break;
2166 }
2167
2168 case SVM_EXIT_VINTR:
2169 /* A virtual interrupt is about to be delivered, which means IF=1. */
2170 Log(("SVM_EXIT_VINTR IF=%d\n", pCtx->eflags.Bits.u1IF));
2171 pVMCB->ctrl.IntCtrl.n.u1VIrqValid = 0;
2172 pVMCB->ctrl.IntCtrl.n.u8VIrqVector = 0;
2173 goto ResumeExecution;
2174
2175 case SVM_EXIT_FERR_FREEZE:
2176 case SVM_EXIT_INTR:
2177 case SVM_EXIT_NMI:
2178 case SVM_EXIT_SMI:
2179 case SVM_EXIT_INIT:
2180 /* External interrupt; leave to allow it to be dispatched again. */
2181 rc = VINF_EM_RAW_INTERRUPT;
2182 break;
2183
2184 case SVM_EXIT_WBINVD:
2185 case SVM_EXIT_INVD: /* Guest software attempted to execute INVD. */
2186 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitInvd);
2187 /* Skip instruction and continue directly. */
2188 pCtx->rip += 2; /* Note! hardcoded opcode size! */
2189 /* Continue execution.*/
2190 goto ResumeExecution;
2191
2192 case SVM_EXIT_CPUID: /* Guest software attempted to execute CPUID. */
2193 {
2194 Log2(("SVM: Cpuid at %RGv for %x\n", (RTGCPTR)pCtx->rip, pCtx->eax));
2195 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitCpuid);
2196 rc = EMInterpretCpuId(pVM, pVCpu, CPUMCTX2CORE(pCtx));
2197 if (rc == VINF_SUCCESS)
2198 {
2199 /* Update EIP and continue execution. */
2200 pCtx->rip += 2; /* Note! hardcoded opcode size! */
2201 goto ResumeExecution;
2202 }
2203 AssertMsgFailed(("EMU: cpuid failed with %Rrc\n", VBOXSTRICTRC_VAL(rc)));
2204 rc = VINF_EM_RAW_EMULATE_INSTR;
2205 break;
2206 }
2207
2208 case SVM_EXIT_RDTSC: /* Guest software attempted to execute RDTSC. */
2209 {
2210 Log2(("SVM: Rdtsc\n"));
2211 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitRdtsc);
2212 rc = EMInterpretRdtsc(pVM, pVCpu, CPUMCTX2CORE(pCtx));
2213 if (rc == VINF_SUCCESS)
2214 {
2215 /* Update EIP and continue execution. */
2216 pCtx->rip += 2; /* Note! hardcoded opcode size! */
2217 goto ResumeExecution;
2218 }
2219 rc = VINF_EM_RAW_EMULATE_INSTR;
2220 break;
2221 }
2222
2223 case SVM_EXIT_RDPMC: /* Guest software attempted to execute RDPMC. */
2224 {
2225 Log2(("SVM: Rdpmc %x\n", pCtx->ecx));
2226 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitRdpmc);
2227 rc = EMInterpretRdpmc(pVM, pVCpu, CPUMCTX2CORE(pCtx));
2228 if (rc == VINF_SUCCESS)
2229 {
2230 /* Update EIP and continue execution. */
2231 pCtx->rip += 2; /* Note! hardcoded opcode size! */
2232 goto ResumeExecution;
2233 }
2234 rc = VINF_EM_RAW_EMULATE_INSTR;
2235 break;
2236 }
2237
2238 case SVM_EXIT_RDTSCP: /* Guest software attempted to execute RDTSCP. */
2239 {
2240 Log2(("SVM: Rdtscp\n"));
2241 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitRdtscp);
2242 rc = EMInterpretRdtscp(pVM, pVCpu, pCtx);
2243 if (rc == VINF_SUCCESS)
2244 {
2245 /* Update EIP and continue execution. */
2246 pCtx->rip += 3; /* Note! hardcoded opcode size! */
2247 goto ResumeExecution;
2248 }
2249 AssertMsgFailed(("EMU: rdtscp failed with %Rrc\n", VBOXSTRICTRC_VAL(rc)));
2250 rc = VINF_EM_RAW_EMULATE_INSTR;
2251 break;
2252 }
2253
2254 case SVM_EXIT_INVLPG: /* Guest software attempted to execute INVLPG. */
2255 {
2256 Log2(("SVM: invlpg\n"));
2257 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitInvlpg);
2258
2259 Assert(!pVM->hwaccm.s.fNestedPaging);
2260
2261 /* Truly a pita. Why can't SVM give the same information as VT-x? */
2262 rc = hmR0SvmInterpretInvlpg(pVM, pVCpu, CPUMCTX2CORE(pCtx));
2263 if (rc == VINF_SUCCESS)
2264 {
2265 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatFlushPageInvlpg);
2266 goto ResumeExecution; /* eip already updated */
2267 }
2268 break;
2269 }
2270
2271 case SVM_EXIT_WRITE_CR0: case SVM_EXIT_WRITE_CR1: case SVM_EXIT_WRITE_CR2: case SVM_EXIT_WRITE_CR3:
2272 case SVM_EXIT_WRITE_CR4: case SVM_EXIT_WRITE_CR5: case SVM_EXIT_WRITE_CR6: case SVM_EXIT_WRITE_CR7:
2273 case SVM_EXIT_WRITE_CR8: case SVM_EXIT_WRITE_CR9: case SVM_EXIT_WRITE_CR10: case SVM_EXIT_WRITE_CR11:
2274 case SVM_EXIT_WRITE_CR12: case SVM_EXIT_WRITE_CR13: case SVM_EXIT_WRITE_CR14: case SVM_EXIT_WRITE_CR15:
2275 {
2276 Log2(("SVM: %RGv mov cr%d, \n", (RTGCPTR)pCtx->rip, exitCode - SVM_EXIT_WRITE_CR0));
2277 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitCRxWrite[exitCode - SVM_EXIT_WRITE_CR0]);
2278 rc = EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0);
2279
2280 switch (exitCode - SVM_EXIT_WRITE_CR0)
2281 {
2282 case 0:
2283 pVCpu->hwaccm.s.fContextUseFlags |= HWACCM_CHANGED_GUEST_CR0;
2284 break;
2285 case 2:
2286 break;
2287 case 3:
2288 Assert(!pVM->hwaccm.s.fNestedPaging);
2289 pVCpu->hwaccm.s.fContextUseFlags |= HWACCM_CHANGED_GUEST_CR3;
2290 break;
2291 case 4:
2292 pVCpu->hwaccm.s.fContextUseFlags |= HWACCM_CHANGED_GUEST_CR4;
2293 break;
2294 case 8:
2295 break;
2296 default:
2297 AssertFailed();
2298 }
2299 if (rc == VINF_SUCCESS)
2300 {
2301 /* EIP has been updated already. */
2302 /* Only resume if successful. */
2303 goto ResumeExecution;
2304 }
2305 Assert(rc == VERR_EM_INTERPRETER || rc == VINF_PGM_CHANGE_MODE || rc == VINF_PGM_SYNC_CR3);
2306 break;
2307 }
2308
2309 case SVM_EXIT_READ_CR0: case SVM_EXIT_READ_CR1: case SVM_EXIT_READ_CR2: case SVM_EXIT_READ_CR3:
2310 case SVM_EXIT_READ_CR4: case SVM_EXIT_READ_CR5: case SVM_EXIT_READ_CR6: case SVM_EXIT_READ_CR7:
2311 case SVM_EXIT_READ_CR8: case SVM_EXIT_READ_CR9: case SVM_EXIT_READ_CR10: case SVM_EXIT_READ_CR11:
2312 case SVM_EXIT_READ_CR12: case SVM_EXIT_READ_CR13: case SVM_EXIT_READ_CR14: case SVM_EXIT_READ_CR15:
2313 {
2314 Log2(("SVM: %RGv mov x, cr%d\n", (RTGCPTR)pCtx->rip, exitCode - SVM_EXIT_READ_CR0));
2315 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitCRxRead[exitCode - SVM_EXIT_READ_CR0]);
2316 rc = EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0);
2317 if (rc == VINF_SUCCESS)
2318 {
2319 /* EIP has been updated already. */
2320 /* Only resume if successful. */
2321 goto ResumeExecution;
2322 }
2323 Assert(rc == VERR_EM_INTERPRETER || rc == VINF_PGM_CHANGE_MODE || rc == VINF_PGM_SYNC_CR3);
2324 break;
2325 }
2326
2327 case SVM_EXIT_WRITE_DR0: case SVM_EXIT_WRITE_DR1: case SVM_EXIT_WRITE_DR2: case SVM_EXIT_WRITE_DR3:
2328 case SVM_EXIT_WRITE_DR4: case SVM_EXIT_WRITE_DR5: case SVM_EXIT_WRITE_DR6: case SVM_EXIT_WRITE_DR7:
2329 case SVM_EXIT_WRITE_DR8: case SVM_EXIT_WRITE_DR9: case SVM_EXIT_WRITE_DR10: case SVM_EXIT_WRITE_DR11:
2330 case SVM_EXIT_WRITE_DR12: case SVM_EXIT_WRITE_DR13: case SVM_EXIT_WRITE_DR14: case SVM_EXIT_WRITE_DR15:
2331 {
2332 Log2(("SVM: %RGv mov dr%d, x\n", (RTGCPTR)pCtx->rip, exitCode - SVM_EXIT_WRITE_DR0));
2333 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitDRxWrite);
2334
2335 if ( !DBGFIsStepping(pVCpu)
2336 && !CPUMIsHyperDebugStateActive(pVCpu))
2337 {
2338 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatDRxContextSwitch);
2339
2340 /* Disable drx move intercepts. */
2341 pVMCB->ctrl.u16InterceptRdDRx = 0;
2342 pVMCB->ctrl.u16InterceptWrDRx = 0;
2343
2344 /* Save the host and load the guest debug state. */
2345 rc2 = CPUMR0LoadGuestDebugState(pVM, pVCpu, pCtx, false /* exclude DR6 */);
2346 AssertRC(rc2);
2347 goto ResumeExecution;
2348 }
2349
2350 rc = EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0);
2351 if (rc == VINF_SUCCESS)
2352 {
2353 /* EIP has been updated already. */
2354 pVCpu->hwaccm.s.fContextUseFlags |= HWACCM_CHANGED_GUEST_DEBUG;
2355
2356 /* Only resume if successful. */
2357 goto ResumeExecution;
2358 }
2359 Assert(rc == VERR_EM_INTERPRETER || rc == VINF_PGM_CHANGE_MODE || rc == VINF_PGM_SYNC_CR3);
2360 break;
2361 }
2362
2363 case SVM_EXIT_READ_DR0: case SVM_EXIT_READ_DR1: case SVM_EXIT_READ_DR2: case SVM_EXIT_READ_DR3:
2364 case SVM_EXIT_READ_DR4: case SVM_EXIT_READ_DR5: case SVM_EXIT_READ_DR6: case SVM_EXIT_READ_DR7:
2365 case SVM_EXIT_READ_DR8: case SVM_EXIT_READ_DR9: case SVM_EXIT_READ_DR10: case SVM_EXIT_READ_DR11:
2366 case SVM_EXIT_READ_DR12: case SVM_EXIT_READ_DR13: case SVM_EXIT_READ_DR14: case SVM_EXIT_READ_DR15:
2367 {
2368 Log2(("SVM: %RGv mov x, dr%d\n", (RTGCPTR)pCtx->rip, exitCode - SVM_EXIT_READ_DR0));
2369 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitDRxRead);
2370
2371 if (!DBGFIsStepping(pVCpu))
2372 {
2373 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatDRxContextSwitch);
2374
2375 /* Disable DRx move intercepts. */
2376 pVMCB->ctrl.u16InterceptRdDRx = 0;
2377 pVMCB->ctrl.u16InterceptWrDRx = 0;
2378
2379 /* Save the host and load the guest debug state. */
2380 rc2 = CPUMR0LoadGuestDebugState(pVM, pVCpu, pCtx, false /* exclude DR6 */);
2381 AssertRC(rc2);
2382 goto ResumeExecution;
2383 }
2384
2385 rc = EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0);
2386 if (rc == VINF_SUCCESS)
2387 {
2388 /* EIP has been updated already. */
2389 /* Only resume if successful. */
2390 goto ResumeExecution;
2391 }
2392 Assert(rc == VERR_EM_INTERPRETER || rc == VINF_PGM_CHANGE_MODE || rc == VINF_PGM_SYNC_CR3);
2393 break;
2394 }
2395
2396 /* Note: We'll get a #GP if the IO instruction isn't allowed (IOPL or TSS bitmap); no need to double check. */
2397 case SVM_EXIT_IOIO: /* I/O instruction. */
2398 {
2399 SVM_IOIO_EXIT IoExitInfo;
2400
2401 IoExitInfo.au32[0] = pVMCB->ctrl.u64ExitInfo1;
2402 unsigned uIdx = (IoExitInfo.au32[0] >> 4) & 0x7;
2403 uint32_t uIOSize = g_aIOSize[uIdx];
2404 uint32_t uAndVal = g_aIOOpAnd[uIdx];
2405 if (RT_UNLIKELY(!uIOSize))
2406 {
2407 AssertFailed(); /* should be fatal. */
2408 rc = VINF_EM_RAW_EMULATE_INSTR; /** @todo r=ramshankar: would this really fall back to the recompiler and work? */
2409 break;
2410 }
2411
2412 if (IoExitInfo.n.u1STR)
2413 {
2414 /* ins/outs */
2415 PDISCPUSTATE pDis = &pVCpu->hwaccm.s.DisState;
2416
2417 /* Disassemble manually to deal with segment prefixes. */
2418 rc = EMInterpretDisasCurrent(pVM, pVCpu, pDis, NULL);
2419 if (rc == VINF_SUCCESS)
2420 {
2421 if (IoExitInfo.n.u1Type == 0)
2422 {
2423 Log2(("IOMInterpretOUTSEx %RGv %x size=%d\n", (RTGCPTR)pCtx->rip, IoExitInfo.n.u16Port, uIOSize));
2424 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitIOStringWrite);
2425 rc = IOMInterpretOUTSEx(pVM, CPUMCTX2CORE(pCtx), IoExitInfo.n.u16Port, pDis->fPrefix,
2426 (DISCPUMODE)pDis->uAddrMode, uIOSize);
2427 }
2428 else
2429 {
2430 Log2(("IOMInterpretINSEx %RGv %x size=%d\n", (RTGCPTR)pCtx->rip, IoExitInfo.n.u16Port, uIOSize));
2431 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitIOStringRead);
2432 rc = IOMInterpretINSEx(pVM, CPUMCTX2CORE(pCtx), IoExitInfo.n.u16Port, pDis->fPrefix,
2433 (DISCPUMODE)pDis->uAddrMode, uIOSize);
2434 }
2435 }
2436 else
2437 rc = VINF_EM_RAW_EMULATE_INSTR;
2438 }
2439 else
2440 {
2441 /* Normal in/out */
2442 Assert(!IoExitInfo.n.u1REP);
2443
2444 if (IoExitInfo.n.u1Type == 0)
2445 {
2446 Log2(("IOMIOPortWrite %RGv %x %x size=%d\n", (RTGCPTR)pCtx->rip, IoExitInfo.n.u16Port, pCtx->eax & uAndVal,
2447 uIOSize));
2448 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitIOWrite);
2449 rc = IOMIOPortWrite(pVM, IoExitInfo.n.u16Port, pCtx->eax & uAndVal, uIOSize);
2450 if (rc == VINF_IOM_R3_IOPORT_WRITE)
2451 {
2452 HWACCMR0SavePendingIOPortWrite(pVCpu, pCtx->rip, pVMCB->ctrl.u64ExitInfo2, IoExitInfo.n.u16Port,
2453 uAndVal, uIOSize);
2454 }
2455 }
2456 else
2457 {
2458 uint32_t u32Val = 0;
2459
2460 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitIORead);
2461 rc = IOMIOPortRead(pVM, IoExitInfo.n.u16Port, &u32Val, uIOSize);
2462 if (IOM_SUCCESS(rc))
2463 {
2464 /* Write back to the EAX register. */
2465 pCtx->eax = (pCtx->eax & ~uAndVal) | (u32Val & uAndVal);
2466 Log2(("IOMIOPortRead %RGv %x %x size=%d\n", (RTGCPTR)pCtx->rip, IoExitInfo.n.u16Port, u32Val & uAndVal,
2467 uIOSize));
2468 }
2469 else if (rc == VINF_IOM_R3_IOPORT_READ)
2470 {
2471 HWACCMR0SavePendingIOPortRead(pVCpu, pCtx->rip, pVMCB->ctrl.u64ExitInfo2, IoExitInfo.n.u16Port,
2472 uAndVal, uIOSize);
2473 }
2474 }
2475 }
2476
2477 /*
2478 * Handled the I/O return codes.
2479 * (The unhandled cases end up with rc == VINF_EM_RAW_EMULATE_INSTR.)
2480 */
2481 if (IOM_SUCCESS(rc))
2482 {
2483 /* Update EIP and continue execution. */
2484 pCtx->rip = pVMCB->ctrl.u64ExitInfo2; /* RIP/EIP of the next instruction is saved in EXITINFO2. */
2485 if (RT_LIKELY(rc == VINF_SUCCESS))
2486 {
2487 /* If any IO breakpoints are armed, then we should check if a debug trap needs to be generated. */
2488 if (pCtx->dr[7] & X86_DR7_ENABLED_MASK)
2489 {
2490 /* IO operation lookup arrays. */
2491 static uint32_t const aIOSize[4] = { 1, 2, 0, 4 };
2492
2493 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatDRxIOCheck);
2494 for (unsigned i = 0; i < 4; i++)
2495 {
2496 unsigned uBPLen = aIOSize[X86_DR7_GET_LEN(pCtx->dr[7], i)];
2497
2498 if ( (IoExitInfo.n.u16Port >= pCtx->dr[i] && IoExitInfo.n.u16Port < pCtx->dr[i] + uBPLen)
2499 && (pCtx->dr[7] & (X86_DR7_L(i) | X86_DR7_G(i)))
2500 && (pCtx->dr[7] & X86_DR7_RW(i, X86_DR7_RW_IO)) == X86_DR7_RW(i, X86_DR7_RW_IO))
2501 {
2502 SVM_EVENT Event;
2503
2504 Assert(CPUMIsGuestDebugStateActive(pVCpu));
2505
2506 /* Clear all breakpoint status flags and set the one we just hit. */
2507 pCtx->dr[6] &= ~(X86_DR6_B0|X86_DR6_B1|X86_DR6_B2|X86_DR6_B3);
2508 pCtx->dr[6] |= (uint64_t)RT_BIT(i);
2509
2510 /*
2511 * Note: AMD64 Architecture Programmer's Manual 13.1:
2512 * Bits 15:13 of the DR6 register is never cleared by the processor and must be cleared
2513 * by software after the contents have been read.
2514 */
2515 pVMCB->guest.u64DR6 = pCtx->dr[6];
2516
2517 /* X86_DR7_GD will be cleared if drx accesses should be trapped inside the guest. */
2518 pCtx->dr[7] &= ~X86_DR7_GD;
2519
2520 /* Paranoia. */
2521 pCtx->dr[7] &= 0xffffffff; /* upper 32 bits reserved */
2522 pCtx->dr[7] &= ~(RT_BIT(11) | RT_BIT(12) | RT_BIT(14) | RT_BIT(15)); /* must be zero */
2523 pCtx->dr[7] |= 0x400; /* must be one */
2524
2525 pVMCB->guest.u64DR7 = pCtx->dr[7];
2526
2527 /* Inject the exception. */
2528 Log(("Inject IO debug trap at %RGv\n", (RTGCPTR)pCtx->rip));
2529
2530 Event.au64[0] = 0;
2531 Event.n.u3Type = SVM_EVENT_EXCEPTION; /* trap or fault */
2532 Event.n.u1Valid = 1;
2533 Event.n.u8Vector = X86_XCPT_DB;
2534
2535 hmR0SvmInjectEvent(pVCpu, pVMCB, pCtx, &Event);
2536 goto ResumeExecution;
2537 }
2538 }
2539 }
2540 goto ResumeExecution;
2541 }
2542 Log2(("EM status from IO at %RGv %x size %d: %Rrc\n", (RTGCPTR)pCtx->rip, IoExitInfo.n.u16Port, uIOSize,
2543 VBOXSTRICTRC_VAL(rc)));
2544 break;
2545 }
2546
2547#ifdef VBOX_STRICT
2548 if (rc == VINF_IOM_R3_IOPORT_READ)
2549 Assert(IoExitInfo.n.u1Type != 0);
2550 else if (rc == VINF_IOM_R3_IOPORT_WRITE)
2551 Assert(IoExitInfo.n.u1Type == 0);
2552 else
2553 {
2554 AssertMsg( RT_FAILURE(rc)
2555 || rc == VINF_EM_RAW_EMULATE_INSTR
2556 || rc == VINF_EM_RAW_GUEST_TRAP
2557 || rc == VINF_TRPM_XCPT_DISPATCHED, ("%Rrc\n", VBOXSTRICTRC_VAL(rc)));
2558 }
2559#endif
2560 Log2(("Failed IO at %RGv %x size %d\n", (RTGCPTR)pCtx->rip, IoExitInfo.n.u16Port, uIOSize));
2561 break;
2562 }
2563
2564 case SVM_EXIT_HLT:
2565 /* Check if external interrupts are pending; if so, don't switch back. */
2566 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitHlt);
2567 pCtx->rip++; /* skip hlt */
2568 if (EMShouldContinueAfterHalt(pVCpu, pCtx))
2569 goto ResumeExecution;
2570
2571 rc = VINF_EM_HALT;
2572 break;
2573
2574 case SVM_EXIT_MWAIT_UNCOND:
2575 Log2(("SVM: mwait\n"));
2576 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitMwait);
2577 rc = EMInterpretMWait(pVM, pVCpu, CPUMCTX2CORE(pCtx));
2578 if ( rc == VINF_EM_HALT
2579 || rc == VINF_SUCCESS)
2580 {
2581 /* Update EIP and continue execution. */
2582 pCtx->rip += 3; /* Note: hardcoded opcode size assumption! */
2583
2584 /* Check if external interrupts are pending; if so, don't switch back. */
2585 if ( rc == VINF_SUCCESS
2586 || ( rc == VINF_EM_HALT
2587 && EMShouldContinueAfterHalt(pVCpu, pCtx))
2588 )
2589 goto ResumeExecution;
2590 }
2591 AssertMsg(rc == VERR_EM_INTERPRETER || rc == VINF_EM_HALT, ("EMU: mwait failed with %Rrc\n", VBOXSTRICTRC_VAL(rc)));
2592 break;
2593
2594 case SVM_EXIT_MONITOR:
2595 {
2596 Log2(("SVM: monitor\n"));
2597
2598 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatExitMonitor);
2599 rc = EMInterpretMonitor(pVM, pVCpu, CPUMCTX2CORE(pCtx));
2600 if (rc == VINF_SUCCESS)
2601 {
2602 /* Update EIP and continue execution. */
2603 pCtx->rip += 3; /* Note: hardcoded opcode size assumption! */
2604 goto ResumeExecution;
2605 }
2606 AssertMsg(rc == VERR_EM_INTERPRETER, ("EMU: monitor failed with %Rrc\n", VBOXSTRICTRC_VAL(rc)));
2607 break;
2608 }
2609
2610 case SVM_EXIT_VMMCALL:
2611 rc = hmR0SvmEmulateTprVMMCall(pVM, pVCpu, pCtx);
2612 if (rc == VINF_SUCCESS)
2613 {
2614 goto ResumeExecution; /* rip already updated. */
2615 }
2616 /* no break */
2617
2618 case SVM_EXIT_RSM:
2619 case SVM_EXIT_INVLPGA:
2620 case SVM_EXIT_VMRUN:
2621 case SVM_EXIT_VMLOAD:
2622 case SVM_EXIT_VMSAVE:
2623 case SVM_EXIT_STGI:
2624 case SVM_EXIT_CLGI:
2625 case SVM_EXIT_SKINIT:
2626 {
2627 /* Unsupported instructions. */
2628 SVM_EVENT Event;
2629
2630 Event.au64[0] = 0;
2631 Event.n.u3Type = SVM_EVENT_EXCEPTION;
2632 Event.n.u1Valid = 1;
2633 Event.n.u8Vector = X86_XCPT_UD;
2634
2635 Log(("Forced #UD trap at %RGv\n", (RTGCPTR)pCtx->rip));
2636 hmR0SvmInjectEvent(pVCpu, pVMCB, pCtx, &Event);
2637 goto ResumeExecution;
2638 }
2639
2640 /* Emulate in ring-3. */
2641 case SVM_EXIT_MSR:
2642 {
2643 /* When an interrupt is pending, we'll let MSR_K8_LSTAR writes fault in our TPR patch code. */
2644 if ( pVM->hwaccm.s.fTPRPatchingActive
2645 && pCtx->ecx == MSR_K8_LSTAR
2646 && pVMCB->ctrl.u64ExitInfo1 == 1 /* wrmsr */)
2647 {
2648 if ((pCtx->eax & 0xff) != u8LastTPR)
2649 {
2650 Log(("SVM: Faulting MSR_K8_LSTAR write with new TPR value %x\n", pCtx->eax & 0xff));
2651
2652 /* Our patch code uses LSTAR for TPR caching. */
2653 rc2 = PDMApicSetTPR(pVCpu, pCtx->eax & 0xff);
2654 AssertRC(rc2);
2655 }
2656
2657 /* Skip the instruction and continue. */
2658 pCtx->rip += 2; /* wrmsr = [0F 30] */
2659
2660 /* Only resume if successful. */
2661 goto ResumeExecution;
2662 }
2663
2664 /*
2665 * The Intel spec. claims there's an REX version of RDMSR that's slightly different,
2666 * so we play safe by completely disassembling the instruction.
2667 */
2668 STAM_COUNTER_INC((pVMCB->ctrl.u64ExitInfo1 == 0) ? &pVCpu->hwaccm.s.StatExitRdmsr : &pVCpu->hwaccm.s.StatExitWrmsr);
2669 Log(("SVM: %s\n", (pVMCB->ctrl.u64ExitInfo1 == 0) ? "rdmsr" : "wrmsr"));
2670 rc = EMInterpretInstruction(pVCpu, CPUMCTX2CORE(pCtx), 0);
2671 if (rc == VINF_SUCCESS)
2672 {
2673 /* EIP has been updated already. */
2674 /* Only resume if successful. */
2675 goto ResumeExecution;
2676 }
2677 AssertMsg(rc == VERR_EM_INTERPRETER, ("EMU: %s failed with %Rrc\n", (pVMCB->ctrl.u64ExitInfo1 == 0) ? "rdmsr" : "wrmsr",
2678 VBOXSTRICTRC_VAL(rc)));
2679 break;
2680 }
2681
2682 case SVM_EXIT_TASK_SWITCH: /* too complicated to emulate, so fall back to the recompiler */
2683 Log(("SVM_EXIT_TASK_SWITCH: exit2=%RX64\n", pVMCB->ctrl.u64ExitInfo2));
2684 if ( !(pVMCB->ctrl.u64ExitInfo2 & (SVM_EXIT2_TASK_SWITCH_IRET | SVM_EXIT2_TASK_SWITCH_JMP))
2685 && pVCpu->hwaccm.s.Event.fPending)
2686 {
2687 SVM_EVENT Event;
2688 Event.au64[0] = pVCpu->hwaccm.s.Event.intInfo;
2689
2690 /* Caused by an injected interrupt. */
2691 pVCpu->hwaccm.s.Event.fPending = false;
2692 switch (Event.n.u3Type)
2693 {
2694 case SVM_EVENT_EXTERNAL_IRQ:
2695 case SVM_EVENT_NMI:
2696 Log(("SVM_EXIT_TASK_SWITCH: reassert trap %d\n", Event.n.u8Vector));
2697 Assert(!Event.n.u1ErrorCodeValid);
2698 rc2 = TRPMAssertTrap(pVCpu, Event.n.u8Vector, TRPM_HARDWARE_INT);
2699 AssertRC(rc2);
2700 break;
2701
2702 default:
2703 /* Exceptions and software interrupts can just be restarted. */
2704 break;
2705 }
2706 }
2707 rc = VERR_EM_INTERPRETER;
2708 break;
2709
2710 case SVM_EXIT_PAUSE:
2711 case SVM_EXIT_MWAIT_ARMED:
2712 rc = VERR_EM_INTERPRETER;
2713 break;
2714
2715 case SVM_EXIT_SHUTDOWN:
2716 rc = VINF_EM_RESET; /* Triple fault equals a reset. */
2717 break;
2718
2719 case SVM_EXIT_IDTR_READ:
2720 case SVM_EXIT_GDTR_READ:
2721 case SVM_EXIT_LDTR_READ:
2722 case SVM_EXIT_TR_READ:
2723 case SVM_EXIT_IDTR_WRITE:
2724 case SVM_EXIT_GDTR_WRITE:
2725 case SVM_EXIT_LDTR_WRITE:
2726 case SVM_EXIT_TR_WRITE:
2727 case SVM_EXIT_CR0_SEL_WRITE:
2728 default:
2729 /* Unexpected exit codes. */
2730 rc = VERR_HMSVM_UNEXPECTED_EXIT;
2731 AssertMsgFailed(("Unexpected exit code %x\n", exitCode)); /* Can't happen. */
2732 break;
2733 }
2734
2735end:
2736
2737 /*
2738 * We are now going back to ring-3, so clear the forced action flag.
2739 */
2740 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_TO_R3);
2741
2742 /*
2743 * Signal changes to the recompiler.
2744 */
2745 CPUMSetChangedFlags(pVCpu,
2746 CPUM_CHANGED_SYSENTER_MSR
2747 | CPUM_CHANGED_LDTR
2748 | CPUM_CHANGED_GDTR
2749 | CPUM_CHANGED_IDTR
2750 | CPUM_CHANGED_TR
2751 | CPUM_CHANGED_HIDDEN_SEL_REGS);
2752
2753 /*
2754 * If we executed vmrun and an external IRQ was pending, then we don't have to do a full sync the next time.
2755 */
2756 if (exitCode == SVM_EXIT_INTR)
2757 {
2758 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatPendingHostIrq);
2759 /* On the next entry we'll only sync the host context. */
2760 pVCpu->hwaccm.s.fContextUseFlags |= HWACCM_CHANGED_HOST_CONTEXT;
2761 }
2762 else
2763 {
2764 /* On the next entry we'll sync everything. */
2765 /** @todo we can do better than this */
2766 /* Not in the VINF_PGM_CHANGE_MODE though! */
2767 pVCpu->hwaccm.s.fContextUseFlags |= HWACCM_CHANGED_ALL;
2768 }
2769
2770 /* Translate into a less severe return code */
2771 if (rc == VERR_EM_INTERPRETER)
2772 rc = VINF_EM_RAW_EMULATE_INSTR;
2773
2774 /* Just set the correct state here instead of trying to catch every goto above. */
2775 VMCPU_CMPXCHG_STATE(pVCpu, VMCPUSTATE_STARTED, VMCPUSTATE_STARTED_EXEC);
2776
2777#ifdef VBOX_WITH_VMMR0_DISABLE_PREEMPTION
2778 /* Restore interrupts if we exitted after disabling them. */
2779 if (uOldEFlags != ~(RTCCUINTREG)0)
2780 ASMSetFlags(uOldEFlags);
2781#endif
2782
2783 STAM_PROFILE_ADV_STOP(&pVCpu->hwaccm.s.StatExit2, x);
2784 STAM_PROFILE_ADV_STOP(&pVCpu->hwaccm.s.StatExit1, x);
2785 STAM_PROFILE_ADV_STOP(&pVCpu->hwaccm.s.StatEntry, x);
2786 return VBOXSTRICTRC_TODO(rc);
2787}
2788
2789
2790/**
2791 * Emulate simple mov tpr instruction.
2792 *
2793 * @returns VBox status code.
2794 * @param pVM Pointer to the VM.
2795 * @param pVCpu Pointer to the VMCPU.
2796 * @param pCtx Pointer to the guest CPU context.
2797 */
2798static int hmR0SvmEmulateTprVMMCall(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
2799{
2800 int rc;
2801
2802 LogFlow(("Emulated VMMCall TPR access replacement at %RGv\n", pCtx->rip));
2803
2804 for (;;)
2805 {
2806 bool fPending;
2807 uint8_t u8Tpr;
2808
2809 PHWACCMTPRPATCH pPatch = (PHWACCMTPRPATCH)RTAvloU32Get(&pVM->hwaccm.s.PatchTree, (AVLOU32KEY)pCtx->eip);
2810 if (!pPatch)
2811 break;
2812
2813 switch (pPatch->enmType)
2814 {
2815 case HWACCMTPRINSTR_READ:
2816 /* TPR caching in CR8 */
2817 rc = PDMApicGetTPR(pVCpu, &u8Tpr, &fPending);
2818 AssertRC(rc);
2819
2820 rc = DISWriteReg32(CPUMCTX2CORE(pCtx), pPatch->uDstOperand, u8Tpr);
2821 AssertRC(rc);
2822
2823 LogFlow(("Emulated read successfully\n"));
2824 pCtx->rip += pPatch->cbOp;
2825 break;
2826
2827 case HWACCMTPRINSTR_WRITE_REG:
2828 case HWACCMTPRINSTR_WRITE_IMM:
2829 /* Fetch the new TPR value */
2830 if (pPatch->enmType == HWACCMTPRINSTR_WRITE_REG)
2831 {
2832 uint32_t val;
2833
2834 rc = DISFetchReg32(CPUMCTX2CORE(pCtx), pPatch->uSrcOperand, &val);
2835 AssertRC(rc);
2836 u8Tpr = val;
2837 }
2838 else
2839 u8Tpr = (uint8_t)pPatch->uSrcOperand;
2840
2841 rc = PDMApicSetTPR(pVCpu, u8Tpr);
2842 AssertRC(rc);
2843 LogFlow(("Emulated write successfully\n"));
2844 pCtx->rip += pPatch->cbOp;
2845 break;
2846
2847 default:
2848 AssertMsgFailedReturn(("Unexpected type %d\n", pPatch->enmType), VERR_HMSVM_UNEXPECTED_PATCH_TYPE);
2849 }
2850 }
2851 return VINF_SUCCESS;
2852}
2853
2854
2855/**
2856 * Enters the AMD-V session.
2857 *
2858 * @returns VBox status code.
2859 * @param pVM Pointer to the VM.
2860 * @param pVCpu Pointer to the VMCPU.
2861 * @param pCpu Pointer to the CPU info struct.
2862 */
2863VMMR0DECL(int) SVMR0Enter(PVM pVM, PVMCPU pVCpu, PHMGLOBLCPUINFO pCpu)
2864{
2865 Assert(pVM->hwaccm.s.svm.fSupported);
2866
2867 LogFlow(("SVMR0Enter cpu%d last=%d asid=%d\n", pCpu->idCpu, pVCpu->hwaccm.s.idLastCpu, pVCpu->hwaccm.s.uCurrentASID));
2868 pVCpu->hwaccm.s.fResumeVM = false;
2869
2870 /* Force to reload LDTR, so we'll execute VMLoad to load additional guest state. */
2871 pVCpu->hwaccm.s.fContextUseFlags |= HWACCM_CHANGED_GUEST_LDTR;
2872
2873 return VINF_SUCCESS;
2874}
2875
2876
2877/**
2878 * Leaves the AMD-V session.
2879 *
2880 * @returns VBox status code.
2881 * @param pVM Pointer to the VM.
2882 * @param pVCpu Pointer to the VMCPU.
2883 * @param pCtx Pointer to the guest CPU context.
2884 */
2885VMMR0DECL(int) SVMR0Leave(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx)
2886{
2887 SVM_VMCB *pVMCB = (SVM_VMCB *)pVCpu->hwaccm.s.svm.pVMCB;
2888
2889 Assert(pVM->hwaccm.s.svm.fSupported);
2890
2891#ifdef DEBUG
2892 if (CPUMIsHyperDebugStateActive(pVCpu))
2893 {
2894 CPUMR0LoadHostDebugState(pVM, pVCpu);
2895 }
2896 else
2897#endif
2898 /* Save the guest debug state if necessary. */
2899 if (CPUMIsGuestDebugStateActive(pVCpu))
2900 {
2901 CPUMR0SaveGuestDebugState(pVM, pVCpu, pCtx, false /* skip DR6 */);
2902
2903 /* Intercept all DRx reads and writes again. Changed later on. */
2904 pVMCB->ctrl.u16InterceptRdDRx = 0xFFFF;
2905 pVMCB->ctrl.u16InterceptWrDRx = 0xFFFF;
2906
2907 /* Resync the debug registers the next time. */
2908 pVCpu->hwaccm.s.fContextUseFlags |= HWACCM_CHANGED_GUEST_DEBUG;
2909 }
2910 else
2911 Assert(pVMCB->ctrl.u16InterceptRdDRx == 0xFFFF && pVMCB->ctrl.u16InterceptWrDRx == 0xFFFF);
2912
2913 return VINF_SUCCESS;
2914}
2915
2916
2917/**
2918 * Worker for Interprets INVLPG.
2919 *
2920 * @return VBox status code.
2921 * @param pVCpu Pointer to the VMCPU.
2922 * @param pCpu Pointer to the CPU info struct.
2923 * @param pRegFrame Pointer to the register frame.
2924 */
2925static int hmR0svmInterpretInvlPgEx(PVMCPU pVCpu, PDISCPUSTATE pCpu, PCPUMCTXCORE pRegFrame)
2926{
2927 DISQPVPARAMVAL param1;
2928 RTGCPTR addr;
2929
2930 int rc = DISQueryParamVal(pRegFrame, pCpu, &pCpu->Param1, &param1, DISQPVWHICH_SRC);
2931 if (RT_FAILURE(rc))
2932 return VERR_EM_INTERPRETER;
2933
2934 switch (param1.type)
2935 {
2936 case DISQPV_TYPE_IMMEDIATE:
2937 case DISQPV_TYPE_ADDRESS:
2938 if (!(param1.flags & (DISQPV_FLAG_32 | DISQPV_FLAG_64)))
2939 return VERR_EM_INTERPRETER;
2940 addr = param1.val.val64;
2941 break;
2942
2943 default:
2944 return VERR_EM_INTERPRETER;
2945 }
2946
2947 /** @todo is addr always a flat linear address or ds based
2948 * (in absence of segment override prefixes)????
2949 */
2950 rc = PGMInvalidatePage(pVCpu, addr);
2951 if (RT_SUCCESS(rc))
2952 return VINF_SUCCESS;
2953
2954 AssertRC(rc);
2955 return rc;
2956}
2957
2958
2959/**
2960 * Interprets INVLPG.
2961 *
2962 * @returns VBox status code.
2963 * @retval VINF_* Scheduling instructions.
2964 * @retval VERR_EM_INTERPRETER Something we can't cope with.
2965 * @retval VERR_* Fatal errors.
2966 *
2967 * @param pVM Pointer to the VM.
2968 * @param pRegFrame Pointer to the register frame.
2969 *
2970 * @remarks Updates the EIP if an instruction was executed successfully.
2971 */
2972static int hmR0SvmInterpretInvlpg(PVM pVM, PVMCPU pVCpu, PCPUMCTXCORE pRegFrame)
2973{
2974 /*
2975 * Only allow 32 & 64 bit code.
2976 */
2977 if (CPUMGetGuestCodeBits(pVCpu) != 16)
2978 {
2979 PDISSTATE pDis = &pVCpu->hwaccm.s.DisState;
2980 int rc = EMInterpretDisasCurrent(pVM, pVCpu, pDis, NULL);
2981 if (RT_SUCCESS(rc) && pDis->pCurInstr->uOpcode == OP_INVLPG)
2982 {
2983 rc = hmR0svmInterpretInvlPgEx(pVCpu, pDis, pRegFrame);
2984 if (RT_SUCCESS(rc))
2985 pRegFrame->rip += pDis->cbInstr; /* Move on to the next instruction. */
2986 return rc;
2987 }
2988 }
2989 return VERR_EM_INTERPRETER;
2990}
2991
2992
2993/**
2994 * Invalidates a guest page by guest virtual address.
2995 *
2996 * @returns VBox status code.
2997 * @param pVM Pointer to the VM.
2998 * @param pVCpu Pointer to the VMCPU.
2999 * @param GCVirt Guest virtual address of the page to invalidate.
3000 */
3001VMMR0DECL(int) SVMR0InvalidatePage(PVM pVM, PVMCPU pVCpu, RTGCPTR GCVirt)
3002{
3003 bool fFlushPending = pVM->hwaccm.s.svm.fAlwaysFlushTLB | VMCPU_FF_ISSET(pVCpu, VMCPU_FF_TLB_FLUSH);
3004
3005 /* Skip it if a TLB flush is already pending. */
3006 if (!fFlushPending)
3007 {
3008 SVM_VMCB *pVMCB;
3009
3010 Log2(("SVMR0InvalidatePage %RGv\n", GCVirt));
3011 AssertReturn(pVM, VERR_INVALID_PARAMETER);
3012 Assert(pVM->hwaccm.s.svm.fSupported);
3013
3014 pVMCB = (SVM_VMCB *)pVCpu->hwaccm.s.svm.pVMCB;
3015 AssertMsgReturn(pVMCB, ("Invalid pVMCB\n"), VERR_HMSVM_INVALID_PVMCB);
3016
3017#if HC_ARCH_BITS == 32
3018 /* If we get a flush in 64 bits guest mode, then force a full TLB flush. Invlpga takes only 32 bits addresses. */
3019 if (CPUMIsGuestInLongMode(pVCpu))
3020 VMCPU_FF_SET(pVCpu, VMCPU_FF_TLB_FLUSH);
3021 else
3022#endif
3023 SVMR0InvlpgA(GCVirt, pVMCB->ctrl.TLBCtrl.n.u32ASID);
3024 }
3025 return VINF_SUCCESS;
3026}
3027
3028
3029#if 0 /* obsolete, but left here for clarification. */
3030/**
3031 * Invalidates a guest page by physical address.
3032 *
3033 * @returns VBox status code.
3034 * @param pVM Pointer to the VM.
3035 * @param pVCpu Pointer to the VMCPU.
3036 * @param GCPhys Guest physical address of the page to invalidate.
3037 */
3038VMMR0DECL(int) SVMR0InvalidatePhysPage(PVM pVM, PVMCPU pVCpu, RTGCPHYS GCPhys)
3039{
3040 Assert(pVM->hwaccm.s.fNestedPaging);
3041 /* invlpga only invalidates TLB entries for guest virtual addresses; we have no choice but to force a TLB flush here. */
3042 VMCPU_FF_SET(pVCpu, VMCPU_FF_TLB_FLUSH);
3043 STAM_COUNTER_INC(&pVCpu->hwaccm.s.StatFlushTLBInvlpga);
3044 return VINF_SUCCESS;
3045}
3046#endif
3047
3048
3049#if HC_ARCH_BITS == 32 && defined(VBOX_ENABLE_64_BITS_GUESTS) && !defined(VBOX_WITH_HYBRID_32BIT_KERNEL)
3050/**
3051 * Prepares for and executes VMRUN (64-bit guests from a 32-bit host).
3052 *
3053 * @returns VBox status code.
3054 * @param pVMCBHostPhys Physical address of host VMCB.
3055 * @param pVMCBPhys Physical address of the VMCB.
3056 * @param pCtx Pointer to the guest CPU context.
3057 * @param pVM Pointer to the VM.
3058 * @param pVCpu Pointer to the VMCPU.
3059 */
3060DECLASM(int) SVMR0VMSwitcherRun64(RTHCPHYS pVMCBHostPhys, RTHCPHYS pVMCBPhys, PCPUMCTX pCtx, PVM pVM, PVMCPU pVCpu)
3061{
3062 uint32_t aParam[4];
3063
3064 aParam[0] = (uint32_t)(pVMCBHostPhys); /* Param 1: pVMCBHostPhys - Lo. */
3065 aParam[1] = (uint32_t)(pVMCBHostPhys >> 32); /* Param 1: pVMCBHostPhys - Hi. */
3066 aParam[2] = (uint32_t)(pVMCBPhys); /* Param 2: pVMCBPhys - Lo. */
3067 aParam[3] = (uint32_t)(pVMCBPhys >> 32); /* Param 2: pVMCBPhys - Hi. */
3068
3069 return SVMR0Execute64BitsHandler(pVM, pVCpu, pCtx, pVM->hwaccm.s.pfnSVMGCVMRun64, 4, &aParam[0]);
3070}
3071
3072
3073/**
3074 * Executes the specified handler in 64-bit mode.
3075 *
3076 * @returns VBox status code.
3077 * @param pVM Pointer to the VM.
3078 * @param pVCpu Pointer to the VMCPU.
3079 * @param pCtx Pointer to the guest CPU context.
3080 * @param pfnHandler Pointer to the RC handler function.
3081 * @param cbParam Number of parameters.
3082 * @param paParam Array of 32-bit parameters.
3083 */
3084VMMR0DECL(int) SVMR0Execute64BitsHandler(PVM pVM, PVMCPU pVCpu, PCPUMCTX pCtx, RTRCPTR pfnHandler, uint32_t cbParam,
3085 uint32_t *paParam)
3086{
3087 int rc;
3088 RTHCUINTREG uOldEFlags;
3089
3090 Assert(pfnHandler);
3091
3092 /* Disable interrupts. */
3093 uOldEFlags = ASMIntDisableFlags();
3094
3095#ifdef VBOX_WITH_VMMR0_DISABLE_LAPIC_NMI
3096 RTCPUID idHostCpu = RTMpCpuId();
3097 CPUMR0SetLApic(pVM, idHostCpu);
3098#endif
3099
3100 CPUMSetHyperESP(pVCpu, VMMGetStackRC(pVCpu));
3101 CPUMSetHyperEIP(pVCpu, pfnHandler);
3102 for (int i = (int)cbParam - 1; i >= 0; i--)
3103 CPUMPushHyper(pVCpu, paParam[i]);
3104
3105 STAM_PROFILE_ADV_START(&pVCpu->hwaccm.s.StatWorldSwitch3264, z);
3106 /* Call switcher. */
3107 rc = pVM->hwaccm.s.pfnHost32ToGuest64R0(pVM, RT_OFFSETOF(VM, aCpus[pVCpu->idCpu].cpum) - RT_OFFSETOF(VM, cpum));
3108 STAM_PROFILE_ADV_STOP(&pVCpu->hwaccm.s.StatWorldSwitch3264, z);
3109
3110 ASMSetFlags(uOldEFlags);
3111 return rc;
3112}
3113
3114#endif /* HC_ARCH_BITS == 32 && defined(VBOX_ENABLE_64_BITS_GUESTS) */
3115
Note: See TracBrowser for help on using the repository browser.

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