VirtualBox

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

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

Trace VM exits.

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

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