VirtualBox

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

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

VMM/VMMR0: Hungarian notation fixes.

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

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