VirtualBox

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

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

VMM: Experimenting with R0 TPs in HM context.

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