VirtualBox

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

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

VMM: invpg -> invlpg, some cleanup.

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