VirtualBox

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

Last change on this file since 30045 was 29902, checked in by vboxsync, 15 years ago

PDM: Flushed out the PDMQueueFlush code as its unused and problematic wrt guest SMP.

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