VirtualBox

source: vbox/trunk/src/VBox/VMM/VMM.cpp@ 26175

Last change on this file since 26175 was 26066, checked in by vboxsync, 15 years ago

Guest SMP: force all VCPUs to go back to ring 3 when a pgm pool flush is pending. Not doing so might cause trouble on a loaded host.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 81.0 KB
Line 
1/* $Id: VMM.cpp 26066 2010-01-27 12:59:32Z vboxsync $ */
2/** @file
3 * VMM - The Virtual Machine Monitor Core.
4 */
5
6/*
7 * Copyright (C) 2006-2007 Sun Microsystems, Inc.
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 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
18 * Clara, CA 95054 USA or visit http://www.sun.com if you need
19 * additional information or have any questions.
20 */
21
22//#define NO_SUPCALLR0VMM
23
24/** @page pg_vmm VMM - The Virtual Machine Monitor
25 *
26 * The VMM component is two things at the moment, it's a component doing a few
27 * management and routing tasks, and it's the whole virtual machine monitor
28 * thing. For hysterical reasons, it is not doing all the management that one
29 * would expect, this is instead done by @ref pg_vm. We'll address this
30 * misdesign eventually.
31 *
32 * @see grp_vmm, grp_vm
33 *
34 *
35 * @section sec_vmmstate VMM State
36 *
37 * @image html VM_Statechart_Diagram.gif
38 *
39 * To be written.
40 *
41 *
42 * @subsection subsec_vmm_init VMM Initialization
43 *
44 * To be written.
45 *
46 *
47 * @subsection subsec_vmm_term VMM Termination
48 *
49 * To be written.
50 *
51 */
52
53/*******************************************************************************
54* Header Files *
55*******************************************************************************/
56#define LOG_GROUP LOG_GROUP_VMM
57#include <VBox/vmm.h>
58#include <VBox/vmapi.h>
59#include <VBox/pgm.h>
60#include <VBox/cfgm.h>
61#include <VBox/pdmqueue.h>
62#include <VBox/pdmcritsect.h>
63#include <VBox/pdmapi.h>
64#include <VBox/cpum.h>
65#include <VBox/mm.h>
66#include <VBox/iom.h>
67#include <VBox/trpm.h>
68#include <VBox/selm.h>
69#include <VBox/em.h>
70#include <VBox/sup.h>
71#include <VBox/dbgf.h>
72#include <VBox/csam.h>
73#include <VBox/patm.h>
74#include <VBox/rem.h>
75#include <VBox/ssm.h>
76#include <VBox/tm.h>
77#include "VMMInternal.h"
78#include "VMMSwitcher/VMMSwitcher.h"
79#include <VBox/vm.h>
80
81#include <VBox/err.h>
82#include <VBox/param.h>
83#include <VBox/version.h>
84#include <VBox/x86.h>
85#include <VBox/hwaccm.h>
86#include <iprt/assert.h>
87#include <iprt/alloc.h>
88#include <iprt/asm.h>
89#include <iprt/time.h>
90#include <iprt/semaphore.h>
91#include <iprt/stream.h>
92#include <iprt/string.h>
93#include <iprt/stdarg.h>
94#include <iprt/ctype.h>
95
96
97
98/*******************************************************************************
99* Defined Constants And Macros *
100*******************************************************************************/
101/** The saved state version. */
102#define VMM_SAVED_STATE_VERSION 4
103/** The saved state version used by v3.0 and earlier. (Teleportation) */
104#define VMM_SAVED_STATE_VERSION_3_0 3
105
106
107/*******************************************************************************
108* Internal Functions *
109*******************************************************************************/
110static int vmmR3InitStacks(PVM pVM);
111static int vmmR3InitLoggers(PVM pVM);
112static void vmmR3InitRegisterStats(PVM pVM);
113static DECLCALLBACK(int) vmmR3Save(PVM pVM, PSSMHANDLE pSSM);
114static DECLCALLBACK(int) vmmR3Load(PVM pVM, PSSMHANDLE pSSM, uint32_t uVersion, uint32_t uPass);
115static DECLCALLBACK(void) vmmR3YieldEMT(PVM pVM, PTMTIMER pTimer, void *pvUser);
116static int vmmR3ServiceCallRing3Request(PVM pVM, PVMCPU pVCpu);
117static DECLCALLBACK(void) vmmR3InfoFF(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs);
118
119
120/**
121 * Initializes the VMM.
122 *
123 * @returns VBox status code.
124 * @param pVM The VM to operate on.
125 */
126VMMR3DECL(int) VMMR3Init(PVM pVM)
127{
128 LogFlow(("VMMR3Init\n"));
129
130 /*
131 * Assert alignment, sizes and order.
132 */
133 AssertMsg(pVM->vmm.s.offVM == 0, ("Already initialized!\n"));
134 AssertCompile(sizeof(pVM->vmm.s) <= sizeof(pVM->vmm.padding));
135 AssertCompile(sizeof(pVM->aCpus[0].vmm.s) <= sizeof(pVM->aCpus[0].vmm.padding));
136
137 /*
138 * Init basic VM VMM members.
139 */
140 pVM->vmm.s.offVM = RT_OFFSETOF(VM, vmm);
141 pVM->vmm.s.pahEvtRendezvousEnterOrdered = NULL;
142 pVM->vmm.s.hEvtRendezvousEnterOneByOne = NIL_RTSEMEVENT;
143 pVM->vmm.s.hEvtMulRendezvousEnterAllAtOnce = NIL_RTSEMEVENTMULTI;
144 pVM->vmm.s.hEvtMulRendezvousDone = NIL_RTSEMEVENTMULTI;
145 pVM->vmm.s.hEvtRendezvousDoneCaller = NIL_RTSEMEVENT;
146 int rc = CFGMR3QueryU32(CFGMR3GetRoot(pVM), "YieldEMTInterval", &pVM->vmm.s.cYieldEveryMillies);
147 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
148 pVM->vmm.s.cYieldEveryMillies = 23; /* Value arrived at after experimenting with the grub boot prompt. */
149 //pVM->vmm.s.cYieldEveryMillies = 8; //debugging
150 else
151 AssertMsgRCReturn(rc, ("Configuration error. Failed to query \"YieldEMTInterval\", rc=%Rrc\n", rc), rc);
152
153 /*
154 * Initialize the VMM sync critical section and semaphores.
155 */
156 rc = RTCritSectInit(&pVM->vmm.s.CritSectSync);
157 AssertRCReturn(rc, rc);
158 pVM->vmm.s.pahEvtRendezvousEnterOrdered = (PRTSEMEVENT)MMR3HeapAlloc(pVM, MM_TAG_VMM, sizeof(RTSEMEVENT) * pVM->cCpus);
159 if (!pVM->vmm.s.pahEvtRendezvousEnterOrdered)
160 return VERR_NO_MEMORY;
161 for (VMCPUID i = 0; i < pVM->cCpus; i++)
162 pVM->vmm.s.pahEvtRendezvousEnterOrdered[i] = NIL_RTSEMEVENT;
163 for (VMCPUID i = 0; i < pVM->cCpus; i++)
164 {
165 rc = RTSemEventCreate(&pVM->vmm.s.pahEvtRendezvousEnterOrdered[i]);
166 AssertRCReturn(rc, rc);
167 }
168 rc = RTSemEventCreate(&pVM->vmm.s.hEvtRendezvousEnterOneByOne);
169 AssertRCReturn(rc, rc);
170 rc = RTSemEventMultiCreate(&pVM->vmm.s.hEvtMulRendezvousEnterAllAtOnce);
171 AssertRCReturn(rc, rc);
172 rc = RTSemEventMultiCreate(&pVM->vmm.s.hEvtMulRendezvousDone);
173 AssertRCReturn(rc, rc);
174 rc = RTSemEventCreate(&pVM->vmm.s.hEvtRendezvousDoneCaller);
175 AssertRCReturn(rc, rc);
176
177 /* GC switchers are enabled by default. Turned off by HWACCM. */
178 pVM->vmm.s.fSwitcherDisabled = false;
179
180 /*
181 * Register the saved state data unit.
182 */
183 rc = SSMR3RegisterInternal(pVM, "vmm", 1, VMM_SAVED_STATE_VERSION, VMM_STACK_SIZE + sizeof(RTGCPTR),
184 NULL, NULL, NULL,
185 NULL, vmmR3Save, NULL,
186 NULL, vmmR3Load, NULL);
187 if (RT_FAILURE(rc))
188 return rc;
189
190 /*
191 * Register the Ring-0 VM handle with the session for fast ioctl calls.
192 */
193 rc = SUPR3SetVMForFastIOCtl(pVM->pVMR0);
194 if (RT_FAILURE(rc))
195 return rc;
196
197 /*
198 * Init various sub-components.
199 */
200 rc = vmmR3SwitcherInit(pVM);
201 if (RT_SUCCESS(rc))
202 {
203 rc = vmmR3InitStacks(pVM);
204 if (RT_SUCCESS(rc))
205 {
206 rc = vmmR3InitLoggers(pVM);
207
208#ifdef VBOX_WITH_NMI
209 /*
210 * Allocate mapping for the host APIC.
211 */
212 if (RT_SUCCESS(rc))
213 {
214 rc = MMR3HyperReserve(pVM, PAGE_SIZE, "Host APIC", &pVM->vmm.s.GCPtrApicBase);
215 AssertRC(rc);
216 }
217#endif
218 if (RT_SUCCESS(rc))
219 {
220 /*
221 * Debug info and statistics.
222 */
223 DBGFR3InfoRegisterInternal(pVM, "ff", "Displays the current Forced actions Flags.", vmmR3InfoFF);
224 vmmR3InitRegisterStats(pVM);
225
226 return VINF_SUCCESS;
227 }
228 }
229 /** @todo: Need failure cleanup. */
230
231 //more todo in here?
232 //if (RT_SUCCESS(rc))
233 //{
234 //}
235 //int rc2 = vmmR3TermCoreCode(pVM);
236 //AssertRC(rc2));
237 }
238
239 return rc;
240}
241
242
243/**
244 * Allocate & setup the VMM RC stack(s) (for EMTs).
245 *
246 * The stacks are also used for long jumps in Ring-0.
247 *
248 * @returns VBox status code.
249 * @param pVM Pointer to the shared VM structure.
250 *
251 * @remarks The optional guard page gets it protection setup up during R3 init
252 * completion because of init order issues.
253 */
254static int vmmR3InitStacks(PVM pVM)
255{
256 int rc = VINF_SUCCESS;
257#ifdef VMM_R0_SWITCH_STACK
258 uint32_t fFlags = MMHYPER_AONR_FLAGS_KERNEL_MAPPING;
259#else
260 uint32_t fFlags = 0;
261#endif
262
263 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
264 {
265 PVMCPU pVCpu = &pVM->aCpus[idCpu];
266
267#ifdef VBOX_STRICT_VMM_STACK
268 rc = MMR3HyperAllocOnceNoRelEx(pVM, PAGE_SIZE + VMM_STACK_SIZE + PAGE_SIZE,
269#else
270 rc = MMR3HyperAllocOnceNoRelEx(pVM, VMM_STACK_SIZE,
271#endif
272 PAGE_SIZE, MM_TAG_VMM, fFlags, (void **)&pVCpu->vmm.s.pbEMTStackR3);
273 if (RT_SUCCESS(rc))
274 {
275#ifdef VBOX_STRICT_VMM_STACK
276 pVCpu->vmm.s.pbEMTStackR3 += PAGE_SIZE;
277#endif
278#ifdef VBOX_WITH_2X_4GB_ADDR_SPACE
279 /* MMHyperR3ToR0 returns R3 when not doing hardware assisted virtualization. */
280 if (!VMMIsHwVirtExtForced(pVM))
281 pVCpu->vmm.s.CallRing3JmpBufR0.pvSavedStack = NIL_RTR0PTR;
282 else
283#endif
284 pVCpu->vmm.s.CallRing3JmpBufR0.pvSavedStack = MMHyperR3ToR0(pVM, pVCpu->vmm.s.pbEMTStackR3);
285 pVCpu->vmm.s.pbEMTStackRC = MMHyperR3ToRC(pVM, pVCpu->vmm.s.pbEMTStackR3);
286 pVCpu->vmm.s.pbEMTStackBottomRC = pVCpu->vmm.s.pbEMTStackRC + VMM_STACK_SIZE;
287 AssertRelease(pVCpu->vmm.s.pbEMTStackRC);
288
289 CPUMSetHyperESP(pVCpu, pVCpu->vmm.s.pbEMTStackBottomRC);
290 }
291 }
292
293 return rc;
294}
295
296
297/**
298 * Initialize the loggers.
299 *
300 * @returns VBox status code.
301 * @param pVM Pointer to the shared VM structure.
302 */
303static int vmmR3InitLoggers(PVM pVM)
304{
305 int rc;
306
307 /*
308 * Allocate RC & R0 Logger instances (they are finalized in the relocator).
309 */
310#ifdef LOG_ENABLED
311 PRTLOGGER pLogger = RTLogDefaultInstance();
312 if (pLogger)
313 {
314 pVM->vmm.s.cbRCLogger = RT_OFFSETOF(RTLOGGERRC, afGroups[pLogger->cGroups]);
315 rc = MMR3HyperAllocOnceNoRel(pVM, pVM->vmm.s.cbRCLogger, 0, MM_TAG_VMM, (void **)&pVM->vmm.s.pRCLoggerR3);
316 if (RT_FAILURE(rc))
317 return rc;
318 pVM->vmm.s.pRCLoggerRC = MMHyperR3ToRC(pVM, pVM->vmm.s.pRCLoggerR3);
319
320# ifdef VBOX_WITH_R0_LOGGING
321 for (VMCPUID i = 0; i < pVM->cCpus; i++)
322 {
323 PVMCPU pVCpu = &pVM->aCpus[i];
324
325 rc = MMR3HyperAllocOnceNoRelEx(pVM, RT_OFFSETOF(VMMR0LOGGER, Logger.afGroups[pLogger->cGroups]),
326 0, MM_TAG_VMM, MMHYPER_AONR_FLAGS_KERNEL_MAPPING,
327 (void **)&pVCpu->vmm.s.pR0LoggerR3);
328 if (RT_FAILURE(rc))
329 return rc;
330 pVCpu->vmm.s.pR0LoggerR3->pVM = pVM->pVMR0;
331 //pVCpu->vmm.s.pR0LoggerR3->fCreated = false;
332 pVCpu->vmm.s.pR0LoggerR3->cbLogger = RT_OFFSETOF(RTLOGGER, afGroups[pLogger->cGroups]);
333 pVCpu->vmm.s.pR0LoggerR0 = MMHyperR3ToR0(pVM, pVCpu->vmm.s.pR0LoggerR3);
334 }
335# endif
336 }
337#endif /* LOG_ENABLED */
338
339#ifdef VBOX_WITH_RC_RELEASE_LOGGING
340 /*
341 * Allocate RC release logger instances (finalized in the relocator).
342 */
343 PRTLOGGER pRelLogger = RTLogRelDefaultInstance();
344 if (pRelLogger)
345 {
346 pVM->vmm.s.cbRCRelLogger = RT_OFFSETOF(RTLOGGERRC, afGroups[pRelLogger->cGroups]);
347 rc = MMR3HyperAllocOnceNoRel(pVM, pVM->vmm.s.cbRCRelLogger, 0, MM_TAG_VMM, (void **)&pVM->vmm.s.pRCRelLoggerR3);
348 if (RT_FAILURE(rc))
349 return rc;
350 pVM->vmm.s.pRCRelLoggerRC = MMHyperR3ToRC(pVM, pVM->vmm.s.pRCRelLoggerR3);
351 }
352#endif /* VBOX_WITH_RC_RELEASE_LOGGING */
353 return VINF_SUCCESS;
354}
355
356
357/**
358 * VMMR3Init worker that register the statistics with STAM.
359 *
360 * @param pVM The shared VM structure.
361 */
362static void vmmR3InitRegisterStats(PVM pVM)
363{
364 /*
365 * Statistics.
366 */
367 STAM_REG(pVM, &pVM->vmm.s.StatRunRC, STAMTYPE_COUNTER, "/VMM/RunRC", STAMUNIT_OCCURENCES, "Number of context switches.");
368 STAM_REG(pVM, &pVM->vmm.s.StatRZRetNormal, STAMTYPE_COUNTER, "/VMM/RZRet/Normal", STAMUNIT_OCCURENCES, "Number of VINF_SUCCESS returns.");
369 STAM_REG(pVM, &pVM->vmm.s.StatRZRetInterrupt, STAMTYPE_COUNTER, "/VMM/RZRet/Interrupt", STAMUNIT_OCCURENCES, "Number of VINF_EM_RAW_INTERRUPT returns.");
370 STAM_REG(pVM, &pVM->vmm.s.StatRZRetInterruptHyper, STAMTYPE_COUNTER, "/VMM/RZRet/InterruptHyper", STAMUNIT_OCCURENCES, "Number of VINF_EM_RAW_INTERRUPT_HYPER returns.");
371 STAM_REG(pVM, &pVM->vmm.s.StatRZRetGuestTrap, STAMTYPE_COUNTER, "/VMM/RZRet/GuestTrap", STAMUNIT_OCCURENCES, "Number of VINF_EM_RAW_GUEST_TRAP returns.");
372 STAM_REG(pVM, &pVM->vmm.s.StatRZRetRingSwitch, STAMTYPE_COUNTER, "/VMM/RZRet/RingSwitch", STAMUNIT_OCCURENCES, "Number of VINF_EM_RAW_RING_SWITCH returns.");
373 STAM_REG(pVM, &pVM->vmm.s.StatRZRetRingSwitchInt, STAMTYPE_COUNTER, "/VMM/RZRet/RingSwitchInt", STAMUNIT_OCCURENCES, "Number of VINF_EM_RAW_RING_SWITCH_INT returns.");
374 STAM_REG(pVM, &pVM->vmm.s.StatRZRetStaleSelector, STAMTYPE_COUNTER, "/VMM/RZRet/StaleSelector", STAMUNIT_OCCURENCES, "Number of VINF_EM_RAW_STALE_SELECTOR returns.");
375 STAM_REG(pVM, &pVM->vmm.s.StatRZRetIRETTrap, STAMTYPE_COUNTER, "/VMM/RZRet/IRETTrap", STAMUNIT_OCCURENCES, "Number of VINF_EM_RAW_IRET_TRAP returns.");
376 STAM_REG(pVM, &pVM->vmm.s.StatRZRetEmulate, STAMTYPE_COUNTER, "/VMM/RZRet/Emulate", STAMUNIT_OCCURENCES, "Number of VINF_EM_EXECUTE_INSTRUCTION returns.");
377 STAM_REG(pVM, &pVM->vmm.s.StatRZRetIOBlockEmulate, STAMTYPE_COUNTER, "/VMM/RZRet/EmulateIOBlock", STAMUNIT_OCCURENCES, "Number of VINF_EM_RAW_EMULATE_IO_BLOCK returns.");
378 STAM_REG(pVM, &pVM->vmm.s.StatRZRetPatchEmulate, STAMTYPE_COUNTER, "/VMM/RZRet/PatchEmulate", STAMUNIT_OCCURENCES, "Number of VINF_PATCH_EMULATE_INSTR returns.");
379 STAM_REG(pVM, &pVM->vmm.s.StatRZRetIORead, STAMTYPE_COUNTER, "/VMM/RZRet/IORead", STAMUNIT_OCCURENCES, "Number of VINF_IOM_HC_IOPORT_READ returns.");
380 STAM_REG(pVM, &pVM->vmm.s.StatRZRetIOWrite, STAMTYPE_COUNTER, "/VMM/RZRet/IOWrite", STAMUNIT_OCCURENCES, "Number of VINF_IOM_HC_IOPORT_WRITE returns.");
381 STAM_REG(pVM, &pVM->vmm.s.StatRZRetMMIORead, STAMTYPE_COUNTER, "/VMM/RZRet/MMIORead", STAMUNIT_OCCURENCES, "Number of VINF_IOM_HC_MMIO_READ returns.");
382 STAM_REG(pVM, &pVM->vmm.s.StatRZRetMMIOWrite, STAMTYPE_COUNTER, "/VMM/RZRet/MMIOWrite", STAMUNIT_OCCURENCES, "Number of VINF_IOM_HC_MMIO_WRITE returns.");
383 STAM_REG(pVM, &pVM->vmm.s.StatRZRetMMIOReadWrite, STAMTYPE_COUNTER, "/VMM/RZRet/MMIOReadWrite", STAMUNIT_OCCURENCES, "Number of VINF_IOM_HC_MMIO_READ_WRITE returns.");
384 STAM_REG(pVM, &pVM->vmm.s.StatRZRetMMIOPatchRead, STAMTYPE_COUNTER, "/VMM/RZRet/MMIOPatchRead", STAMUNIT_OCCURENCES, "Number of VINF_IOM_HC_MMIO_PATCH_READ returns.");
385 STAM_REG(pVM, &pVM->vmm.s.StatRZRetMMIOPatchWrite, STAMTYPE_COUNTER, "/VMM/RZRet/MMIOPatchWrite", STAMUNIT_OCCURENCES, "Number of VINF_IOM_HC_MMIO_PATCH_WRITE returns.");
386 STAM_REG(pVM, &pVM->vmm.s.StatRZRetLDTFault, STAMTYPE_COUNTER, "/VMM/RZRet/LDTFault", STAMUNIT_OCCURENCES, "Number of VINF_EM_EXECUTE_INSTRUCTION_GDT_FAULT returns.");
387 STAM_REG(pVM, &pVM->vmm.s.StatRZRetGDTFault, STAMTYPE_COUNTER, "/VMM/RZRet/GDTFault", STAMUNIT_OCCURENCES, "Number of VINF_EM_EXECUTE_INSTRUCTION_LDT_FAULT returns.");
388 STAM_REG(pVM, &pVM->vmm.s.StatRZRetIDTFault, STAMTYPE_COUNTER, "/VMM/RZRet/IDTFault", STAMUNIT_OCCURENCES, "Number of VINF_EM_EXECUTE_INSTRUCTION_IDT_FAULT returns.");
389 STAM_REG(pVM, &pVM->vmm.s.StatRZRetTSSFault, STAMTYPE_COUNTER, "/VMM/RZRet/TSSFault", STAMUNIT_OCCURENCES, "Number of VINF_EM_EXECUTE_INSTRUCTION_TSS_FAULT returns.");
390 STAM_REG(pVM, &pVM->vmm.s.StatRZRetPDFault, STAMTYPE_COUNTER, "/VMM/RZRet/PDFault", STAMUNIT_OCCURENCES, "Number of VINF_EM_EXECUTE_INSTRUCTION_PD_FAULT returns.");
391 STAM_REG(pVM, &pVM->vmm.s.StatRZRetCSAMTask, STAMTYPE_COUNTER, "/VMM/RZRet/CSAMTask", STAMUNIT_OCCURENCES, "Number of VINF_CSAM_PENDING_ACTION returns.");
392 STAM_REG(pVM, &pVM->vmm.s.StatRZRetSyncCR3, STAMTYPE_COUNTER, "/VMM/RZRet/SyncCR", STAMUNIT_OCCURENCES, "Number of VINF_PGM_SYNC_CR3 returns.");
393 STAM_REG(pVM, &pVM->vmm.s.StatRZRetMisc, STAMTYPE_COUNTER, "/VMM/RZRet/Misc", STAMUNIT_OCCURENCES, "Number of misc returns.");
394 STAM_REG(pVM, &pVM->vmm.s.StatRZRetPatchInt3, STAMTYPE_COUNTER, "/VMM/RZRet/PatchInt3", STAMUNIT_OCCURENCES, "Number of VINF_PATM_PATCH_INT3 returns.");
395 STAM_REG(pVM, &pVM->vmm.s.StatRZRetPatchPF, STAMTYPE_COUNTER, "/VMM/RZRet/PatchPF", STAMUNIT_OCCURENCES, "Number of VINF_PATM_PATCH_TRAP_PF returns.");
396 STAM_REG(pVM, &pVM->vmm.s.StatRZRetPatchGP, STAMTYPE_COUNTER, "/VMM/RZRet/PatchGP", STAMUNIT_OCCURENCES, "Number of VINF_PATM_PATCH_TRAP_GP returns.");
397 STAM_REG(pVM, &pVM->vmm.s.StatRZRetPatchIretIRQ, STAMTYPE_COUNTER, "/VMM/RZRet/PatchIret", STAMUNIT_OCCURENCES, "Number of VINF_PATM_PENDING_IRQ_AFTER_IRET returns.");
398 STAM_REG(pVM, &pVM->vmm.s.StatRZRetRescheduleREM, STAMTYPE_COUNTER, "/VMM/RZRet/ScheduleREM", STAMUNIT_OCCURENCES, "Number of VINF_EM_RESCHEDULE_REM returns.");
399 STAM_REG(pVM, &pVM->vmm.s.StatRZRetToR3, STAMTYPE_COUNTER, "/VMM/RZRet/ToR3", STAMUNIT_OCCURENCES, "Number of VINF_EM_RAW_TO_R3 returns.");
400 STAM_REG(pVM, &pVM->vmm.s.StatRZRetTimerPending, STAMTYPE_COUNTER, "/VMM/RZRet/TimerPending", STAMUNIT_OCCURENCES, "Number of VINF_EM_RAW_TIMER_PENDING returns.");
401 STAM_REG(pVM, &pVM->vmm.s.StatRZRetInterruptPending, STAMTYPE_COUNTER, "/VMM/RZRet/InterruptPending", STAMUNIT_OCCURENCES, "Number of VINF_EM_RAW_INTERRUPT_PENDING returns.");
402 STAM_REG(pVM, &pVM->vmm.s.StatRZRetPATMDuplicateFn, STAMTYPE_COUNTER, "/VMM/RZRet/PATMDuplicateFn", STAMUNIT_OCCURENCES, "Number of VINF_PATM_DUPLICATE_FUNCTION returns.");
403 STAM_REG(pVM, &pVM->vmm.s.StatRZRetPGMChangeMode, STAMTYPE_COUNTER, "/VMM/RZRet/PGMChangeMode", STAMUNIT_OCCURENCES, "Number of VINF_PGM_CHANGE_MODE returns.");
404 STAM_REG(pVM, &pVM->vmm.s.StatRZRetPGMFlushPending, STAMTYPE_COUNTER, "/VMM/RZRet/PGMFlushPending", STAMUNIT_OCCURENCES, "Number of VINF_PGM_POOL_FLUSH_PENDING returns.");
405 STAM_REG(pVM, &pVM->vmm.s.StatRZRetPendingRequest, STAMTYPE_COUNTER, "/VMM/RZRet/PendingRequest", STAMUNIT_OCCURENCES, "Number of VINF_EM_PENDING_REQUEST returns.");
406 STAM_REG(pVM, &pVM->vmm.s.StatRZRetPatchTPR, STAMTYPE_COUNTER, "/VMM/RZRet/PatchTPR", STAMUNIT_OCCURENCES, "Number of VINF_EM_HWACCM_PATCH_TPR_INSTR returns.");
407 STAM_REG(pVM, &pVM->vmm.s.StatRZRetCallRing3, STAMTYPE_COUNTER, "/VMM/RZCallR3/Misc", STAMUNIT_OCCURENCES, "Number of Other ring-3 calls.");
408 STAM_REG(pVM, &pVM->vmm.s.StatRZCallPDMLock, STAMTYPE_COUNTER, "/VMM/RZCallR3/PDMLock", STAMUNIT_OCCURENCES, "Number of VMMCALLRING3_PDM_LOCK calls.");
409 STAM_REG(pVM, &pVM->vmm.s.StatRZCallPDMQueueFlush, STAMTYPE_COUNTER, "/VMM/RZCallR3/PDMQueueFlush", STAMUNIT_OCCURENCES, "Number of VMMCALLRING3_PDM_QUEUE_FLUSH calls.");
410 STAM_REG(pVM, &pVM->vmm.s.StatRZCallPGMLock, STAMTYPE_COUNTER, "/VMM/RZCallR3/PGMLock", STAMUNIT_OCCURENCES, "Number of VMMCALLRING3_PGM_LOCK calls.");
411 STAM_REG(pVM, &pVM->vmm.s.StatRZCallPGMPoolGrow, STAMTYPE_COUNTER, "/VMM/RZCallR3/PGMPoolGrow", STAMUNIT_OCCURENCES, "Number of VMMCALLRING3_PGM_POOL_GROW calls.");
412 STAM_REG(pVM, &pVM->vmm.s.StatRZCallPGMMapChunk, STAMTYPE_COUNTER, "/VMM/RZCallR3/PGMMapChunk", STAMUNIT_OCCURENCES, "Number of VMMCALLRING3_PGM_MAP_CHUNK calls.");
413 STAM_REG(pVM, &pVM->vmm.s.StatRZCallPGMAllocHandy, STAMTYPE_COUNTER, "/VMM/RZCallR3/PGMAllocHandy", STAMUNIT_OCCURENCES, "Number of VMMCALLRING3_PGM_ALLOCATE_HANDY_PAGES calls.");
414 STAM_REG(pVM, &pVM->vmm.s.StatRZCallRemReplay, STAMTYPE_COUNTER, "/VMM/RZCallR3/REMReplay", STAMUNIT_OCCURENCES, "Number of VMMCALLRING3_REM_REPLAY_HANDLER_NOTIFICATIONS calls.");
415 STAM_REG(pVM, &pVM->vmm.s.StatRZCallLogFlush, STAMTYPE_COUNTER, "/VMM/RZCallR3/VMMLogFlush", STAMUNIT_OCCURENCES, "Number of VMMCALLRING3_VMM_LOGGER_FLUSH calls.");
416 STAM_REG(pVM, &pVM->vmm.s.StatRZCallVMSetError, STAMTYPE_COUNTER, "/VMM/RZCallR3/VMSetError", STAMUNIT_OCCURENCES, "Number of VMMCALLRING3_VM_SET_ERROR calls.");
417 STAM_REG(pVM, &pVM->vmm.s.StatRZCallVMSetRuntimeError, STAMTYPE_COUNTER, "/VMM/RZCallR3/VMRuntimeError", STAMUNIT_OCCURENCES, "Number of VMMCALLRING3_VM_SET_RUNTIME_ERROR calls.");
418
419#ifdef VBOX_WITH_STATISTICS
420 for (VMCPUID i = 0; i < pVM->cCpus; i++)
421 {
422 STAMR3RegisterF(pVM, &pVM->aCpus[i].vmm.s.CallRing3JmpBufR0.cbUsedMax, STAMTYPE_U32_RESET, STAMVISIBILITY_ALWAYS, STAMUNIT_BYTES, "Max amount of stack used.", "/VMM/Stack/CPU%u/Max", i);
423 STAMR3RegisterF(pVM, &pVM->aCpus[i].vmm.s.CallRing3JmpBufR0.cbUsedAvg, STAMTYPE_U32, STAMVISIBILITY_ALWAYS, STAMUNIT_BYTES, "Average stack usage.", "/VMM/Stack/CPU%u/Avg", i);
424 STAMR3RegisterF(pVM, &pVM->aCpus[i].vmm.s.CallRing3JmpBufR0.cUsedTotal, STAMTYPE_U64, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of stack usages.", "/VMM/Stack/CPU%u/Uses", i);
425 }
426#endif
427}
428
429
430/**
431 * Initializes the per-VCPU VMM.
432 *
433 * @returns VBox status code.
434 * @param pVM The VM to operate on.
435 */
436VMMR3DECL(int) VMMR3InitCPU(PVM pVM)
437{
438 LogFlow(("VMMR3InitCPU\n"));
439 return VINF_SUCCESS;
440}
441
442
443/**
444 * Ring-3 init finalizing.
445 *
446 * @returns VBox status code.
447 * @param pVM The VM handle.
448 */
449VMMR3DECL(int) VMMR3InitFinalize(PVM pVM)
450{
451 int rc;
452
453 /*
454 * Set page attributes to r/w for stack pages.
455 */
456 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
457 {
458 rc = PGMMapSetPage(pVM, pVM->aCpus[idCpu].vmm.s.pbEMTStackRC, VMM_STACK_SIZE,
459 X86_PTE_P | X86_PTE_A | X86_PTE_D | X86_PTE_RW);
460 AssertRCReturn(rc, rc);
461 }
462
463 /*
464 * Create the EMT yield timer.
465 */
466 rc = TMR3TimerCreateInternal(pVM, TMCLOCK_REAL, vmmR3YieldEMT, NULL, "EMT Yielder", &pVM->vmm.s.pYieldTimer);
467 AssertRCReturn(rc, rc);
468
469 rc = TMTimerSetMillies(pVM->vmm.s.pYieldTimer, pVM->vmm.s.cYieldEveryMillies);
470 AssertRCReturn(rc, rc);
471
472#ifdef VBOX_WITH_NMI
473 /*
474 * Map the host APIC into GC - This is AMD/Intel + Host OS specific!
475 */
476 rc = PGMMap(pVM, pVM->vmm.s.GCPtrApicBase, 0xfee00000, PAGE_SIZE,
477 X86_PTE_P | X86_PTE_RW | X86_PTE_PWT | X86_PTE_PCD | X86_PTE_A | X86_PTE_D);
478 AssertRCReturn(rc, rc);
479#endif
480
481#ifdef VBOX_STRICT_VMM_STACK
482 /*
483 * Setup the stack guard pages: Two inaccessible pages at each sides of the
484 * stack to catch over/under-flows.
485 */
486 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
487 {
488 uint8_t *pbEMTStackR3 = pVM->aCpus[idCpu].vmm.s.pbEMTStackR3;
489
490 memset(pbEMTStackR3 - PAGE_SIZE, 0xcc, PAGE_SIZE);
491 MMR3HyperSetGuard(pVM, pbEMTStackR3 - PAGE_SIZE, PAGE_SIZE, true /*fSet*/);
492
493 memset(pbEMTStackR3 + VMM_STACK_SIZE, 0xcc, PAGE_SIZE);
494 MMR3HyperSetGuard(pVM, pbEMTStackR3 + VMM_STACK_SIZE, PAGE_SIZE, true /*fSet*/);
495 }
496 pVM->vmm.s.fStackGuardsStationed = true;
497#endif
498
499 return VINF_SUCCESS;
500}
501
502
503/**
504 * Initializes the R0 VMM.
505 *
506 * @returns VBox status code.
507 * @param pVM The VM to operate on.
508 */
509VMMR3DECL(int) VMMR3InitR0(PVM pVM)
510{
511 int rc;
512 PVMCPU pVCpu = VMMGetCpu(pVM);
513 Assert(pVCpu && pVCpu->idCpu == 0);
514
515#ifdef LOG_ENABLED
516 /*
517 * Initialize the ring-0 logger if we haven't done so yet.
518 */
519 if ( pVCpu->vmm.s.pR0LoggerR3
520 && !pVCpu->vmm.s.pR0LoggerR3->fCreated)
521 {
522 rc = VMMR3UpdateLoggers(pVM);
523 if (RT_FAILURE(rc))
524 return rc;
525 }
526#endif
527
528 /*
529 * Call Ring-0 entry with init code.
530 */
531 for (;;)
532 {
533#ifdef NO_SUPCALLR0VMM
534 //rc = VERR_GENERAL_FAILURE;
535 rc = VINF_SUCCESS;
536#else
537 rc = SUPR3CallVMMR0Ex(pVM->pVMR0, 0 /*idCpu*/, VMMR0_DO_VMMR0_INIT, VMMGetSvnRev(), NULL);
538#endif
539 /*
540 * Flush the logs.
541 */
542#ifdef LOG_ENABLED
543 if ( pVCpu->vmm.s.pR0LoggerR3
544 && pVCpu->vmm.s.pR0LoggerR3->Logger.offScratch > 0)
545 RTLogFlushToLogger(&pVCpu->vmm.s.pR0LoggerR3->Logger, NULL);
546#endif
547 if (rc != VINF_VMM_CALL_HOST)
548 break;
549 rc = vmmR3ServiceCallRing3Request(pVM, pVCpu);
550 if (RT_FAILURE(rc) || (rc >= VINF_EM_FIRST && rc <= VINF_EM_LAST))
551 break;
552 /* Resume R0 */
553 }
554
555 if (RT_FAILURE(rc) || (rc >= VINF_EM_FIRST && rc <= VINF_EM_LAST))
556 {
557 LogRel(("R0 init failed, rc=%Rra\n", rc));
558 if (RT_SUCCESS(rc))
559 rc = VERR_INTERNAL_ERROR;
560 }
561 return rc;
562}
563
564
565/**
566 * Initializes the RC VMM.
567 *
568 * @returns VBox status code.
569 * @param pVM The VM to operate on.
570 */
571VMMR3DECL(int) VMMR3InitRC(PVM pVM)
572{
573 PVMCPU pVCpu = VMMGetCpu(pVM);
574 Assert(pVCpu && pVCpu->idCpu == 0);
575
576 /* In VMX mode, there's no need to init RC. */
577 if (pVM->vmm.s.fSwitcherDisabled)
578 return VINF_SUCCESS;
579
580 AssertReturn(pVM->cCpus == 1, VERR_RAW_MODE_INVALID_SMP);
581
582 /*
583 * Call VMMGCInit():
584 * -# resolve the address.
585 * -# setup stackframe and EIP to use the trampoline.
586 * -# do a generic hypervisor call.
587 */
588 RTRCPTR RCPtrEP;
589 int rc = PDMR3LdrGetSymbolRC(pVM, VMMGC_MAIN_MODULE_NAME, "VMMGCEntry", &RCPtrEP);
590 if (RT_SUCCESS(rc))
591 {
592 CPUMHyperSetCtxCore(pVCpu, NULL);
593 CPUMSetHyperESP(pVCpu, pVCpu->vmm.s.pbEMTStackBottomRC); /* Clear the stack. */
594 uint64_t u64TS = RTTimeProgramStartNanoTS();
595 CPUMPushHyper(pVCpu, (uint32_t)(u64TS >> 32)); /* Param 3: The program startup TS - Hi. */
596 CPUMPushHyper(pVCpu, (uint32_t)u64TS); /* Param 3: The program startup TS - Lo. */
597 CPUMPushHyper(pVCpu, VMMGetSvnRev()); /* Param 2: Version argument. */
598 CPUMPushHyper(pVCpu, VMMGC_DO_VMMGC_INIT); /* Param 1: Operation. */
599 CPUMPushHyper(pVCpu, pVM->pVMRC); /* Param 0: pVM */
600 CPUMPushHyper(pVCpu, 5 * sizeof(RTRCPTR)); /* trampoline param: stacksize. */
601 CPUMPushHyper(pVCpu, RCPtrEP); /* Call EIP. */
602 CPUMSetHyperEIP(pVCpu, pVM->vmm.s.pfnCallTrampolineRC);
603 Assert(CPUMGetHyperCR3(pVCpu) && CPUMGetHyperCR3(pVCpu) == PGMGetHyperCR3(pVCpu));
604
605 for (;;)
606 {
607#ifdef NO_SUPCALLR0VMM
608 //rc = VERR_GENERAL_FAILURE;
609 rc = VINF_SUCCESS;
610#else
611 rc = SUPR3CallVMMR0(pVM->pVMR0, 0 /* VCPU 0 */, VMMR0_DO_CALL_HYPERVISOR, NULL);
612#endif
613#ifdef LOG_ENABLED
614 PRTLOGGERRC pLogger = pVM->vmm.s.pRCLoggerR3;
615 if ( pLogger
616 && pLogger->offScratch > 0)
617 RTLogFlushRC(NULL, pLogger);
618#endif
619#ifdef VBOX_WITH_RC_RELEASE_LOGGING
620 PRTLOGGERRC pRelLogger = pVM->vmm.s.pRCRelLoggerR3;
621 if (RT_UNLIKELY(pRelLogger && pRelLogger->offScratch > 0))
622 RTLogFlushRC(RTLogRelDefaultInstance(), pRelLogger);
623#endif
624 if (rc != VINF_VMM_CALL_HOST)
625 break;
626 rc = vmmR3ServiceCallRing3Request(pVM, pVCpu);
627 if (RT_FAILURE(rc) || (rc >= VINF_EM_FIRST && rc <= VINF_EM_LAST))
628 break;
629 }
630
631 if (RT_FAILURE(rc) || (rc >= VINF_EM_FIRST && rc <= VINF_EM_LAST))
632 {
633 VMMR3FatalDump(pVM, pVCpu, rc);
634 if (rc >= VINF_EM_FIRST && rc <= VINF_EM_LAST)
635 rc = VERR_INTERNAL_ERROR;
636 }
637 AssertRC(rc);
638 }
639 return rc;
640}
641
642
643/**
644 * Terminate the VMM bits.
645 *
646 * @returns VINF_SUCCESS.
647 * @param pVM The VM handle.
648 */
649VMMR3DECL(int) VMMR3Term(PVM pVM)
650{
651 PVMCPU pVCpu = VMMGetCpu(pVM);
652 Assert(pVCpu && pVCpu->idCpu == 0);
653
654 /*
655 * Call Ring-0 entry with termination code.
656 */
657 int rc;
658 for (;;)
659 {
660#ifdef NO_SUPCALLR0VMM
661 //rc = VERR_GENERAL_FAILURE;
662 rc = VINF_SUCCESS;
663#else
664 rc = SUPR3CallVMMR0Ex(pVM->pVMR0, 0 /*idCpu*/, VMMR0_DO_VMMR0_TERM, 0, NULL);
665#endif
666 /*
667 * Flush the logs.
668 */
669#ifdef LOG_ENABLED
670 if ( pVCpu->vmm.s.pR0LoggerR3
671 && pVCpu->vmm.s.pR0LoggerR3->Logger.offScratch > 0)
672 RTLogFlushToLogger(&pVCpu->vmm.s.pR0LoggerR3->Logger, NULL);
673#endif
674 if (rc != VINF_VMM_CALL_HOST)
675 break;
676 rc = vmmR3ServiceCallRing3Request(pVM, pVCpu);
677 if (RT_FAILURE(rc) || (rc >= VINF_EM_FIRST && rc <= VINF_EM_LAST))
678 break;
679 /* Resume R0 */
680 }
681 if (RT_FAILURE(rc) || (rc >= VINF_EM_FIRST && rc <= VINF_EM_LAST))
682 {
683 LogRel(("VMMR3Term: R0 term failed, rc=%Rra. (warning)\n", rc));
684 if (RT_SUCCESS(rc))
685 rc = VERR_INTERNAL_ERROR;
686 }
687
688 RTCritSectDelete(&pVM->vmm.s.CritSectSync);
689 for (VMCPUID i = 0; i < pVM->cCpus; i++)
690 {
691 RTSemEventDestroy(pVM->vmm.s.pahEvtRendezvousEnterOrdered[i]);
692 pVM->vmm.s.pahEvtRendezvousEnterOrdered[i] = NIL_RTSEMEVENT;
693 }
694 RTSemEventDestroy(pVM->vmm.s.hEvtRendezvousEnterOneByOne);
695 pVM->vmm.s.hEvtRendezvousEnterOneByOne = NIL_RTSEMEVENT;
696 RTSemEventMultiDestroy(pVM->vmm.s.hEvtMulRendezvousEnterAllAtOnce);
697 pVM->vmm.s.hEvtMulRendezvousEnterAllAtOnce = NIL_RTSEMEVENTMULTI;
698 RTSemEventMultiDestroy(pVM->vmm.s.hEvtMulRendezvousDone);
699 pVM->vmm.s.hEvtMulRendezvousDone = NIL_RTSEMEVENTMULTI;
700 RTSemEventDestroy(pVM->vmm.s.hEvtRendezvousDoneCaller);
701 pVM->vmm.s.hEvtRendezvousDoneCaller = NIL_RTSEMEVENT;
702
703#ifdef VBOX_STRICT_VMM_STACK
704 /*
705 * Make the two stack guard pages present again.
706 */
707 if (pVM->vmm.s.fStackGuardsStationed)
708 {
709 for (VMCPUID i = 0; i < pVM->cCpus; i++)
710 {
711 uint8_t *pbEMTStackR3 = pVM->aCpus[i].vmm.s.pbEMTStackR3;
712 MMR3HyperSetGuard(pVM, pbEMTStackR3 - PAGE_SIZE, PAGE_SIZE, false /*fSet*/);
713 MMR3HyperSetGuard(pVM, pbEMTStackR3 + VMM_STACK_SIZE, PAGE_SIZE, false /*fSet*/);
714 }
715 pVM->vmm.s.fStackGuardsStationed = false;
716 }
717#endif
718 return rc;
719}
720
721
722/**
723 * Terminates the per-VCPU VMM.
724 *
725 * Termination means cleaning up and freeing all resources,
726 * the VM it self is at this point powered off or suspended.
727 *
728 * @returns VBox status code.
729 * @param pVM The VM to operate on.
730 */
731VMMR3DECL(int) VMMR3TermCPU(PVM pVM)
732{
733 return VINF_SUCCESS;
734}
735
736
737/**
738 * Applies relocations to data and code managed by this
739 * component. This function will be called at init and
740 * whenever the VMM need to relocate it self inside the GC.
741 *
742 * The VMM will need to apply relocations to the core code.
743 *
744 * @param pVM The VM handle.
745 * @param offDelta The relocation delta.
746 */
747VMMR3DECL(void) VMMR3Relocate(PVM pVM, RTGCINTPTR offDelta)
748{
749 LogFlow(("VMMR3Relocate: offDelta=%RGv\n", offDelta));
750
751 /*
752 * Recalc the RC address.
753 */
754 pVM->vmm.s.pvCoreCodeRC = MMHyperR3ToRC(pVM, pVM->vmm.s.pvCoreCodeR3);
755
756 /*
757 * The stack.
758 */
759 for (VMCPUID i = 0; i < pVM->cCpus; i++)
760 {
761 PVMCPU pVCpu = &pVM->aCpus[i];
762
763 CPUMSetHyperESP(pVCpu, CPUMGetHyperESP(pVCpu) + offDelta);
764
765 pVCpu->vmm.s.pbEMTStackRC = MMHyperR3ToRC(pVM, pVCpu->vmm.s.pbEMTStackR3);
766 pVCpu->vmm.s.pbEMTStackBottomRC = pVCpu->vmm.s.pbEMTStackRC + VMM_STACK_SIZE;
767 }
768
769 /*
770 * All the switchers.
771 */
772 vmmR3SwitcherRelocate(pVM, offDelta);
773
774 /*
775 * Get other RC entry points.
776 */
777 int rc = PDMR3LdrGetSymbolRC(pVM, VMMGC_MAIN_MODULE_NAME, "CPUMGCResumeGuest", &pVM->vmm.s.pfnCPUMRCResumeGuest);
778 AssertReleaseMsgRC(rc, ("CPUMGCResumeGuest not found! rc=%Rra\n", rc));
779
780 rc = PDMR3LdrGetSymbolRC(pVM, VMMGC_MAIN_MODULE_NAME, "CPUMGCResumeGuestV86", &pVM->vmm.s.pfnCPUMRCResumeGuestV86);
781 AssertReleaseMsgRC(rc, ("CPUMGCResumeGuestV86 not found! rc=%Rra\n", rc));
782
783 /*
784 * Update the logger.
785 */
786 VMMR3UpdateLoggers(pVM);
787}
788
789
790/**
791 * Updates the settings for the RC and R0 loggers.
792 *
793 * @returns VBox status code.
794 * @param pVM The VM handle.
795 */
796VMMR3DECL(int) VMMR3UpdateLoggers(PVM pVM)
797{
798 /*
799 * Simply clone the logger instance (for RC).
800 */
801 int rc = VINF_SUCCESS;
802 RTRCPTR RCPtrLoggerFlush = 0;
803
804 if (pVM->vmm.s.pRCLoggerR3
805#ifdef VBOX_WITH_RC_RELEASE_LOGGING
806 || pVM->vmm.s.pRCRelLoggerR3
807#endif
808 )
809 {
810 rc = PDMR3LdrGetSymbolRC(pVM, VMMGC_MAIN_MODULE_NAME, "vmmGCLoggerFlush", &RCPtrLoggerFlush);
811 AssertReleaseMsgRC(rc, ("vmmGCLoggerFlush not found! rc=%Rra\n", rc));
812 }
813
814 if (pVM->vmm.s.pRCLoggerR3)
815 {
816 RTRCPTR RCPtrLoggerWrapper = 0;
817 rc = PDMR3LdrGetSymbolRC(pVM, VMMGC_MAIN_MODULE_NAME, "vmmGCLoggerWrapper", &RCPtrLoggerWrapper);
818 AssertReleaseMsgRC(rc, ("vmmGCLoggerWrapper not found! rc=%Rra\n", rc));
819
820 pVM->vmm.s.pRCLoggerRC = MMHyperR3ToRC(pVM, pVM->vmm.s.pRCLoggerR3);
821 rc = RTLogCloneRC(NULL /* default */, pVM->vmm.s.pRCLoggerR3, pVM->vmm.s.cbRCLogger,
822 RCPtrLoggerWrapper, RCPtrLoggerFlush, RTLOGFLAGS_BUFFERED);
823 AssertReleaseMsgRC(rc, ("RTLogCloneRC failed! rc=%Rra\n", rc));
824 }
825
826#ifdef VBOX_WITH_RC_RELEASE_LOGGING
827 if (pVM->vmm.s.pRCRelLoggerR3)
828 {
829 RTRCPTR RCPtrLoggerWrapper = 0;
830 rc = PDMR3LdrGetSymbolRC(pVM, VMMGC_MAIN_MODULE_NAME, "vmmGCRelLoggerWrapper", &RCPtrLoggerWrapper);
831 AssertReleaseMsgRC(rc, ("vmmGCRelLoggerWrapper not found! rc=%Rra\n", rc));
832
833 pVM->vmm.s.pRCRelLoggerRC = MMHyperR3ToRC(pVM, pVM->vmm.s.pRCRelLoggerR3);
834 rc = RTLogCloneRC(RTLogRelDefaultInstance(), pVM->vmm.s.pRCRelLoggerR3, pVM->vmm.s.cbRCRelLogger,
835 RCPtrLoggerWrapper, RCPtrLoggerFlush, RTLOGFLAGS_BUFFERED);
836 AssertReleaseMsgRC(rc, ("RTLogCloneRC failed! rc=%Rra\n", rc));
837 }
838#endif /* VBOX_WITH_RC_RELEASE_LOGGING */
839
840#ifdef LOG_ENABLED
841 /*
842 * For the ring-0 EMT logger, we use a per-thread logger instance
843 * in ring-0. Only initialize it once.
844 */
845 for (VMCPUID i = 0; i < pVM->cCpus; i++)
846 {
847 PVMCPU pVCpu = &pVM->aCpus[i];
848 PVMMR0LOGGER pR0LoggerR3 = pVCpu->vmm.s.pR0LoggerR3;
849 if (pR0LoggerR3)
850 {
851 if (!pR0LoggerR3->fCreated)
852 {
853 RTR0PTR pfnLoggerWrapper = NIL_RTR0PTR;
854 rc = PDMR3LdrGetSymbolR0(pVM, VMMR0_MAIN_MODULE_NAME, "vmmR0LoggerWrapper", &pfnLoggerWrapper);
855 AssertReleaseMsgRCReturn(rc, ("vmmR0LoggerWrapper not found! rc=%Rra\n", rc), rc);
856
857 RTR0PTR pfnLoggerFlush = NIL_RTR0PTR;
858 rc = PDMR3LdrGetSymbolR0(pVM, VMMR0_MAIN_MODULE_NAME, "vmmR0LoggerFlush", &pfnLoggerFlush);
859 AssertReleaseMsgRCReturn(rc, ("vmmR0LoggerFlush not found! rc=%Rra\n", rc), rc);
860
861 rc = RTLogCreateForR0(&pR0LoggerR3->Logger, pR0LoggerR3->cbLogger,
862 *(PFNRTLOGGER *)&pfnLoggerWrapper, *(PFNRTLOGFLUSH *)&pfnLoggerFlush,
863 RTLOGFLAGS_BUFFERED, RTLOGDEST_DUMMY);
864 AssertReleaseMsgRCReturn(rc, ("RTLogCreateForR0 failed! rc=%Rra\n", rc), rc);
865
866 RTR0PTR pfnLoggerPrefix = NIL_RTR0PTR;
867 rc = PDMR3LdrGetSymbolR0(pVM, VMMR0_MAIN_MODULE_NAME, "vmmR0LoggerPrefix", &pfnLoggerPrefix);
868 AssertReleaseMsgRCReturn(rc, ("vmmR0LoggerPrefix not found! rc=%Rra\n", rc), rc);
869 rc = RTLogSetCustomPrefixCallback(&pR0LoggerR3->Logger, *(PFNRTLOGPREFIX *)&pfnLoggerPrefix, NULL);
870 AssertReleaseMsgRCReturn(rc, ("RTLogSetCustomPrefixCallback failed! rc=%Rra\n", rc), rc);
871
872 pR0LoggerR3->idCpu = i;
873 pR0LoggerR3->fCreated = true;
874 pR0LoggerR3->fFlushingDisabled = false;
875
876 }
877
878 rc = RTLogCopyGroupsAndFlags(&pR0LoggerR3->Logger, NULL /* default */, pVM->vmm.s.pRCLoggerR3->fFlags, RTLOGFLAGS_BUFFERED);
879 AssertRC(rc);
880 }
881 }
882#endif
883 return rc;
884}
885
886
887/**
888 * Gets the pointer to a buffer containing the R0/RC RTAssertMsg1Weak output.
889 *
890 * @returns Pointer to the buffer.
891 * @param pVM The VM handle.
892 */
893VMMR3DECL(const char *) VMMR3GetRZAssertMsg1(PVM pVM)
894{
895 if (HWACCMIsEnabled(pVM))
896 return pVM->vmm.s.szRing0AssertMsg1;
897
898 RTRCPTR RCPtr;
899 int rc = PDMR3LdrGetSymbolRC(pVM, NULL, "g_szRTAssertMsg1", &RCPtr);
900 if (RT_SUCCESS(rc))
901 return (const char *)MMHyperRCToR3(pVM, RCPtr);
902
903 return NULL;
904}
905
906
907/**
908 * Gets the pointer to a buffer containing the R0/RC RTAssertMsg2Weak output.
909 *
910 * @returns Pointer to the buffer.
911 * @param pVM The VM handle.
912 */
913VMMR3DECL(const char *) VMMR3GetRZAssertMsg2(PVM pVM)
914{
915 if (HWACCMIsEnabled(pVM))
916 return pVM->vmm.s.szRing0AssertMsg2;
917
918 RTRCPTR RCPtr;
919 int rc = PDMR3LdrGetSymbolRC(pVM, NULL, "g_szRTAssertMsg2", &RCPtr);
920 if (RT_SUCCESS(rc))
921 return (const char *)MMHyperRCToR3(pVM, RCPtr);
922
923 return NULL;
924}
925
926
927/**
928 * Execute state save operation.
929 *
930 * @returns VBox status code.
931 * @param pVM VM Handle.
932 * @param pSSM SSM operation handle.
933 */
934static DECLCALLBACK(int) vmmR3Save(PVM pVM, PSSMHANDLE pSSM)
935{
936 LogFlow(("vmmR3Save:\n"));
937
938 /*
939 * Save the started/stopped state of all CPUs except 0 as it will always
940 * be running. This avoids breaking the saved state version. :-)
941 */
942 for (VMCPUID i = 1; i < pVM->cCpus; i++)
943 SSMR3PutBool(pSSM, VMCPUSTATE_IS_STARTED(VMCPU_GET_STATE(&pVM->aCpus[i])));
944
945 return SSMR3PutU32(pSSM, UINT32_MAX); /* terminator */
946}
947
948
949/**
950 * Execute state load operation.
951 *
952 * @returns VBox status code.
953 * @param pVM VM Handle.
954 * @param pSSM SSM operation handle.
955 * @param uVersion Data layout version.
956 * @param uPass The data pass.
957 */
958static DECLCALLBACK(int) vmmR3Load(PVM pVM, PSSMHANDLE pSSM, uint32_t uVersion, uint32_t uPass)
959{
960 LogFlow(("vmmR3Load:\n"));
961 Assert(uPass == SSM_PASS_FINAL); NOREF(uPass);
962
963 /*
964 * Validate version.
965 */
966 if ( uVersion != VMM_SAVED_STATE_VERSION
967 && uVersion != VMM_SAVED_STATE_VERSION_3_0)
968 {
969 AssertMsgFailed(("vmmR3Load: Invalid version uVersion=%u!\n", uVersion));
970 return VERR_SSM_UNSUPPORTED_DATA_UNIT_VERSION;
971 }
972
973 if (uVersion <= VMM_SAVED_STATE_VERSION_3_0)
974 {
975 /* Ignore the stack bottom, stack pointer and stack bits. */
976 RTRCPTR RCPtrIgnored;
977 SSMR3GetRCPtr(pSSM, &RCPtrIgnored);
978 SSMR3GetRCPtr(pSSM, &RCPtrIgnored);
979#ifdef RT_OS_DARWIN
980 if ( SSMR3HandleVersion(pSSM) >= VBOX_FULL_VERSION_MAKE(3,0,0)
981 && SSMR3HandleVersion(pSSM) < VBOX_FULL_VERSION_MAKE(3,1,0)
982 && SSMR3HandleRevision(pSSM) >= 48858
983 && ( !strcmp(SSMR3HandleHostOSAndArch(pSSM), "darwin.x86")
984 || !strcmp(SSMR3HandleHostOSAndArch(pSSM), "") )
985 )
986 SSMR3Skip(pSSM, 16384);
987 else
988 SSMR3Skip(pSSM, 8192);
989#else
990 SSMR3Skip(pSSM, 8192);
991#endif
992 }
993
994 /*
995 * Restore the VMCPU states. VCPU 0 is always started.
996 */
997 VMCPU_SET_STATE(&pVM->aCpus[0], VMCPUSTATE_STARTED);
998 for (VMCPUID i = 1; i < pVM->cCpus; i++)
999 {
1000 bool fStarted;
1001 int rc = SSMR3GetBool(pSSM, &fStarted);
1002 if (RT_FAILURE(rc))
1003 return rc;
1004 VMCPU_SET_STATE(&pVM->aCpus[i], fStarted ? VMCPUSTATE_STARTED : VMCPUSTATE_STOPPED);
1005 }
1006
1007 /* terminator */
1008 uint32_t u32;
1009 int rc = SSMR3GetU32(pSSM, &u32);
1010 if (RT_FAILURE(rc))
1011 return rc;
1012 if (u32 != UINT32_MAX)
1013 {
1014 AssertMsgFailed(("u32=%#x\n", u32));
1015 return VERR_SSM_DATA_UNIT_FORMAT_CHANGED;
1016 }
1017 return VINF_SUCCESS;
1018}
1019
1020
1021/**
1022 * Resolve a builtin RC symbol.
1023 *
1024 * Called by PDM when loading or relocating RC modules.
1025 *
1026 * @returns VBox status
1027 * @param pVM VM Handle.
1028 * @param pszSymbol Symbol to resolv
1029 * @param pRCPtrValue Where to store the symbol value.
1030 *
1031 * @remark This has to work before VMMR3Relocate() is called.
1032 */
1033VMMR3DECL(int) VMMR3GetImportRC(PVM pVM, const char *pszSymbol, PRTRCPTR pRCPtrValue)
1034{
1035 if (!strcmp(pszSymbol, "g_Logger"))
1036 {
1037 if (pVM->vmm.s.pRCLoggerR3)
1038 pVM->vmm.s.pRCLoggerRC = MMHyperR3ToRC(pVM, pVM->vmm.s.pRCLoggerR3);
1039 *pRCPtrValue = pVM->vmm.s.pRCLoggerRC;
1040 }
1041 else if (!strcmp(pszSymbol, "g_RelLogger"))
1042 {
1043#ifdef VBOX_WITH_RC_RELEASE_LOGGING
1044 if (pVM->vmm.s.pRCRelLoggerR3)
1045 pVM->vmm.s.pRCRelLoggerRC = MMHyperR3ToRC(pVM, pVM->vmm.s.pRCRelLoggerR3);
1046 *pRCPtrValue = pVM->vmm.s.pRCRelLoggerRC;
1047#else
1048 *pRCPtrValue = NIL_RTRCPTR;
1049#endif
1050 }
1051 else
1052 return VERR_SYMBOL_NOT_FOUND;
1053 return VINF_SUCCESS;
1054}
1055
1056
1057/**
1058 * Suspends the CPU yielder.
1059 *
1060 * @param pVM The VM handle.
1061 */
1062VMMR3DECL(void) VMMR3YieldSuspend(PVM pVM)
1063{
1064 VMCPU_ASSERT_EMT(&pVM->aCpus[0]);
1065 if (!pVM->vmm.s.cYieldResumeMillies)
1066 {
1067 uint64_t u64Now = TMTimerGet(pVM->vmm.s.pYieldTimer);
1068 uint64_t u64Expire = TMTimerGetExpire(pVM->vmm.s.pYieldTimer);
1069 if (u64Now >= u64Expire || u64Expire == ~(uint64_t)0)
1070 pVM->vmm.s.cYieldResumeMillies = pVM->vmm.s.cYieldEveryMillies;
1071 else
1072 pVM->vmm.s.cYieldResumeMillies = TMTimerToMilli(pVM->vmm.s.pYieldTimer, u64Expire - u64Now);
1073 TMTimerStop(pVM->vmm.s.pYieldTimer);
1074 }
1075 pVM->vmm.s.u64LastYield = RTTimeNanoTS();
1076}
1077
1078
1079/**
1080 * Stops the CPU yielder.
1081 *
1082 * @param pVM The VM handle.
1083 */
1084VMMR3DECL(void) VMMR3YieldStop(PVM pVM)
1085{
1086 if (!pVM->vmm.s.cYieldResumeMillies)
1087 TMTimerStop(pVM->vmm.s.pYieldTimer);
1088 pVM->vmm.s.cYieldResumeMillies = pVM->vmm.s.cYieldEveryMillies;
1089 pVM->vmm.s.u64LastYield = RTTimeNanoTS();
1090}
1091
1092
1093/**
1094 * Resumes the CPU yielder when it has been a suspended or stopped.
1095 *
1096 * @param pVM The VM handle.
1097 */
1098VMMR3DECL(void) VMMR3YieldResume(PVM pVM)
1099{
1100 if (pVM->vmm.s.cYieldResumeMillies)
1101 {
1102 TMTimerSetMillies(pVM->vmm.s.pYieldTimer, pVM->vmm.s.cYieldResumeMillies);
1103 pVM->vmm.s.cYieldResumeMillies = 0;
1104 }
1105}
1106
1107
1108/**
1109 * Internal timer callback function.
1110 *
1111 * @param pVM The VM.
1112 * @param pTimer The timer handle.
1113 * @param pvUser User argument specified upon timer creation.
1114 */
1115static DECLCALLBACK(void) vmmR3YieldEMT(PVM pVM, PTMTIMER pTimer, void *pvUser)
1116{
1117 /*
1118 * This really needs some careful tuning. While we shouldn't be too greedy since
1119 * that'll cause the rest of the system to stop up, we shouldn't be too nice either
1120 * because that'll cause us to stop up.
1121 *
1122 * The current logic is to use the default interval when there is no lag worth
1123 * mentioning, but when we start accumulating lag we don't bother yielding at all.
1124 *
1125 * (This depends on the TMCLOCK_VIRTUAL_SYNC to be scheduled before TMCLOCK_REAL
1126 * so the lag is up to date.)
1127 */
1128 const uint64_t u64Lag = TMVirtualSyncGetLag(pVM);
1129 if ( u64Lag < 50000000 /* 50ms */
1130 || ( u64Lag < 1000000000 /* 1s */
1131 && RTTimeNanoTS() - pVM->vmm.s.u64LastYield < 500000000 /* 500 ms */)
1132 )
1133 {
1134 uint64_t u64Elapsed = RTTimeNanoTS();
1135 pVM->vmm.s.u64LastYield = u64Elapsed;
1136
1137 RTThreadYield();
1138
1139#ifdef LOG_ENABLED
1140 u64Elapsed = RTTimeNanoTS() - u64Elapsed;
1141 Log(("vmmR3YieldEMT: %RI64 ns\n", u64Elapsed));
1142#endif
1143 }
1144 TMTimerSetMillies(pTimer, pVM->vmm.s.cYieldEveryMillies);
1145}
1146
1147
1148/**
1149 * Executes guest code in the raw-mode context.
1150 *
1151 * @param pVM VM handle.
1152 * @param pVCpu The VMCPU to operate on.
1153 */
1154VMMR3DECL(int) VMMR3RawRunGC(PVM pVM, PVMCPU pVCpu)
1155{
1156 Log2(("VMMR3RawRunGC: (cs:eip=%04x:%08x)\n", CPUMGetGuestCS(pVCpu), CPUMGetGuestEIP(pVCpu)));
1157
1158 AssertReturn(pVM->cCpus == 1, VERR_RAW_MODE_INVALID_SMP);
1159
1160 /*
1161 * Set the EIP and ESP.
1162 */
1163 CPUMSetHyperEIP(pVCpu, CPUMGetGuestEFlags(pVCpu) & X86_EFL_VM
1164 ? pVM->vmm.s.pfnCPUMRCResumeGuestV86
1165 : pVM->vmm.s.pfnCPUMRCResumeGuest);
1166 CPUMSetHyperESP(pVCpu, pVCpu->vmm.s.pbEMTStackBottomRC);
1167
1168 /*
1169 * We hide log flushes (outer) and hypervisor interrupts (inner).
1170 */
1171 for (;;)
1172 {
1173#ifdef VBOX_STRICT
1174 if (RT_UNLIKELY(!CPUMGetHyperCR3(pVCpu) || CPUMGetHyperCR3(pVCpu) != PGMGetHyperCR3(pVCpu)))
1175 EMR3FatalError(pVCpu, VERR_VMM_HYPER_CR3_MISMATCH);
1176 PGMMapCheck(pVM);
1177#endif
1178 int rc;
1179 do
1180 {
1181#ifdef NO_SUPCALLR0VMM
1182 rc = VERR_GENERAL_FAILURE;
1183#else
1184 rc = SUPR3CallVMMR0Fast(pVM->pVMR0, VMMR0_DO_RAW_RUN, 0);
1185 if (RT_LIKELY(rc == VINF_SUCCESS))
1186 rc = pVCpu->vmm.s.iLastGZRc;
1187#endif
1188 } while (rc == VINF_EM_RAW_INTERRUPT_HYPER);
1189
1190 /*
1191 * Flush the logs.
1192 */
1193#ifdef LOG_ENABLED
1194 PRTLOGGERRC pLogger = pVM->vmm.s.pRCLoggerR3;
1195 if ( pLogger
1196 && pLogger->offScratch > 0)
1197 RTLogFlushRC(NULL, pLogger);
1198#endif
1199#ifdef VBOX_WITH_RC_RELEASE_LOGGING
1200 PRTLOGGERRC pRelLogger = pVM->vmm.s.pRCRelLoggerR3;
1201 if (RT_UNLIKELY(pRelLogger && pRelLogger->offScratch > 0))
1202 RTLogFlushRC(RTLogRelDefaultInstance(), pRelLogger);
1203#endif
1204 if (rc != VINF_VMM_CALL_HOST)
1205 {
1206 Log2(("VMMR3RawRunGC: returns %Rrc (cs:eip=%04x:%08x)\n", rc, CPUMGetGuestCS(pVCpu), CPUMGetGuestEIP(pVCpu)));
1207 return rc;
1208 }
1209 rc = vmmR3ServiceCallRing3Request(pVM, pVCpu);
1210 if (RT_FAILURE(rc))
1211 return rc;
1212 /* Resume GC */
1213 }
1214}
1215
1216
1217/**
1218 * Executes guest code (Intel VT-x and AMD-V).
1219 *
1220 * @param pVM VM handle.
1221 * @param pVCpu The VMCPU to operate on.
1222 */
1223VMMR3DECL(int) VMMR3HwAccRunGC(PVM pVM, PVMCPU pVCpu)
1224{
1225 Log2(("VMMR3HwAccRunGC: (cs:eip=%04x:%08x)\n", CPUMGetGuestCS(pVCpu), CPUMGetGuestEIP(pVCpu)));
1226
1227 for (;;)
1228 {
1229 int rc;
1230 do
1231 {
1232#ifdef NO_SUPCALLR0VMM
1233 rc = VERR_GENERAL_FAILURE;
1234#else
1235 rc = SUPR3CallVMMR0Fast(pVM->pVMR0, VMMR0_DO_HWACC_RUN, pVCpu->idCpu);
1236 if (RT_LIKELY(rc == VINF_SUCCESS))
1237 rc = pVCpu->vmm.s.iLastGZRc;
1238#endif
1239 } while (rc == VINF_EM_RAW_INTERRUPT_HYPER);
1240
1241#ifdef LOG_ENABLED
1242 /*
1243 * Flush the log
1244 */
1245 PVMMR0LOGGER pR0LoggerR3 = pVCpu->vmm.s.pR0LoggerR3;
1246 if ( pR0LoggerR3
1247 && pR0LoggerR3->Logger.offScratch > 0)
1248 RTLogFlushToLogger(&pR0LoggerR3->Logger, NULL);
1249#endif /* !LOG_ENABLED */
1250 if (rc != VINF_VMM_CALL_HOST)
1251 {
1252 Log2(("VMMR3HwAccRunGC: returns %Rrc (cs:eip=%04x:%08x)\n", rc, CPUMGetGuestCS(pVCpu), CPUMGetGuestEIP(pVCpu)));
1253 return rc;
1254 }
1255 rc = vmmR3ServiceCallRing3Request(pVM, pVCpu);
1256 if (RT_FAILURE(rc))
1257 return rc;
1258 /* Resume R0 */
1259 }
1260}
1261
1262/**
1263 * VCPU worker for VMMSendSipi.
1264 *
1265 * @param pVM The VM to operate on.
1266 * @param idCpu Virtual CPU to perform SIPI on
1267 * @param uVector SIPI vector
1268 */
1269DECLCALLBACK(int) vmmR3SendSipi(PVM pVM, VMCPUID idCpu, uint32_t uVector)
1270{
1271 PVMCPU pVCpu = VMMGetCpuById(pVM, idCpu);
1272 VMCPU_ASSERT_EMT(pVCpu);
1273
1274 /** @todo what are we supposed to do if the processor is already running? */
1275 if (EMGetState(pVCpu) != EMSTATE_WAIT_SIPI)
1276 return VERR_ACCESS_DENIED;
1277
1278
1279 PCPUMCTX pCtx = CPUMQueryGuestCtxPtr(pVCpu);
1280
1281 pCtx->cs = uVector << 8;
1282 pCtx->csHid.u64Base = uVector << 12;
1283 pCtx->csHid.u32Limit = 0x0000ffff;
1284 pCtx->rip = 0;
1285
1286 Log(("vmmR3SendSipi for VCPU %d with vector %x\n", uVector));
1287
1288# if 1 /* If we keep the EMSTATE_WAIT_SIPI method, then move this to EM.cpp. */
1289 EMSetState(pVCpu, EMSTATE_HALTED);
1290 return VINF_EM_RESCHEDULE;
1291# else /* And if we go the VMCPU::enmState way it can stay here. */
1292 VMCPU_ASSERT_STATE(pVCpu, VMCPUSTATE_STOPPED);
1293 VMCPU_SET_STATE(pVCpu, VMCPUSTATE_STARTED);
1294 return VINF_SUCCESS;
1295# endif
1296}
1297
1298DECLCALLBACK(int) vmmR3SendInitIpi(PVM pVM, VMCPUID idCpu)
1299{
1300 PVMCPU pVCpu = VMMGetCpuById(pVM, idCpu);
1301 VMCPU_ASSERT_EMT(pVCpu);
1302
1303 Log(("vmmR3SendInitIpi for VCPU %d\n", idCpu));
1304 CPUMR3ResetCpu(pVCpu);
1305 return VINF_EM_WAIT_SIPI;
1306}
1307
1308/**
1309 * Sends SIPI to the virtual CPU by setting CS:EIP into vector-dependent state
1310 * and unhalting processor
1311 *
1312 * @param pVM The VM to operate on.
1313 * @param idCpu Virtual CPU to perform SIPI on
1314 * @param uVector SIPI vector
1315 */
1316VMMR3DECL(void) VMMR3SendSipi(PVM pVM, VMCPUID idCpu, uint32_t uVector)
1317{
1318 AssertReturnVoid(idCpu < pVM->cCpus);
1319
1320 int rc = VMR3ReqCallNoWaitU(pVM->pUVM, idCpu, (PFNRT)vmmR3SendSipi, 3, pVM, idCpu, uVector);
1321 AssertRC(rc);
1322}
1323
1324/**
1325 * Sends init IPI to the virtual CPU.
1326 *
1327 * @param pVM The VM to operate on.
1328 * @param idCpu Virtual CPU to perform int IPI on
1329 */
1330VMMR3DECL(void) VMMR3SendInitIpi(PVM pVM, VMCPUID idCpu)
1331{
1332 AssertReturnVoid(idCpu < pVM->cCpus);
1333
1334 int rc = VMR3ReqCallNoWaitU(pVM->pUVM, idCpu, (PFNRT)vmmR3SendInitIpi, 2, pVM, idCpu);
1335 AssertRC(rc);
1336}
1337
1338/**
1339 * Registers the guest memory range that can be used for patching
1340 *
1341 * @returns VBox status code.
1342 * @param pVM The VM to operate on.
1343 * @param pPatchMem Patch memory range
1344 * @param cbPatchMem Size of the memory range
1345 */
1346VMMR3DECL(int) VMMR3RegisterPatchMemory(PVM pVM, RTGCPTR pPatchMem, unsigned cbPatchMem)
1347{
1348 if (HWACCMIsEnabled(pVM))
1349 return HWACMMR3EnablePatching(pVM, pPatchMem, cbPatchMem);
1350
1351 return VERR_NOT_SUPPORTED;
1352}
1353
1354/**
1355 * Deregisters the guest memory range that can be used for patching
1356 *
1357 * @returns VBox status code.
1358 * @param pVM The VM to operate on.
1359 * @param pPatchMem Patch memory range
1360 * @param cbPatchMem Size of the memory range
1361 */
1362VMMR3DECL(int) VMMR3DeregisterPatchMemory(PVM pVM, RTGCPTR pPatchMem, unsigned cbPatchMem)
1363{
1364 if (HWACCMIsEnabled(pVM))
1365 return HWACMMR3DisablePatching(pVM, pPatchMem, cbPatchMem);
1366
1367 return VINF_SUCCESS;
1368}
1369
1370
1371/**
1372 * VCPU worker for VMMR3SynchronizeAllVCpus.
1373 *
1374 * @param pVM The VM to operate on.
1375 * @param idCpu Virtual CPU to perform SIPI on
1376 * @param uVector SIPI vector
1377 */
1378DECLCALLBACK(int) vmmR3SyncVCpu(PVM pVM)
1379{
1380 /* Block until the job in the caller has finished. */
1381 RTCritSectEnter(&pVM->vmm.s.CritSectSync);
1382 RTCritSectLeave(&pVM->vmm.s.CritSectSync);
1383 return VINF_SUCCESS;
1384}
1385
1386
1387/**
1388 * Atomically execute a callback handler
1389 * Note: This is very expensive; avoid using it frequently!
1390 *
1391 * @param pVM The VM to operate on.
1392 * @param pfnHandler Callback handler
1393 * @param pvUser User specified parameter
1394 *
1395 * @thread EMT
1396 */
1397VMMR3DECL(int) VMMR3AtomicExecuteHandler(PVM pVM, PFNATOMICHANDLER pfnHandler, void *pvUser)
1398{
1399 int rc;
1400 PVMCPU pVCpu = VMMGetCpu(pVM);
1401 AssertReturn(pVCpu, VERR_VM_THREAD_NOT_EMT);
1402
1403 /* Shortcut for the uniprocessor case. */
1404 if (pVM->cCpus == 1)
1405 return pfnHandler(pVM, pvUser);
1406
1407 RTCritSectEnter(&pVM->vmm.s.CritSectSync);
1408 for (VMCPUID idCpu = 0; idCpu < pVM->cCpus; idCpu++)
1409 {
1410 if (idCpu != pVCpu->idCpu)
1411 {
1412 rc = VMR3ReqCallNoWaitU(pVM->pUVM, idCpu, (PFNRT)vmmR3SyncVCpu, 1, pVM);
1413 AssertRC(rc);
1414 }
1415 }
1416 /* Wait until all other VCPUs are waiting for us. */
1417 while (RTCritSectGetWaiters(&pVM->vmm.s.CritSectSync) != (int32_t)(pVM->cCpus - 1))
1418 RTThreadSleep(1);
1419
1420 rc = pfnHandler(pVM, pvUser);
1421 RTCritSectLeave(&pVM->vmm.s.CritSectSync);
1422 return rc;
1423}
1424
1425
1426/**
1427 * Count returns and have the last non-caller EMT wake up the caller.
1428 *
1429 * @returns VBox strict informational status code for EM scheduling. No failures
1430 * will be returned here, those are for the caller only.
1431 *
1432 * @param pVM The VM handle.
1433 */
1434DECL_FORCE_INLINE(int) vmmR3EmtRendezvousNonCallerReturn(PVM pVM)
1435{
1436 int rcRet = ASMAtomicReadS32(&pVM->vmm.s.i32RendezvousStatus);
1437 uint32_t cReturned = ASMAtomicIncU32(&pVM->vmm.s.cRendezvousEmtsReturned);
1438 if (cReturned == pVM->cCpus - 1U)
1439 {
1440 int rc = RTSemEventSignal(pVM->vmm.s.hEvtRendezvousDoneCaller);
1441 AssertLogRelRC(rc);
1442 }
1443
1444 AssertLogRelMsgReturn( rcRet <= VINF_SUCCESS
1445 || (rcRet >= VINF_EM_FIRST && rcRet <= VINF_EM_LAST),
1446 ("%Rrc\n", rcRet),
1447 VERR_IPE_UNEXPECTED_INFO_STATUS);
1448 return RT_SUCCESS(rcRet) ? rcRet : VINF_SUCCESS;
1449}
1450
1451
1452/**
1453 * Common worker for VMMR3EmtRendezvous and VMMR3EmtRendezvousFF.
1454 *
1455 * @returns VBox strict informational status code for EM scheduling. No failures
1456 * will be returned here, those are for the caller only. When
1457 * fIsCaller is set, VINF_SUCESS is always returned.
1458 *
1459 * @param pVM The VM handle.
1460 * @param pVCpu The VMCPU structure for the calling EMT.
1461 * @param fIsCaller Whether we're the VMMR3EmtRendezvous caller or
1462 * not.
1463 * @param fFlags The flags.
1464 * @param pfnRendezvous The callback.
1465 * @param pvUser The user argument for the callback.
1466 */
1467static int vmmR3EmtRendezvousCommon(PVM pVM, PVMCPU pVCpu, bool fIsCaller,
1468 uint32_t fFlags, PFNVMMEMTRENDEZVOUS pfnRendezvous, void *pvUser)
1469{
1470 int rc;
1471
1472 /*
1473 * Enter, the last EMT triggers the next callback phase.
1474 */
1475 uint32_t cEntered = ASMAtomicIncU32(&pVM->vmm.s.cRendezvousEmtsEntered);
1476 if (cEntered != pVM->cCpus)
1477 {
1478 if ((fFlags & VMMEMTRENDEZVOUS_FLAGS_TYPE_MASK) == VMMEMTRENDEZVOUS_FLAGS_TYPE_ONE_BY_ONE)
1479 {
1480 /* Wait for our turn. */
1481 rc = RTSemEventWait(pVM->vmm.s.hEvtRendezvousEnterOneByOne, RT_INDEFINITE_WAIT);
1482 AssertLogRelRC(rc);
1483 }
1484 else if ((fFlags & VMMEMTRENDEZVOUS_FLAGS_TYPE_MASK) == VMMEMTRENDEZVOUS_FLAGS_TYPE_ALL_AT_ONCE)
1485 {
1486 /* Wait for the last EMT to arrive and wake everyone up. */
1487 rc = RTSemEventMultiWait(pVM->vmm.s.hEvtMulRendezvousEnterAllAtOnce, RT_INDEFINITE_WAIT);
1488 AssertLogRelRC(rc);
1489 }
1490 else if ( (fFlags & VMMEMTRENDEZVOUS_FLAGS_TYPE_MASK) == VMMEMTRENDEZVOUS_FLAGS_TYPE_ASCENDING
1491 || (fFlags & VMMEMTRENDEZVOUS_FLAGS_TYPE_MASK) == VMMEMTRENDEZVOUS_FLAGS_TYPE_DESCENDING)
1492 {
1493 /* Wait for our turn. */
1494 rc = RTSemEventWait(pVM->vmm.s.pahEvtRendezvousEnterOrdered[pVCpu->idCpu], RT_INDEFINITE_WAIT);
1495 AssertLogRelRC(rc);
1496 }
1497 else
1498 {
1499 Assert((fFlags & VMMEMTRENDEZVOUS_FLAGS_TYPE_MASK) == VMMEMTRENDEZVOUS_FLAGS_TYPE_ONCE);
1500
1501 /*
1502 * The execute once is handled specially to optimize the code flow.
1503 *
1504 * The last EMT to arrive will perform the callback and the other
1505 * EMTs will wait on the Done/DoneCaller semaphores (instead of
1506 * the EnterOneByOne/AllAtOnce) in the meanwhile. When the callback
1507 * returns, that EMT will initiate the normal return sequence.
1508 */
1509 if (!fIsCaller)
1510 {
1511 rc = RTSemEventMultiWait(pVM->vmm.s.hEvtMulRendezvousDone, RT_INDEFINITE_WAIT);
1512 AssertLogRelRC(rc);
1513
1514 return vmmR3EmtRendezvousNonCallerReturn(pVM);
1515 }
1516 return VINF_SUCCESS;
1517 }
1518 }
1519 else
1520 {
1521 /*
1522 * All EMTs are waiting, clear the FF and take action according to the
1523 * execution method.
1524 */
1525 VM_FF_CLEAR(pVM, VM_FF_EMT_RENDEZVOUS);
1526
1527 if ((fFlags & VMMEMTRENDEZVOUS_FLAGS_TYPE_MASK) == VMMEMTRENDEZVOUS_FLAGS_TYPE_ALL_AT_ONCE)
1528 {
1529 /* Wake up everyone. */
1530 rc = RTSemEventMultiSignal(pVM->vmm.s.hEvtMulRendezvousEnterAllAtOnce);
1531 AssertLogRelRC(rc);
1532 }
1533 else if ( (fFlags & VMMEMTRENDEZVOUS_FLAGS_TYPE_MASK) == VMMEMTRENDEZVOUS_FLAGS_TYPE_ASCENDING
1534 || (fFlags & VMMEMTRENDEZVOUS_FLAGS_TYPE_MASK) == VMMEMTRENDEZVOUS_FLAGS_TYPE_DESCENDING)
1535 {
1536 /* Figure out who to wake up and wake it up. If it's ourself, then
1537 it's easy otherwise wait for our turn. */
1538 VMCPUID iFirst = (fFlags & VMMEMTRENDEZVOUS_FLAGS_TYPE_MASK) == VMMEMTRENDEZVOUS_FLAGS_TYPE_ASCENDING
1539 ? 0
1540 : pVM->cCpus - 1U;
1541 if (pVCpu->idCpu != iFirst)
1542 {
1543 rc = RTSemEventSignal(pVM->vmm.s.pahEvtRendezvousEnterOrdered[iFirst]);
1544 AssertLogRelRC(rc);
1545 rc = RTSemEventWait(pVM->vmm.s.pahEvtRendezvousEnterOrdered[pVCpu->idCpu], RT_INDEFINITE_WAIT);
1546 AssertLogRelRC(rc);
1547 }
1548 }
1549 /* else: execute the handler on the current EMT and wake up one or more threads afterwards. */
1550 }
1551
1552
1553 /*
1554 * Do the callback and update the status if necessary.
1555 */
1556 if ( !(fFlags & VMMEMTRENDEZVOUS_FLAGS_STOP_ON_ERROR)
1557 || RT_SUCCESS(ASMAtomicUoReadS32(&pVM->vmm.s.i32RendezvousStatus)) )
1558 {
1559 VBOXSTRICTRC rcStrict = pfnRendezvous(pVM, pVCpu, pvUser);
1560 if (rcStrict != VINF_SUCCESS)
1561 {
1562 AssertLogRelMsg( rcStrict <= VINF_SUCCESS
1563 || (rcStrict >= VINF_EM_FIRST && rcStrict <= VINF_EM_LAST),
1564 ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)));
1565 int32_t i32RendezvousStatus;
1566 do
1567 {
1568 i32RendezvousStatus = ASMAtomicUoReadS32(&pVM->vmm.s.i32RendezvousStatus);
1569 if ( rcStrict == i32RendezvousStatus
1570 || RT_FAILURE(i32RendezvousStatus)
1571 || ( i32RendezvousStatus != VINF_SUCCESS
1572 && rcStrict > i32RendezvousStatus))
1573 break;
1574 } while (!ASMAtomicCmpXchgS32(&pVM->vmm.s.i32RendezvousStatus, VBOXSTRICTRC_VAL(rcStrict), i32RendezvousStatus));
1575 }
1576 }
1577
1578 /*
1579 * Increment the done counter and take action depending on whether we're
1580 * the last to finish callback execution.
1581 */
1582 uint32_t cDone = ASMAtomicIncU32(&pVM->vmm.s.cRendezvousEmtsDone);
1583 if ( cDone != pVM->cCpus
1584 && (fFlags & VMMEMTRENDEZVOUS_FLAGS_TYPE_MASK) != VMMEMTRENDEZVOUS_FLAGS_TYPE_ONCE)
1585 {
1586 /* Signal the next EMT? */
1587 if ((fFlags & VMMEMTRENDEZVOUS_FLAGS_TYPE_MASK) == VMMEMTRENDEZVOUS_FLAGS_TYPE_ONE_BY_ONE)
1588 {
1589 rc = RTSemEventSignal(pVM->vmm.s.hEvtRendezvousEnterOneByOne);
1590 AssertLogRelRC(rc);
1591 }
1592 else if ((fFlags & VMMEMTRENDEZVOUS_FLAGS_TYPE_MASK) == VMMEMTRENDEZVOUS_FLAGS_TYPE_ASCENDING)
1593 {
1594 Assert(cDone == pVCpu->idCpu + 1U);
1595 rc = RTSemEventSignal(pVM->vmm.s.pahEvtRendezvousEnterOrdered[pVCpu->idCpu + 1U]);
1596 AssertLogRelRC(rc);
1597 }
1598 else if ((fFlags & VMMEMTRENDEZVOUS_FLAGS_TYPE_MASK) == VMMEMTRENDEZVOUS_FLAGS_TYPE_DESCENDING)
1599 {
1600 Assert(pVM->cCpus - cDone == pVCpu->idCpu);
1601 rc = RTSemEventSignal(pVM->vmm.s.pahEvtRendezvousEnterOrdered[pVM->cCpus - cDone - 1U]);
1602 AssertLogRelRC(rc);
1603 }
1604
1605 /* Wait for the rest to finish (the caller waits on hEvtRendezvousDoneCaller). */
1606 if (!fIsCaller)
1607 {
1608 rc = RTSemEventMultiWait(pVM->vmm.s.hEvtMulRendezvousDone, RT_INDEFINITE_WAIT);
1609 AssertLogRelRC(rc);
1610 }
1611 }
1612 else
1613 {
1614 /* Callback execution is all done, tell the rest to return. */
1615 rc = RTSemEventMultiSignal(pVM->vmm.s.hEvtMulRendezvousDone);
1616 AssertLogRelRC(rc);
1617 }
1618
1619 if (!fIsCaller)
1620 return vmmR3EmtRendezvousNonCallerReturn(pVM);
1621 return VINF_SUCCESS;
1622}
1623
1624
1625/**
1626 * Called in response to VM_FF_EMT_RENDEZVOUS.
1627 *
1628 * @returns VBox strict status code - EM scheduling. No errors will be returned
1629 * here, nor will any non-EM scheduling status codes be returned.
1630 *
1631 * @param pVM The VM handle
1632 * @param pVCpu The handle of the calling EMT.
1633 *
1634 * @thread EMT
1635 */
1636VMMR3DECL(int) VMMR3EmtRendezvousFF(PVM pVM, PVMCPU pVCpu)
1637{
1638 return vmmR3EmtRendezvousCommon(pVM, pVCpu, false /* fIsCaller */, pVM->vmm.s.fRendezvousFlags,
1639 pVM->vmm.s.pfnRendezvous, pVM->vmm.s.pvRendezvousUser);
1640}
1641
1642
1643/**
1644 * EMT rendezvous.
1645 *
1646 * Gathers all the EMTs and execute some code on each of them, either in a one
1647 * by one fashion or all at once.
1648 *
1649 * @returns VBox strict status code. This will be the the first error,
1650 * VINF_SUCCESS, or an EM scheduling status code.
1651 *
1652 * @param pVM The VM handle.
1653 * @param fFlags Flags indicating execution methods. See
1654 * grp_VMMR3EmtRendezvous_fFlags.
1655 * @param pfnRendezvous The callback.
1656 * @param pvUser User argument for the callback.
1657 *
1658 * @thread Any.
1659 */
1660VMMR3DECL(int) VMMR3EmtRendezvous(PVM pVM, uint32_t fFlags, PFNVMMEMTRENDEZVOUS pfnRendezvous, void *pvUser)
1661{
1662 /*
1663 * Validate input.
1664 */
1665 AssertMsg( (fFlags & VMMEMTRENDEZVOUS_FLAGS_TYPE_MASK) != VMMEMTRENDEZVOUS_FLAGS_TYPE_INVALID
1666 && (fFlags & VMMEMTRENDEZVOUS_FLAGS_TYPE_MASK) <= VMMEMTRENDEZVOUS_FLAGS_TYPE_DESCENDING
1667 && !(fFlags & ~VMMEMTRENDEZVOUS_FLAGS_VALID_MASK), ("%#x\n", fFlags));
1668 AssertMsg( !(fFlags & VMMEMTRENDEZVOUS_FLAGS_STOP_ON_ERROR)
1669 || ( (fFlags & VMMEMTRENDEZVOUS_FLAGS_TYPE_MASK) != VMMEMTRENDEZVOUS_FLAGS_TYPE_ALL_AT_ONCE
1670 && (fFlags & VMMEMTRENDEZVOUS_FLAGS_TYPE_MASK) != VMMEMTRENDEZVOUS_FLAGS_TYPE_ONCE),
1671 ("type %u\n", fFlags & VMMEMTRENDEZVOUS_FLAGS_TYPE_MASK));
1672
1673 VBOXSTRICTRC rcStrict;
1674 PVMCPU pVCpu = VMMGetCpu(pVM);
1675 if (!pVCpu)
1676 /*
1677 * Forward the request to an EMT thread.
1678 */
1679 rcStrict = VMR3ReqCallWait(pVM, VMCPUID_ANY,
1680 (PFNRT)VMMR3EmtRendezvous, 4, pVM, fFlags, pfnRendezvous, pvUser);
1681 else if (pVM->cCpus == 1)
1682 /*
1683 * Shortcut for the single EMT case.
1684 */
1685 rcStrict = pfnRendezvous(pVM, pVCpu, pvUser);
1686 else
1687 {
1688 /*
1689 * Spin lock. If busy, wait for the other EMT to finish while keeping a
1690 * lookout of the RENDEZVOUS FF.
1691 */
1692 int rc;
1693 rcStrict = VINF_SUCCESS;
1694 if (RT_UNLIKELY(!ASMAtomicCmpXchgU32(&pVM->vmm.s.u32RendezvousLock, 0x77778888, 0)))
1695 {
1696 while (!ASMAtomicCmpXchgU32(&pVM->vmm.s.u32RendezvousLock, 0x77778888, 0))
1697 {
1698 if (VM_FF_ISPENDING(pVM, VM_FF_EMT_RENDEZVOUS))
1699 {
1700 rc = VMMR3EmtRendezvousFF(pVM, pVCpu);
1701 if ( rc != VINF_SUCCESS
1702 && ( rcStrict == VINF_SUCCESS
1703 || rcStrict > rc))
1704 rcStrict = rc;
1705 /** @todo Perhaps deal with termination here? */
1706 }
1707 ASMNopPause();
1708 }
1709 }
1710 Assert(!VM_FF_ISPENDING(pVM, VM_FF_EMT_RENDEZVOUS));
1711
1712 /*
1713 * Clear the slate. This is a semaphore ping-pong orgy. :-)
1714 */
1715 for (VMCPUID i = 0; i < pVM->cCpus; i++)
1716 {
1717 rc = RTSemEventWait(pVM->vmm.s.pahEvtRendezvousEnterOrdered[i], 0);
1718 AssertLogRelMsg(rc == VERR_TIMEOUT || rc == VINF_SUCCESS, ("%Rrc\n", rc));
1719 }
1720 rc = RTSemEventWait(pVM->vmm.s.hEvtRendezvousEnterOneByOne, 0); AssertLogRelMsg(rc == VERR_TIMEOUT || rc == VINF_SUCCESS, ("%Rrc\n", rc));
1721 rc = RTSemEventMultiReset(pVM->vmm.s.hEvtMulRendezvousEnterAllAtOnce); AssertLogRelRC(rc);
1722 rc = RTSemEventMultiReset(pVM->vmm.s.hEvtMulRendezvousDone); AssertLogRelRC(rc);
1723 rc = RTSemEventWait(pVM->vmm.s.hEvtRendezvousDoneCaller, 0); AssertLogRelMsg(rc == VERR_TIMEOUT || rc == VINF_SUCCESS, ("%Rrc\n", rc));
1724 ASMAtomicWriteU32(&pVM->vmm.s.cRendezvousEmtsEntered, 0);
1725 ASMAtomicWriteU32(&pVM->vmm.s.cRendezvousEmtsDone, 0);
1726 ASMAtomicWriteU32(&pVM->vmm.s.cRendezvousEmtsReturned, 0);
1727 ASMAtomicWriteS32(&pVM->vmm.s.i32RendezvousStatus, VINF_SUCCESS);
1728 ASMAtomicWritePtr((void * volatile *)&pVM->vmm.s.pfnRendezvous, (void *)(uintptr_t)pfnRendezvous);
1729 ASMAtomicWritePtr(&pVM->vmm.s.pvRendezvousUser, pvUser);
1730 ASMAtomicWriteU32(&pVM->vmm.s.fRendezvousFlags, fFlags);
1731
1732 /*
1733 * Set the FF and poke the other EMTs.
1734 */
1735 VM_FF_SET(pVM, VM_FF_EMT_RENDEZVOUS);
1736 VMR3NotifyGlobalFFU(pVM->pUVM, VMNOTIFYFF_FLAGS_POKE);
1737
1738 /*
1739 * Do the same ourselves.
1740 */
1741 vmmR3EmtRendezvousCommon(pVM, pVCpu, true /* fIsCaller */, fFlags, pfnRendezvous, pvUser);
1742
1743 /*
1744 * The caller waits for the other EMTs to be done and return before doing
1745 * the cleanup. This makes away with wakeup / reset races we would otherwise
1746 * risk in the multiple release event semaphore code (hEvtRendezvousDoneCaller).
1747 */
1748 rc = RTSemEventWait(pVM->vmm.s.hEvtRendezvousDoneCaller, RT_INDEFINITE_WAIT);
1749 AssertLogRelRC(rc);
1750
1751 /*
1752 * Get the return code and clean up a little bit.
1753 */
1754 int rcMy = pVM->vmm.s.i32RendezvousStatus;
1755 ASMAtomicWritePtr((void * volatile *)&pVM->vmm.s.pfnRendezvous, NULL);
1756
1757 ASMAtomicWriteU32(&pVM->vmm.s.u32RendezvousLock, 0);
1758
1759 /*
1760 * Merge rcStrict and rcMy.
1761 */
1762 AssertRC(VBOXSTRICTRC_VAL(rcStrict));
1763 if ( rcMy != VINF_SUCCESS
1764 && ( rcStrict == VINF_SUCCESS
1765 || rcStrict > rcMy))
1766 rcStrict = rcMy;
1767 }
1768
1769 AssertLogRelMsgReturn( rcStrict <= VINF_SUCCESS
1770 || (rcStrict >= VINF_EM_FIRST && rcStrict <= VINF_EM_LAST),
1771 ("%Rrc\n", VBOXSTRICTRC_VAL(rcStrict)),
1772 VERR_IPE_UNEXPECTED_INFO_STATUS);
1773 return VBOXSTRICTRC_VAL(rcStrict);
1774}
1775
1776
1777/**
1778 * Read from the ring 0 jump buffer stack
1779 *
1780 * @returns VBox status code.
1781 *
1782 * @param pVM Pointer to the shared VM structure.
1783 * @param idCpu The ID of the source CPU context (for the address).
1784 * @param pAddress Where to start reading.
1785 * @param pvBuf Where to store the data we've read.
1786 * @param cbRead The number of bytes to read.
1787 */
1788VMMR3DECL(int) VMMR3ReadR0Stack(PVM pVM, VMCPUID idCpu, RTHCUINTPTR pAddress, void *pvBuf, size_t cbRead)
1789{
1790 PVMCPU pVCpu = VMMGetCpuById(pVM, idCpu);
1791 AssertReturn(pVCpu, VERR_INVALID_PARAMETER);
1792
1793 RTHCUINTPTR offset = pVCpu->vmm.s.CallRing3JmpBufR0.SpCheck - pAddress;
1794 if (offset >= pVCpu->vmm.s.CallRing3JmpBufR0.cbSavedStack)
1795 return VERR_INVALID_POINTER;
1796
1797 memcpy(pvBuf, pVCpu->vmm.s.pbEMTStackR3 + pVCpu->vmm.s.CallRing3JmpBufR0.cbSavedStack - offset, cbRead);
1798 return VINF_SUCCESS;
1799}
1800
1801
1802/**
1803 * Calls a RC function.
1804 *
1805 * @param pVM The VM handle.
1806 * @param RCPtrEntry The address of the RC function.
1807 * @param cArgs The number of arguments in the ....
1808 * @param ... Arguments to the function.
1809 */
1810VMMR3DECL(int) VMMR3CallRC(PVM pVM, RTRCPTR RCPtrEntry, unsigned cArgs, ...)
1811{
1812 va_list args;
1813 va_start(args, cArgs);
1814 int rc = VMMR3CallRCV(pVM, RCPtrEntry, cArgs, args);
1815 va_end(args);
1816 return rc;
1817}
1818
1819
1820/**
1821 * Calls a RC function.
1822 *
1823 * @param pVM The VM handle.
1824 * @param RCPtrEntry The address of the RC function.
1825 * @param cArgs The number of arguments in the ....
1826 * @param args Arguments to the function.
1827 */
1828VMMR3DECL(int) VMMR3CallRCV(PVM pVM, RTRCPTR RCPtrEntry, unsigned cArgs, va_list args)
1829{
1830 /* Raw mode implies 1 VCPU. */
1831 AssertReturn(pVM->cCpus == 1, VERR_RAW_MODE_INVALID_SMP);
1832 PVMCPU pVCpu = &pVM->aCpus[0];
1833
1834 Log2(("VMMR3CallGCV: RCPtrEntry=%RRv cArgs=%d\n", RCPtrEntry, cArgs));
1835
1836 /*
1837 * Setup the call frame using the trampoline.
1838 */
1839 CPUMHyperSetCtxCore(pVCpu, NULL);
1840 memset(pVCpu->vmm.s.pbEMTStackR3, 0xaa, VMM_STACK_SIZE); /* Clear the stack. */
1841 CPUMSetHyperESP(pVCpu, pVCpu->vmm.s.pbEMTStackBottomRC - cArgs * sizeof(RTGCUINTPTR32));
1842 PRTGCUINTPTR32 pFrame = (PRTGCUINTPTR32)(pVCpu->vmm.s.pbEMTStackR3 + VMM_STACK_SIZE) - cArgs;
1843 int i = cArgs;
1844 while (i-- > 0)
1845 *pFrame++ = va_arg(args, RTGCUINTPTR32);
1846
1847 CPUMPushHyper(pVCpu, cArgs * sizeof(RTGCUINTPTR32)); /* stack frame size */
1848 CPUMPushHyper(pVCpu, RCPtrEntry); /* what to call */
1849 CPUMSetHyperEIP(pVCpu, pVM->vmm.s.pfnCallTrampolineRC);
1850
1851 /*
1852 * We hide log flushes (outer) and hypervisor interrupts (inner).
1853 */
1854 for (;;)
1855 {
1856 int rc;
1857 Assert(CPUMGetHyperCR3(pVCpu) && CPUMGetHyperCR3(pVCpu) == PGMGetHyperCR3(pVCpu));
1858 do
1859 {
1860#ifdef NO_SUPCALLR0VMM
1861 rc = VERR_GENERAL_FAILURE;
1862#else
1863 rc = SUPR3CallVMMR0Fast(pVM->pVMR0, VMMR0_DO_RAW_RUN, 0);
1864 if (RT_LIKELY(rc == VINF_SUCCESS))
1865 rc = pVCpu->vmm.s.iLastGZRc;
1866#endif
1867 } while (rc == VINF_EM_RAW_INTERRUPT_HYPER);
1868
1869 /*
1870 * Flush the logs.
1871 */
1872#ifdef LOG_ENABLED
1873 PRTLOGGERRC pLogger = pVM->vmm.s.pRCLoggerR3;
1874 if ( pLogger
1875 && pLogger->offScratch > 0)
1876 RTLogFlushRC(NULL, pLogger);
1877#endif
1878#ifdef VBOX_WITH_RC_RELEASE_LOGGING
1879 PRTLOGGERRC pRelLogger = pVM->vmm.s.pRCRelLoggerR3;
1880 if (RT_UNLIKELY(pRelLogger && pRelLogger->offScratch > 0))
1881 RTLogFlushRC(RTLogRelDefaultInstance(), pRelLogger);
1882#endif
1883 if (rc == VERR_TRPM_PANIC || rc == VERR_TRPM_DONT_PANIC)
1884 VMMR3FatalDump(pVM, pVCpu, rc);
1885 if (rc != VINF_VMM_CALL_HOST)
1886 {
1887 Log2(("VMMR3CallGCV: returns %Rrc (cs:eip=%04x:%08x)\n", rc, CPUMGetGuestCS(pVCpu), CPUMGetGuestEIP(pVCpu)));
1888 return rc;
1889 }
1890 rc = vmmR3ServiceCallRing3Request(pVM, pVCpu);
1891 if (RT_FAILURE(rc))
1892 return rc;
1893 }
1894}
1895
1896
1897/**
1898 * Wrapper for SUPR3CallVMMR0Ex which will deal with VINF_VMM_CALL_HOST returns.
1899 *
1900 * @returns VBox status code.
1901 * @param pVM The VM to operate on.
1902 * @param uOperation Operation to execute.
1903 * @param u64Arg Constant argument.
1904 * @param pReqHdr Pointer to a request header. See SUPR3CallVMMR0Ex for
1905 * details.
1906 */
1907VMMR3DECL(int) VMMR3CallR0(PVM pVM, uint32_t uOperation, uint64_t u64Arg, PSUPVMMR0REQHDR pReqHdr)
1908{
1909 PVMCPU pVCpu = VMMGetCpu(pVM);
1910 AssertReturn(pVCpu, VERR_VM_THREAD_NOT_EMT);
1911
1912 /*
1913 * Call Ring-0 entry with init code.
1914 */
1915 int rc;
1916 for (;;)
1917 {
1918#ifdef NO_SUPCALLR0VMM
1919 rc = VERR_GENERAL_FAILURE;
1920#else
1921 rc = SUPR3CallVMMR0Ex(pVM->pVMR0, pVCpu->idCpu, uOperation, u64Arg, pReqHdr);
1922#endif
1923 /*
1924 * Flush the logs.
1925 */
1926#ifdef LOG_ENABLED
1927 if ( pVCpu->vmm.s.pR0LoggerR3
1928 && pVCpu->vmm.s.pR0LoggerR3->Logger.offScratch > 0)
1929 RTLogFlushToLogger(&pVCpu->vmm.s.pR0LoggerR3->Logger, NULL);
1930#endif
1931 if (rc != VINF_VMM_CALL_HOST)
1932 break;
1933 rc = vmmR3ServiceCallRing3Request(pVM, pVCpu);
1934 if (RT_FAILURE(rc) || (rc >= VINF_EM_FIRST && rc <= VINF_EM_LAST))
1935 break;
1936 /* Resume R0 */
1937 }
1938
1939 AssertLogRelMsgReturn(rc == VINF_SUCCESS || VBOX_FAILURE(rc),
1940 ("uOperation=%u rc=%Rrc\n", uOperation, rc),
1941 VERR_INTERNAL_ERROR);
1942 return rc;
1943}
1944
1945
1946/**
1947 * Resumes executing hypervisor code when interrupted by a queue flush or a
1948 * debug event.
1949 *
1950 * @returns VBox status code.
1951 * @param pVM VM handle.
1952 * @param pVCpu VMCPU handle.
1953 */
1954VMMR3DECL(int) VMMR3ResumeHyper(PVM pVM, PVMCPU pVCpu)
1955{
1956 Log(("VMMR3ResumeHyper: eip=%RRv esp=%RRv\n", CPUMGetHyperEIP(pVCpu), CPUMGetHyperESP(pVCpu)));
1957 AssertReturn(pVM->cCpus == 1, VERR_RAW_MODE_INVALID_SMP);
1958
1959 /*
1960 * We hide log flushes (outer) and hypervisor interrupts (inner).
1961 */
1962 for (;;)
1963 {
1964 int rc;
1965 Assert(CPUMGetHyperCR3(pVCpu) && CPUMGetHyperCR3(pVCpu) == PGMGetHyperCR3(pVCpu));
1966 do
1967 {
1968#ifdef NO_SUPCALLR0VMM
1969 rc = VERR_GENERAL_FAILURE;
1970#else
1971 rc = SUPR3CallVMMR0Fast(pVM->pVMR0, VMMR0_DO_RAW_RUN, 0);
1972 if (RT_LIKELY(rc == VINF_SUCCESS))
1973 rc = pVCpu->vmm.s.iLastGZRc;
1974#endif
1975 } while (rc == VINF_EM_RAW_INTERRUPT_HYPER);
1976
1977 /*
1978 * Flush the loggers,
1979 */
1980#ifdef LOG_ENABLED
1981 PRTLOGGERRC pLogger = pVM->vmm.s.pRCLoggerR3;
1982 if ( pLogger
1983 && pLogger->offScratch > 0)
1984 RTLogFlushRC(NULL, pLogger);
1985#endif
1986#ifdef VBOX_WITH_RC_RELEASE_LOGGING
1987 PRTLOGGERRC pRelLogger = pVM->vmm.s.pRCRelLoggerR3;
1988 if (RT_UNLIKELY(pRelLogger && pRelLogger->offScratch > 0))
1989 RTLogFlushRC(RTLogRelDefaultInstance(), pRelLogger);
1990#endif
1991 if (rc == VERR_TRPM_PANIC || rc == VERR_TRPM_DONT_PANIC)
1992 VMMR3FatalDump(pVM, pVCpu, rc);
1993 if (rc != VINF_VMM_CALL_HOST)
1994 {
1995 Log(("VMMR3ResumeHyper: returns %Rrc\n", rc));
1996 return rc;
1997 }
1998 rc = vmmR3ServiceCallRing3Request(pVM, pVCpu);
1999 if (RT_FAILURE(rc))
2000 return rc;
2001 }
2002}
2003
2004
2005/**
2006 * Service a call to the ring-3 host code.
2007 *
2008 * @returns VBox status code.
2009 * @param pVM VM handle.
2010 * @param pVCpu VMCPU handle
2011 * @remark Careful with critsects.
2012 */
2013static int vmmR3ServiceCallRing3Request(PVM pVM, PVMCPU pVCpu)
2014{
2015 /*
2016 * We must also check for pending critsect exits or else we can deadlock
2017 * when entering other critsects here.
2018 */
2019 if (VMCPU_FF_ISPENDING(pVCpu, VMCPU_FF_PDM_CRITSECT))
2020 PDMCritSectFF(pVCpu);
2021
2022 switch (pVCpu->vmm.s.enmCallRing3Operation)
2023 {
2024 /*
2025 * Acquire the PDM lock.
2026 */
2027 case VMMCALLRING3_PDM_LOCK:
2028 {
2029 pVCpu->vmm.s.rcCallRing3 = PDMR3LockCall(pVM);
2030 break;
2031 }
2032
2033 /*
2034 * Flush a PDM queue.
2035 */
2036 case VMMCALLRING3_PDM_QUEUE_FLUSH:
2037 {
2038 PDMR3QueueFlushWorker(pVM, NULL);
2039 pVCpu->vmm.s.rcCallRing3 = VINF_SUCCESS;
2040 break;
2041 }
2042
2043 /*
2044 * Grow the PGM pool.
2045 */
2046 case VMMCALLRING3_PGM_POOL_GROW:
2047 {
2048 pVCpu->vmm.s.rcCallRing3 = PGMR3PoolGrow(pVM);
2049 break;
2050 }
2051
2052 /*
2053 * Maps an page allocation chunk into ring-3 so ring-0 can use it.
2054 */
2055 case VMMCALLRING3_PGM_MAP_CHUNK:
2056 {
2057 pVCpu->vmm.s.rcCallRing3 = PGMR3PhysChunkMap(pVM, pVCpu->vmm.s.u64CallRing3Arg);
2058 break;
2059 }
2060
2061 /*
2062 * Allocates more handy pages.
2063 */
2064 case VMMCALLRING3_PGM_ALLOCATE_HANDY_PAGES:
2065 {
2066 pVCpu->vmm.s.rcCallRing3 = PGMR3PhysAllocateHandyPages(pVM);
2067 break;
2068 }
2069
2070 /*
2071 * Acquire the PGM lock.
2072 */
2073 case VMMCALLRING3_PGM_LOCK:
2074 {
2075 pVCpu->vmm.s.rcCallRing3 = PGMR3LockCall(pVM);
2076 break;
2077 }
2078
2079 /*
2080 * Acquire the MM hypervisor heap lock.
2081 */
2082 case VMMCALLRING3_MMHYPER_LOCK:
2083 {
2084 pVCpu->vmm.s.rcCallRing3 = MMR3LockCall(pVM);
2085 break;
2086 }
2087
2088 /*
2089 * Flush REM handler notifications.
2090 */
2091 case VMMCALLRING3_REM_REPLAY_HANDLER_NOTIFICATIONS:
2092 {
2093 REMR3ReplayHandlerNotifications(pVM);
2094 pVCpu->vmm.s.rcCallRing3 = VINF_SUCCESS;
2095 break;
2096 }
2097
2098 /*
2099 * This is a noop. We just take this route to avoid unnecessary
2100 * tests in the loops.
2101 */
2102 case VMMCALLRING3_VMM_LOGGER_FLUSH:
2103 pVCpu->vmm.s.rcCallRing3 = VINF_SUCCESS;
2104 LogAlways(("*FLUSH*\n"));
2105 break;
2106
2107 /*
2108 * Set the VM error message.
2109 */
2110 case VMMCALLRING3_VM_SET_ERROR:
2111 VMR3SetErrorWorker(pVM);
2112 pVCpu->vmm.s.rcCallRing3 = VINF_SUCCESS;
2113 break;
2114
2115 /*
2116 * Set the VM runtime error message.
2117 */
2118 case VMMCALLRING3_VM_SET_RUNTIME_ERROR:
2119 pVCpu->vmm.s.rcCallRing3 = VMR3SetRuntimeErrorWorker(pVM);
2120 break;
2121
2122 /*
2123 * Signal a ring 0 hypervisor assertion.
2124 * Cancel the longjmp operation that's in progress.
2125 */
2126 case VMMCALLRING3_VM_R0_ASSERTION:
2127 pVCpu->vmm.s.enmCallRing3Operation = VMMCALLRING3_INVALID;
2128 pVCpu->vmm.s.CallRing3JmpBufR0.fInRing3Call = false;
2129#ifdef RT_ARCH_X86
2130 pVCpu->vmm.s.CallRing3JmpBufR0.eip = 0;
2131#else
2132 pVCpu->vmm.s.CallRing3JmpBufR0.rip = 0;
2133#endif
2134 LogRel((pVM->vmm.s.szRing0AssertMsg1));
2135 LogRel((pVM->vmm.s.szRing0AssertMsg2));
2136 return VERR_VMM_RING0_ASSERTION;
2137
2138 /*
2139 * A forced switch to ring 0 for preemption purposes.
2140 */
2141 case VMMCALLRING3_VM_R0_PREEMPT:
2142 pVCpu->vmm.s.rcCallRing3 = VINF_SUCCESS;
2143 break;
2144
2145 default:
2146 AssertMsgFailed(("enmCallRing3Operation=%d\n", pVCpu->vmm.s.enmCallRing3Operation));
2147 return VERR_INTERNAL_ERROR;
2148 }
2149
2150 pVCpu->vmm.s.enmCallRing3Operation = VMMCALLRING3_INVALID;
2151 return VINF_SUCCESS;
2152}
2153
2154
2155/**
2156 * Displays the Force action Flags.
2157 *
2158 * @param pVM The VM handle.
2159 * @param pHlp The output helpers.
2160 * @param pszArgs The additional arguments (ignored).
2161 */
2162static DECLCALLBACK(void) vmmR3InfoFF(PVM pVM, PCDBGFINFOHLP pHlp, const char *pszArgs)
2163{
2164 int c;
2165 uint32_t f;
2166#define PRINT_FLAG(prf,flag) do { \
2167 if (f & (prf##flag)) \
2168 { \
2169 static const char *s_psz = #flag; \
2170 if (!(c % 6)) \
2171 pHlp->pfnPrintf(pHlp, "%s\n %s", c ? "," : "", s_psz); \
2172 else \
2173 pHlp->pfnPrintf(pHlp, ", %s", s_psz); \
2174 c++; \
2175 f &= ~(prf##flag); \
2176 } \
2177 } while (0)
2178
2179#define PRINT_GROUP(prf,grp,sfx) do { \
2180 if (f & (prf##grp##sfx)) \
2181 { \
2182 static const char *s_psz = #grp; \
2183 if (!(c % 5)) \
2184 pHlp->pfnPrintf(pHlp, "%s %s", c ? ",\n" : " Groups:\n", s_psz); \
2185 else \
2186 pHlp->pfnPrintf(pHlp, ", %s", s_psz); \
2187 c++; \
2188 } \
2189 } while (0)
2190
2191 /*
2192 * The global flags.
2193 */
2194 const uint32_t fGlobalForcedActions = pVM->fGlobalForcedActions;
2195 pHlp->pfnPrintf(pHlp, "Global FFs: %#RX32", fGlobalForcedActions);
2196
2197 /* show the flag mnemonics */
2198 c = 0;
2199 f = fGlobalForcedActions;
2200 PRINT_FLAG(VM_FF_,TM_VIRTUAL_SYNC);
2201 PRINT_FLAG(VM_FF_,PDM_QUEUES);
2202 PRINT_FLAG(VM_FF_,PDM_DMA);
2203 PRINT_FLAG(VM_FF_,DBGF);
2204 PRINT_FLAG(VM_FF_,REQUEST);
2205 PRINT_FLAG(VM_FF_,TERMINATE);
2206 PRINT_FLAG(VM_FF_,RESET);
2207 PRINT_FLAG(VM_FF_,EMT_RENDEZVOUS);
2208 PRINT_FLAG(VM_FF_,PGM_NEED_HANDY_PAGES);
2209 PRINT_FLAG(VM_FF_,PGM_NO_MEMORY);
2210 PRINT_FLAG(VM_FF_,REM_HANDLER_NOTIFY);
2211 PRINT_FLAG(VM_FF_,DEBUG_SUSPEND);
2212 if (f)
2213 pHlp->pfnPrintf(pHlp, "%s\n Unknown bits: %#RX32\n", c ? "," : "", f);
2214 else
2215 pHlp->pfnPrintf(pHlp, "\n");
2216
2217 /* the groups */
2218 c = 0;
2219 f = fGlobalForcedActions;
2220 PRINT_GROUP(VM_FF_,EXTERNAL_SUSPENDED,_MASK);
2221 PRINT_GROUP(VM_FF_,EXTERNAL_HALTED,_MASK);
2222 PRINT_GROUP(VM_FF_,HIGH_PRIORITY_PRE,_MASK);
2223 PRINT_GROUP(VM_FF_,HIGH_PRIORITY_PRE_RAW,_MASK);
2224 PRINT_GROUP(VM_FF_,HIGH_PRIORITY_POST,_MASK);
2225 PRINT_GROUP(VM_FF_,NORMAL_PRIORITY_POST,_MASK);
2226 PRINT_GROUP(VM_FF_,NORMAL_PRIORITY,_MASK);
2227 PRINT_GROUP(VM_FF_,ALL_BUT_RAW,_MASK);
2228 if (c)
2229 pHlp->pfnPrintf(pHlp, "\n");
2230
2231 /*
2232 * Per CPU flags.
2233 */
2234 for (VMCPUID i = 0; i < pVM->cCpus; i++)
2235 {
2236 const uint32_t fLocalForcedActions = pVM->aCpus[i].fLocalForcedActions;
2237 pHlp->pfnPrintf(pHlp, "CPU %u FFs: %#RX32", i, fLocalForcedActions);
2238
2239 /* show the flag mnemonics */
2240 c = 0;
2241 f = fLocalForcedActions;
2242 PRINT_FLAG(VMCPU_FF_,INTERRUPT_APIC);
2243 PRINT_FLAG(VMCPU_FF_,INTERRUPT_PIC);
2244 PRINT_FLAG(VMCPU_FF_,TIMER);
2245 PRINT_FLAG(VMCPU_FF_,PDM_CRITSECT);
2246 PRINT_FLAG(VMCPU_FF_,PGM_SYNC_CR3);
2247 PRINT_FLAG(VMCPU_FF_,PGM_SYNC_CR3_NON_GLOBAL);
2248 PRINT_FLAG(VMCPU_FF_,TRPM_SYNC_IDT);
2249 PRINT_FLAG(VMCPU_FF_,SELM_SYNC_TSS);
2250 PRINT_FLAG(VMCPU_FF_,SELM_SYNC_GDT);
2251 PRINT_FLAG(VMCPU_FF_,SELM_SYNC_LDT);
2252 PRINT_FLAG(VMCPU_FF_,INHIBIT_INTERRUPTS);
2253 PRINT_FLAG(VMCPU_FF_,CSAM_SCAN_PAGE);
2254 PRINT_FLAG(VMCPU_FF_,CSAM_PENDING_ACTION);
2255 PRINT_FLAG(VMCPU_FF_,TO_R3);
2256 if (f)
2257 pHlp->pfnPrintf(pHlp, "%s\n Unknown bits: %#RX32\n", c ? "," : "", f);
2258 else
2259 pHlp->pfnPrintf(pHlp, "\n");
2260
2261 /* the groups */
2262 c = 0;
2263 f = fLocalForcedActions;
2264 PRINT_GROUP(VMCPU_FF_,EXTERNAL_SUSPENDED,_MASK);
2265 PRINT_GROUP(VMCPU_FF_,EXTERNAL_HALTED,_MASK);
2266 PRINT_GROUP(VMCPU_FF_,HIGH_PRIORITY_PRE,_MASK);
2267 PRINT_GROUP(VMCPU_FF_,HIGH_PRIORITY_PRE_RAW,_MASK);
2268 PRINT_GROUP(VMCPU_FF_,HIGH_PRIORITY_POST,_MASK);
2269 PRINT_GROUP(VMCPU_FF_,NORMAL_PRIORITY_POST,_MASK);
2270 PRINT_GROUP(VMCPU_FF_,NORMAL_PRIORITY,_MASK);
2271 PRINT_GROUP(VMCPU_FF_,RESUME_GUEST,_MASK);
2272 PRINT_GROUP(VMCPU_FF_,HWACCM_TO_R3,_MASK);
2273 PRINT_GROUP(VMCPU_FF_,ALL_BUT_RAW,_MASK);
2274 if (c)
2275 pHlp->pfnPrintf(pHlp, "\n");
2276 }
2277
2278#undef PRINT_FLAG
2279#undef PRINT_GROUP
2280}
2281
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