VirtualBox

source: vbox/trunk/src/VBox/VMM/VM.cpp@ 4041

Last change on this file since 4041 was 4013, checked in by vboxsync, 17 years ago

pdm.h = include pdm*.h; pdmapi.h = only the 'core' pdm APIs.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 83.2 KB
Line 
1/* $Id: VM.cpp 4013 2007-08-03 00:11:38Z vboxsync $ */
2/** @file
3 * VM - Virtual Machine
4 */
5
6/*
7 * Copyright (C) 2006-2007 innotek GmbH
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 as published by the Free Software Foundation,
13 * in version 2 as it comes in the "COPYING" file of the VirtualBox OSE
14 * distribution. VirtualBox OSE is distributed in the hope that it will
15 * be useful, but WITHOUT ANY WARRANTY of any kind.
16 *
17 * If you received this file as part of a commercial VirtualBox
18 * distribution, then only the terms of your commercial VirtualBox
19 * license agreement apply instead of the previous paragraph.
20 */
21
22
23/*******************************************************************************
24* Header Files *
25*******************************************************************************/
26#define LOG_GROUP LOG_GROUP_VM
27#include <VBox/cfgm.h>
28#include <VBox/vmm.h>
29#include <VBox/mm.h>
30#include <VBox/cpum.h>
31#include <VBox/selm.h>
32#include <VBox/trpm.h>
33#include <VBox/dbgf.h>
34#include <VBox/pgm.h>
35#include <VBox/pdmapi.h>
36#include <VBox/pdmcritsect.h>
37#include <VBox/em.h>
38#include <VBox/rem.h>
39#include <VBox/tm.h>
40#include <VBox/stam.h>
41#include <VBox/patm.h>
42#include <VBox/csam.h>
43#include <VBox/iom.h>
44#include <VBox/ssm.h>
45#include <VBox/hwaccm.h>
46#include "VMInternal.h"
47#include <VBox/vm.h>
48
49#include <VBox/sup.h>
50#include <VBox/dbg.h>
51#include <VBox/err.h>
52#include <VBox/param.h>
53#include <VBox/log.h>
54#include <iprt/assert.h>
55#include <iprt/alloc.h>
56#include <iprt/asm.h>
57#include <iprt/string.h>
58#include <iprt/time.h>
59#include <iprt/semaphore.h>
60#include <iprt/thread.h>
61
62#include <stdlib.h> /* getenv */
63
64
65/*******************************************************************************
66* Structures and Typedefs *
67*******************************************************************************/
68/**
69 * VM destruction callback registration record.
70 */
71typedef struct VMATDTOR
72{
73 /** Pointer to the next record in the list. */
74 struct VMATDTOR *pNext;
75 /** Pointer to the callback function. */
76 PFNVMATDTOR pfnAtDtor;
77 /** The user argument. */
78 void *pvUser;
79} VMATDTOR;
80/** Pointer to a VM destruction callback registration record. */
81typedef VMATDTOR *PVMATDTOR;
82
83
84/*******************************************************************************
85* Global Variables *
86*******************************************************************************/
87/** Pointer to the list of VMs. */
88static PVM g_pVMsHead;
89
90/** Pointer to the list of at VM destruction callbacks. */
91static PVMATDTOR g_pVMAtDtorHead;
92/** Lock the g_pVMAtDtorHead list. */
93#define VM_ATDTOR_LOCK() do { } while (0)
94/** Unlock the g_pVMAtDtorHead list. */
95#define VM_ATDTOR_UNLOCK() do { } while (0)
96
97/*******************************************************************************
98* Internal Functions *
99*******************************************************************************/
100static int vmR3Create(PVM pVM, PFNVMATERROR pfnVMAtError, void *pvUserVM, PFNCFGMCONSTRUCTOR pfnCFGMConstructor, void *pvUserCFGM);
101static void vmR3CallVMAtError(PFNVMATERROR pfnVMAtError, void *pvUser, int rc, RT_SRC_POS_DECL, const char *pszError, ...);
102static int vmR3InitRing3(PVM pVM);
103static int vmR3InitRing0(PVM pVM);
104static int vmR3InitGC(PVM pVM);
105static int vmR3InitDoCompleted(PVM pVM, VMINITCOMPLETED enmWhat);
106static DECLCALLBACK(int) vmR3PowerOn(PVM pVM);
107static DECLCALLBACK(int) vmR3Suspend(PVM pVM);
108static DECLCALLBACK(int) vmR3Resume(PVM pVM);
109static DECLCALLBACK(int) vmR3Save(PVM pVM, const char *pszFilename, PFNVMPROGRESS pfnProgress, void *pvUser);
110static DECLCALLBACK(int) vmR3Load(PVM pVM, const char *pszFilename, PFNVMPROGRESS pfnProgress, void *pvUser);
111static DECLCALLBACK(int) vmR3PowerOff(PVM pVM);
112static void vmR3AtDtor(PVM pVM);
113static void vmR3SetState(PVM pVM, VMSTATE enmStateNew);
114static int vmR3AtReset(PVM pVM);
115static DECLCALLBACK(int) vmR3Reset(PVM pVM);
116static DECLCALLBACK(int) vmR3AtStateRegister(PVM pVM, PFNVMATSTATE pfnAtState, void *pvUser);
117static DECLCALLBACK(int) vmR3AtStateDeregister(PVM pVM, PFNVMATSTATE pfnAtState, void *pvUser);
118static DECLCALLBACK(int) vmR3AtErrorRegister(PVM pVM, PFNVMATERROR pfnAtError, void *pvUser);
119static DECLCALLBACK(int) vmR3AtErrorDeregister(PVM pVM, PFNVMATERROR pfnAtError, void *pvUser);
120static DECLCALLBACK(int) vmR3AtRuntimeErrorRegister(PVM pVM, PFNVMATRUNTIMEERROR pfnAtRuntimeError, void *pvUser);
121static DECLCALLBACK(int) vmR3AtRuntimeErrorDeregister(PVM pVM, PFNVMATRUNTIMEERROR pfnAtRuntimeError, void *pvUser);
122
123
124/**
125 * Do global VMM init.
126 *
127 * @returns VBox status code.
128 */
129VMR3DECL(int) VMR3GlobalInit(void)
130{
131 /*
132 * Only once.
133 */
134 static bool fDone = false;
135 if (fDone)
136 return VINF_SUCCESS;
137
138 /*
139 * We're done.
140 */
141 fDone = true;
142 return VINF_SUCCESS;
143}
144
145
146
147/**
148 * Creates a virtual machine by calling the supplied configuration constructor.
149 *
150 * On successful returned the VM is powered, i.e. VMR3PowerOn() should be
151 * called to start the execution.
152 *
153 * @returns 0 on success.
154 * @returns VBox error code on failure.
155 * @param pfnVMAtError Pointer to callback function for setting VM errors.
156 * This is called in the EM.
157 * @param pvUserVM The user argument passed to pfnVMAtError.
158 * @param pfnCFGMConstructor Pointer to callback function for constructing the VM configuration tree.
159 * This is called in the EM.
160 * @param pvUserCFGM The user argument passed to pfnCFGMConstructor.
161 * @param ppVM Where to store the 'handle' of the created VM.
162 */
163VMR3DECL(int) VMR3Create(PFNVMATERROR pfnVMAtError, void *pvUserVM, PFNCFGMCONSTRUCTOR pfnCFGMConstructor, void *pvUserCFGM, PVM *ppVM)
164{
165 LogFlow(("VMR3Create: pfnVMAtError=%p pvUserVM=%p pfnCFGMConstructor=%p pvUserCFGM=%p ppVM=%p\n", pfnVMAtError, pvUserVM, pfnCFGMConstructor, pvUserCFGM, ppVM));
166
167 /*
168 * Because of the current hackiness of the applications
169 * we'll have to initialize global stuff from here.
170 * Later the applications will take care of this in a proper way.
171 */
172 static bool fGlobalInitDone = false;
173 if (!fGlobalInitDone)
174 {
175 int rc = VMR3GlobalInit();
176 if (VBOX_FAILURE(rc))
177 return rc;
178 fGlobalInitDone = true;
179 }
180
181 /*
182 * Init support library.
183 */
184 PSUPDRVSESSION pSession = 0;
185 int rc = SUPInit(&pSession, 0);
186 if (VBOX_SUCCESS(rc))
187 {
188 /*
189 * Allocate memory for the VM structure.
190 */
191 PVMR0 pVMR0 = NIL_RTR0PTR;
192 PVM pVM = NULL;
193 const unsigned cPages = RT_ALIGN_Z(sizeof(*pVM), PAGE_SIZE) >> PAGE_SHIFT;
194 PSUPPAGE paPages = (PSUPPAGE)RTMemAllocZ(cPages * sizeof(SUPPAGE));
195 AssertReturn(paPages, VERR_NO_MEMORY);
196 rc = SUPLowAlloc(cPages, (void **)&pVM, &pVMR0, &paPages[0]);
197 if (VBOX_SUCCESS(rc))
198 {
199 Log(("VMR3Create: Allocated pVM=%p pVMR0=%p\n", pVM, pVMR0));
200
201 /*
202 * Do basic init of the VM structure.
203 */
204 memset(pVM, 0, sizeof(*pVM));
205 pVM->pVMHC = pVM;
206 pVM->pVMR0 = pVMR0;
207 pVM->pVMR3 = pVM;
208 pVM->paVMPagesR3 = paPages;
209 pVM->pSession = pSession;
210 pVM->vm.s.offVM = RT_OFFSETOF(VM, vm.s);
211 pVM->vm.s.ppAtResetNext = &pVM->vm.s.pAtReset;
212 pVM->vm.s.ppAtStateNext = &pVM->vm.s.pAtState;
213 pVM->vm.s.ppAtErrorNext = &pVM->vm.s.pAtError;
214 pVM->vm.s.ppAtRuntimeErrorNext = &pVM->vm.s.pAtRuntimeError;
215 rc = RTSemEventCreate(&pVM->vm.s.EventSemWait);
216 AssertRCReturn(rc, rc);
217
218 /*
219 * Initialize STAM.
220 */
221 rc = STAMR3Init(pVM);
222 if (VBOX_SUCCESS(rc))
223 {
224 /*
225 * Create the EMT thread and make it do VM initialization and go sleep
226 * in EM waiting for requests.
227 */
228 VMEMULATIONTHREADARGS Args;
229 Args.pVM = pVM;
230 rc = RTThreadCreate(&pVM->ThreadEMT, &vmR3EmulationThread, &Args, _1M,
231 RTTHREADTYPE_EMULATION, RTTHREADFLAGS_WAITABLE, "EMT");
232 if (VBOX_SUCCESS(rc))
233 {
234 /*
235 * Issue a VM Create request and wait for it to complete.
236 */
237 PVMREQ pReq;
238 rc = VMR3ReqCall(pVM, &pReq, RT_INDEFINITE_WAIT, (PFNRT)vmR3Create, 5, pVM, pfnVMAtError, pvUserVM, pfnCFGMConstructor, pvUserCFGM);
239 if (VBOX_SUCCESS(rc))
240 {
241 rc = pReq->iStatus;
242 VMR3ReqFree(pReq);
243 if (VBOX_SUCCESS(rc))
244 {
245 *ppVM = pVM;
246 LogFlow(("VMR3Create: returns VINF_SUCCESS *ppVM=%p\n", pVM));
247 return VINF_SUCCESS;
248 }
249 AssertMsgFailed(("vmR3Create failed rc=%Vrc\n", rc));
250 }
251 else
252 AssertMsgFailed(("VMR3ReqCall failed rc=%Vrc\n", rc));
253
254 /* Forcefully terminate the emulation thread. */
255 VM_FF_SET(pVM, VM_FF_TERMINATE);
256 VMR3NotifyFF(pVM, false);
257 RTThreadWait(pVM->ThreadEMT, 1000, NULL);
258 }
259
260 int rc2 = STAMR3Term(pVM);
261 AssertRC(rc2);
262 }
263
264 /* cleanup the heap. */
265 int rc2 = MMR3Term(pVM);
266 AssertRC(rc2);
267
268 /* free the VM memory */
269 rc2 = SUPLowFree(pVM, cPages);
270 AssertRC(rc2);
271 }
272 else
273 {
274 rc = VERR_NO_MEMORY;
275 vmR3CallVMAtError(pfnVMAtError, pvUserVM, rc, RT_SRC_POS,
276 N_("Failed to allocate %d bytes of contiguous memory for the VM structure!\n"),
277 RT_ALIGN(sizeof(*pVM), PAGE_SIZE));
278 AssertMsgFailed(("Failed to allocate %d bytes of contiguous memory for the VM structure!\n", RT_ALIGN(sizeof(*pVM), PAGE_SIZE)));
279 }
280 RTMemFree(paPages);
281
282 /* terminate SUPLib */
283 int rc2 = SUPTerm(false);
284 AssertRC(rc2);
285 }
286 else
287 {
288 const char *pszError;
289 /*
290 * An error occurred at support library initialization time (before the
291 * VM could be created). Set the error message directly using the
292 * initial callback, as the callback list doesn't exist yet.
293 */
294 switch (rc)
295 {
296 case VERR_VM_DRIVER_LOAD_ERROR:
297#ifdef __LINUX
298 pszError = N_("VirtualBox kernel driver not loaded. The vboxdrv kernel module "
299 "was either not loaded or /dev/vboxdrv is not set up properly. "
300 "Re-setup the kernel module by executing "
301 "'/etc/init.d/vboxdrv setup' as root");
302#else
303 pszError = N_("VirtualBox kernel driver not loaded.");
304#endif
305 break;
306 case VERR_VM_DRIVER_OPEN_ERROR:
307 pszError = N_("VirtualBox kernel driver cannot be opened");
308 break;
309 case VERR_VM_DRIVER_NOT_ACCESSIBLE:
310#ifdef RT_OS_LINUX
311 pszError = N_("The VirtualBox kernel driver is not accessible to the current "
312 "user. Make sure that the user has write permissions for "
313 "/dev/vboxdrv by adding them to the vboxusers groups. You "
314 "will need to logout for the change to take effect.");
315#else
316 pszError = N_("VirtualBox kernel driver not accessible, permission problem");
317#endif
318 break;
319 case VERR_VM_DRIVER_NOT_INSTALLED:
320#ifdef RT_OS_LINUX
321 pszError = N_("VirtualBox kernel driver not installed. The vboxdrv kernel module "
322 "was either not loaded or /dev/vboxdrv was not created for some "
323 "reason. Re-setup the kernel module by executing "
324 "'/etc/init.d/vboxdrv setup' as root");
325#else
326 pszError = N_("VirtualBox kernel driver not installed");
327#endif
328 break;
329 case VERR_NO_MEMORY:
330 pszError = N_("VirtualBox support library out of memory");
331 break;
332 case VERR_VERSION_MISMATCH:
333 pszError = N_("The VirtualBox support driver which is running is from a different "
334 "version of VirtualBox. You can correct this by stopping all "
335 "running instances of VirtualBox and reinstalling the software.");
336 break;
337 default:
338 pszError = N_("Unknown error initializing kernel driver (%Vrc)");
339 AssertMsgFailed(("Add error message for rc=%d (%Vrc)\n", rc, rc));
340 }
341 vmR3CallVMAtError(pfnVMAtError, pvUserVM, rc, RT_SRC_POS, pszError, rc);
342 }
343
344 LogFlow(("VMR3Create: returns %Vrc\n", rc));
345 return rc;
346}
347
348
349/**
350 * Wrapper for getting a correct va_list.
351 */
352static void vmR3CallVMAtError(PFNVMATERROR pfnVMAtError, void *pvUser, int rc, RT_SRC_POS_DECL, const char *pszError, ...)
353{
354 va_list va;
355 va_start(va, pszError);
356 pfnVMAtError(NULL, pvUser, rc, RT_SRC_POS_ARGS, pszError, va);
357 va_end(va);
358}
359
360
361/**
362 * Initializes the VM.
363 */
364static int vmR3Create(PVM pVM, PFNVMATERROR pfnVMAtError, void *pvUserVM, PFNCFGMCONSTRUCTOR pfnCFGMConstructor, void *pvUserCFGM)
365{
366 int rc = VINF_SUCCESS;
367
368 /* Register error callback if specified. */
369 if (pfnVMAtError)
370 rc = VMR3AtErrorRegister(pVM, pfnVMAtError, pvUserVM);
371 if (VBOX_SUCCESS(rc))
372 {
373 /*
374 * Init the configuration.
375 */
376 rc = CFGMR3Init(pVM, pfnCFGMConstructor, pvUserCFGM);
377 if (VBOX_SUCCESS(rc))
378 {
379 /*
380 * If executing in fake suplib mode disable RR3 and RR0 in the config.
381 */
382 const char *psz = getenv("VBOX_SUPLIB_FAKE");
383 if (psz && !strcmp(psz, "fake"))
384 {
385 CFGMR3RemoveValue(CFGMR3GetRoot(pVM), "RawR3Enabled");
386 CFGMR3InsertInteger(CFGMR3GetRoot(pVM), "RawR3Enabled", 0);
387 CFGMR3RemoveValue(CFGMR3GetRoot(pVM), "RawR0Enabled");
388 CFGMR3InsertInteger(CFGMR3GetRoot(pVM), "RawR0Enabled", 0);
389 }
390
391 /*
392 * Check if the required minimum of resources are available.
393 */
394 /** @todo Check if the required minimum of resources are available. */
395 if (VBOX_SUCCESS(rc))
396 {
397 /*
398 * Init the Ring-3 components and do a round of relocations with 0 delta.
399 */
400 rc = vmR3InitRing3(pVM);
401 if (VBOX_SUCCESS(rc))
402 {
403 VMR3Relocate(pVM, 0);
404 LogFlow(("Ring-3 init succeeded\n"));
405
406 /*
407 * Init the Ring-0 components.
408 */
409 rc = vmR3InitRing0(pVM);
410 if (VBOX_SUCCESS(rc))
411 {
412 /* Relocate again, because some switcher fixups depends on R0 init results. */
413 VMR3Relocate(pVM, 0);
414
415 /*
416 * Init the tcp debugger console if we're building
417 * with debugger support.
418 */
419 void *pvUser = NULL;
420 rc = DBGCTcpCreate(pVM, &pvUser);
421 if ( VBOX_SUCCESS(rc)
422 || rc == VERR_NET_ADDRESS_IN_USE)
423 {
424 pVM->vm.s.pvDBGC = pvUser;
425
426 /*
427 * Init the Guest Context components.
428 */
429 rc = vmR3InitGC(pVM);
430 if (VBOX_SUCCESS(rc))
431 {
432 /*
433 * Set the state and link into the global list.
434 */
435 vmR3SetState(pVM, VMSTATE_CREATED);
436 pVM->pNext = g_pVMsHead;
437 g_pVMsHead = pVM;
438 return VINF_SUCCESS;
439 }
440 DBGCTcpTerminate(pVM, pVM->vm.s.pvDBGC);
441 pVM->vm.s.pvDBGC = NULL;
442 }
443 //..
444 }
445 //..
446 }
447 //..
448 }
449
450 /* Clean CFGM. */
451 int rc2 = CFGMR3Term(pVM);
452 AssertRC(rc2);
453 }
454 //..
455 }
456
457 LogFlow(("vmR3Create: returns %Vrc\n", rc));
458 return rc;
459}
460
461
462
463/**
464 * Initializes all R3 components of the VM
465 */
466static int vmR3InitRing3(PVM pVM)
467{
468 int rc;
469
470 /*
471 * Init all R3 components, the order here might be important.
472 */
473 rc = vmR3SetHaltMethod(pVM, VMHALTMETHOD_DEFAULT);
474 AssertRCReturn(rc, rc);
475
476 rc = MMR3Init(pVM);
477 if (VBOX_SUCCESS(rc))
478 {
479 STAM_REG(pVM, &pVM->StatTotalInGC, STAMTYPE_PROFILE_ADV, "/PROF/VM/InGC", STAMUNIT_TICKS_PER_CALL, "Profiling the total time spent in GC.");
480 STAM_REG(pVM, &pVM->StatSwitcherToGC, STAMTYPE_PROFILE_ADV, "/PROF/VM/SwitchToGC", STAMUNIT_TICKS_PER_CALL, "Profiling switching to GC.");
481 STAM_REG(pVM, &pVM->StatSwitcherToHC, STAMTYPE_PROFILE_ADV, "/PROF/VM/SwitchToHC", STAMUNIT_TICKS_PER_CALL, "Profiling switching to HC.");
482
483 STAM_REL_REG(pVM, &pVM->vm.s.StatHaltYield, STAMTYPE_PROFILE, "/PROF/VM/Halt/Yield", STAMUNIT_TICKS_PER_CALL, "Profiling halted state yielding.");
484 STAM_REL_REG(pVM, &pVM->vm.s.StatHaltBlock, STAMTYPE_PROFILE, "/PROF/VM/Halt/Block", STAMUNIT_TICKS_PER_CALL, "Profiling halted state blocking.");
485 STAM_REL_REG(pVM, &pVM->vm.s.StatHaltTimers,STAMTYPE_PROFILE, "/PROF/VM/Halt/Timers", STAMUNIT_TICKS_PER_CALL, "Profiling halted state timer tasks.");
486 STAM_REL_REG(pVM, &pVM->vm.s.StatHaltPoll, STAMTYPE_PROFILE, "/PROF/VM/Halt/Poll", STAMUNIT_TICKS_PER_CALL, "Profiling halted state poll tasks.");
487
488 STAM_REG(pVM, &pVM->StatSwitcherSaveRegs, STAMTYPE_PROFILE_ADV, "/VM/Switcher/ToGC/SaveRegs", STAMUNIT_TICKS_PER_CALL,"Profiling switching to GC.");
489 STAM_REG(pVM, &pVM->StatSwitcherSysEnter, STAMTYPE_PROFILE_ADV, "/VM/Switcher/ToGC/SysEnter", STAMUNIT_TICKS_PER_CALL,"Profiling switching to GC.");
490 STAM_REG(pVM, &pVM->StatSwitcherDebug, STAMTYPE_PROFILE_ADV, "/VM/Switcher/ToGC/Debug", STAMUNIT_TICKS_PER_CALL,"Profiling switching to GC.");
491 STAM_REG(pVM, &pVM->StatSwitcherCR0, STAMTYPE_PROFILE_ADV, "/VM/Switcher/ToGC/CR0", STAMUNIT_TICKS_PER_CALL, "Profiling switching to GC.");
492 STAM_REG(pVM, &pVM->StatSwitcherCR4, STAMTYPE_PROFILE_ADV, "/VM/Switcher/ToGC/CR4", STAMUNIT_TICKS_PER_CALL, "Profiling switching to GC.");
493 STAM_REG(pVM, &pVM->StatSwitcherLgdt, STAMTYPE_PROFILE_ADV, "/VM/Switcher/ToGC/Lgdt", STAMUNIT_TICKS_PER_CALL, "Profiling switching to GC.");
494 STAM_REG(pVM, &pVM->StatSwitcherLidt, STAMTYPE_PROFILE_ADV, "/VM/Switcher/ToGC/Lidt", STAMUNIT_TICKS_PER_CALL, "Profiling switching to GC.");
495 STAM_REG(pVM, &pVM->StatSwitcherLldt, STAMTYPE_PROFILE_ADV, "/VM/Switcher/ToGC/Lldt", STAMUNIT_TICKS_PER_CALL, "Profiling switching to GC.");
496 STAM_REG(pVM, &pVM->StatSwitcherTSS, STAMTYPE_PROFILE_ADV, "/VM/Switcher/ToGC/TSS", STAMUNIT_TICKS_PER_CALL, "Profiling switching to GC.");
497 STAM_REG(pVM, &pVM->StatSwitcherJmpCR3, STAMTYPE_PROFILE_ADV, "/VM/Switcher/ToGC/JmpCR3", STAMUNIT_TICKS_PER_CALL,"Profiling switching to GC.");
498 STAM_REG(pVM, &pVM->StatSwitcherRstrRegs, STAMTYPE_PROFILE_ADV, "/VM/Switcher/ToGC/RstrRegs", STAMUNIT_TICKS_PER_CALL,"Profiling switching to GC.");
499
500 STAM_REG(pVM, &pVM->vm.s.StatReqAllocNew, STAMTYPE_COUNTER, "/VM/Req/AllocNew", STAMUNIT_OCCURENCES, "Number of VMR3ReqAlloc returning a new packet.");
501 STAM_REG(pVM, &pVM->vm.s.StatReqAllocRaces, STAMTYPE_COUNTER, "/VM/Req/AllocRaces", STAMUNIT_OCCURENCES, "Number of VMR3ReqAlloc causing races.");
502 STAM_REG(pVM, &pVM->vm.s.StatReqAllocRecycled, STAMTYPE_COUNTER, "/VM/Req/AllocRecycled", STAMUNIT_OCCURENCES, "Number of VMR3ReqAlloc returning a recycled packet.");
503 STAM_REG(pVM, &pVM->vm.s.StatReqFree, STAMTYPE_COUNTER, "/VM/Req/Free", STAMUNIT_OCCURENCES, "Number of VMR3ReqFree calls.");
504 STAM_REG(pVM, &pVM->vm.s.StatReqFreeOverflow, STAMTYPE_COUNTER, "/VM/Req/FreeOverflow", STAMUNIT_OCCURENCES, "Number of times the request was actually freed.");
505
506 rc = CPUMR3Init(pVM);
507 if (VBOX_SUCCESS(rc))
508 {
509 rc = HWACCMR3Init(pVM);
510 if (VBOX_SUCCESS(rc))
511 {
512 rc = PGMR3Init(pVM);
513 if (VBOX_SUCCESS(rc))
514 {
515 rc = REMR3Init(pVM);
516 if (VBOX_SUCCESS(rc))
517 {
518 rc = MMR3InitPaging(pVM);
519 if (VBOX_SUCCESS(rc))
520 rc = TMR3Init(pVM);
521 if (VBOX_SUCCESS(rc))
522 {
523 rc = VMMR3Init(pVM);
524 if (VBOX_SUCCESS(rc))
525 {
526 rc = SELMR3Init(pVM);
527 if (VBOX_SUCCESS(rc))
528 {
529 rc = TRPMR3Init(pVM);
530 if (VBOX_SUCCESS(rc))
531 {
532 rc = CSAMR3Init(pVM);
533 if (VBOX_SUCCESS(rc))
534 {
535 rc = PATMR3Init(pVM);
536 if (VBOX_SUCCESS(rc))
537 {
538 rc = IOMR3Init(pVM);
539 if (VBOX_SUCCESS(rc))
540 {
541 rc = EMR3Init(pVM);
542 if (VBOX_SUCCESS(rc))
543 {
544 rc = DBGFR3Init(pVM);
545 if (VBOX_SUCCESS(rc))
546 {
547 rc = PDMR3Init(pVM);
548 if (VBOX_SUCCESS(rc))
549 {
550 rc = PGMR3InitDynMap(pVM);
551 if (VBOX_SUCCESS(rc))
552 rc = MMR3HyperInitFinalize(pVM);
553 if (VBOX_SUCCESS(rc))
554 rc = PATMR3InitFinalize(pVM);
555 if (VBOX_SUCCESS(rc))
556 rc = PGMR3InitFinalize(pVM);
557 if (VBOX_SUCCESS(rc))
558 rc = SELMR3InitFinalize(pVM);
559 if (VBOX_SUCCESS(rc))
560 rc = VMMR3InitFinalize(pVM);
561 if (VBOX_SUCCESS(rc))
562 rc = vmR3InitDoCompleted(pVM, VMINITCOMPLETED_RING3);
563 if (VBOX_SUCCESS(rc))
564 {
565 LogFlow(("vmR3InitRing3: returns %Vrc\n", VINF_SUCCESS));
566 return VINF_SUCCESS;
567 }
568 int rc2 = PDMR3Term(pVM);
569 AssertRC(rc2);
570 }
571 int rc2 = DBGFR3Term(pVM);
572 AssertRC(rc2);
573 }
574 int rc2 = EMR3Term(pVM);
575 AssertRC(rc2);
576 }
577 int rc2 = IOMR3Term(pVM);
578 AssertRC(rc2);
579 }
580 int rc2 = PATMR3Term(pVM);
581 AssertRC(rc2);
582 }
583 int rc2 = CSAMR3Term(pVM);
584 AssertRC(rc2);
585 }
586 int rc2 = TRPMR3Term(pVM);
587 AssertRC(rc2);
588 }
589 int rc2 = SELMR3Term(pVM);
590 AssertRC(rc2);
591 }
592 int rc2 = VMMR3Term(pVM);
593 AssertRC(rc2);
594 }
595 int rc2 = TMR3Term(pVM);
596 AssertRC(rc2);
597 }
598 int rc2 = REMR3Term(pVM);
599 AssertRC(rc2);
600 }
601 int rc2 = PGMR3Term(pVM);
602 AssertRC(rc2);
603 }
604 int rc2 = HWACCMR3Term(pVM);
605 AssertRC(rc2);
606 }
607 //int rc2 = CPUMR3Term(pVM);
608 //AssertRC(rc2);
609 }
610 /* MMR3Term is not called here because it'll kill the heap. */
611 }
612
613 LogFlow(("vmR3InitRing3: returns %Vrc\n", rc));
614 return rc;
615}
616
617
618/**
619 * Initializes all R0 components of the VM
620 */
621static int vmR3InitRing0(PVM pVM)
622{
623 LogFlow(("vmR3InitRing0:\n"));
624
625 /*
626 * Check for FAKE suplib mode.
627 */
628 int rc = VINF_SUCCESS;
629 const char *psz = getenv("VBOX_SUPLIB_FAKE");
630 if (!psz || strcmp(psz, "fake"))
631 {
632 /*
633 * Call the VMMR0 component and let it do the init.
634 */
635 rc = VMMR3InitR0(pVM);
636 }
637 else
638 Log(("vmR3InitRing0: skipping because of VBOX_SUPLIB_FAKE=fake\n"));
639
640 /*
641 * Do notifications and return.
642 */
643 if (VBOX_SUCCESS(rc))
644 rc = vmR3InitDoCompleted(pVM, VMINITCOMPLETED_RING0);
645 LogFlow(("vmR3InitRing0: returns %Vrc\n", rc));
646 return rc;
647}
648
649
650/**
651 * Initializes all GC components of the VM
652 */
653static int vmR3InitGC(PVM pVM)
654{
655 LogFlow(("vmR3InitGC:\n"));
656
657 /*
658 * Check for FAKE suplib mode.
659 */
660 int rc = VINF_SUCCESS;
661 const char *psz = getenv("VBOX_SUPLIB_FAKE");
662 if (!psz || strcmp(psz, "fake"))
663 {
664 /*
665 * Call the VMMR0 component and let it do the init.
666 */
667 rc = VMMR3InitGC(pVM);
668 }
669 else
670 Log(("vmR3InitGC: skipping because of VBOX_SUPLIB_FAKE=fake\n"));
671
672 /*
673 * Do notifications and return.
674 */
675 if (VBOX_SUCCESS(rc))
676 rc = vmR3InitDoCompleted(pVM, VMINITCOMPLETED_GC);
677 LogFlow(("vmR3InitGC: returns %Vrc\n", rc));
678 return rc;
679}
680
681
682/**
683 * Do init completed notifications.
684 * This notifications can fail.
685 *
686 * @param pVM The VM handle.
687 * @param enmWhat What's completed.
688 */
689static int vmR3InitDoCompleted(PVM pVM, VMINITCOMPLETED enmWhat)
690{
691
692 return VINF_SUCCESS;
693}
694
695
696/**
697 * Calls the relocation functions for all VMM components so they can update
698 * any GC pointers. When this function is called all the basic VM members
699 * have been updated and the actual memory relocation have been done
700 * by the PGM/MM.
701 *
702 * This is used both on init and on runtime relocations.
703 *
704 * @param pVM VM handle.
705 * @param offDelta Relocation delta relative to old location.
706 */
707VMR3DECL(void) VMR3Relocate(PVM pVM, RTGCINTPTR offDelta)
708{
709 LogFlow(("VMR3Relocate: offDelta=%VGv\n", offDelta));
710
711 /*
712 * The order here is very important!
713 */
714 PGMR3Relocate(pVM, offDelta);
715 PDMR3LdrRelocate(pVM, offDelta);
716 PGMR3Relocate(pVM, 0); /* Repeat after PDM relocation. */
717 CPUMR3Relocate(pVM);
718 HWACCMR3Relocate(pVM);
719 SELMR3Relocate(pVM);
720 VMMR3Relocate(pVM, offDelta);
721 SELMR3Relocate(pVM); /* !hack! fix stack! */
722 TRPMR3Relocate(pVM, offDelta);
723 PATMR3Relocate(pVM);
724 CSAMR3Relocate(pVM, offDelta);
725 IOMR3Relocate(pVM, offDelta);
726 EMR3Relocate(pVM);
727 TMR3Relocate(pVM, offDelta);
728 DBGFR3Relocate(pVM, offDelta);
729 PDMR3Relocate(pVM, offDelta);
730}
731
732
733
734/**
735 * Power on the virtual machine.
736 *
737 * @returns 0 on success.
738 * @returns VBox error code on failure.
739 * @param pVM VM to power on.
740 * @thread Any thread.
741 * @vmstate Created
742 * @vmstateto Running
743 */
744VMR3DECL(int) VMR3PowerOn(PVM pVM)
745{
746 LogFlow(("VMR3PowerOn: pVM=%p\n", pVM));
747
748 /*
749 * Validate input.
750 */
751 if (!pVM)
752 {
753 AssertMsgFailed(("Invalid VM pointer\n"));
754 return VERR_INVALID_PARAMETER;
755 }
756
757 /*
758 * Request the operation in EMT.
759 */
760 PVMREQ pReq;
761 int rc = VMR3ReqCall(pVM, &pReq, RT_INDEFINITE_WAIT, (PFNRT)vmR3PowerOn, 1, pVM);
762 if (VBOX_SUCCESS(rc))
763 {
764 rc = pReq->iStatus;
765 VMR3ReqFree(pReq);
766 }
767
768 LogFlow(("VMR3PowerOn: returns %Vrc\n", rc));
769 return rc;
770}
771
772
773/**
774 * Power on the virtual machine.
775 *
776 * @returns 0 on success.
777 * @returns VBox error code on failure.
778 * @param pVM VM to power on.
779 * @thread EMT
780 */
781static DECLCALLBACK(int) vmR3PowerOn(PVM pVM)
782{
783 LogFlow(("vmR3PowerOn: pVM=%p\n", pVM));
784
785 /*
786 * Validate input.
787 */
788 if (pVM->enmVMState != VMSTATE_CREATED)
789 {
790 AssertMsgFailed(("Invalid VM state %d\n", pVM->enmVMState));
791 return VERR_VM_INVALID_VM_STATE;
792 }
793
794 /*
795 * Change the state, notify the components and resume the execution.
796 */
797 vmR3SetState(pVM, VMSTATE_RUNNING);
798 PDMR3PowerOn(pVM);
799
800 return VINF_SUCCESS;
801}
802
803
804/**
805 * Suspends a running VM.
806 *
807 * @returns 0 on success.
808 * @returns VBox error code on failure.
809 * @param pVM VM to suspend.
810 * @thread Any thread.
811 * @vmstate Running
812 * @vmstateto Suspended
813 */
814VMR3DECL(int) VMR3Suspend(PVM pVM)
815{
816 LogFlow(("VMR3Suspend: pVM=%p\n", pVM));
817
818 /*
819 * Validate input.
820 */
821 if (!pVM)
822 {
823 AssertMsgFailed(("Invalid VM pointer\n"));
824 return VERR_INVALID_PARAMETER;
825 }
826
827 /*
828 * Request the operation in EMT.
829 */
830 PVMREQ pReq;
831 int rc = VMR3ReqCall(pVM, &pReq, RT_INDEFINITE_WAIT, (PFNRT)vmR3Suspend, 1, pVM);
832 if (VBOX_SUCCESS(rc))
833 {
834 rc = pReq->iStatus;
835 VMR3ReqFree(pReq);
836 }
837
838 LogFlow(("VMR3Suspend: returns %Vrc\n", rc));
839 return rc;
840}
841
842
843/**
844 * Suspends a running VM and prevent state saving until the VM is resumed or stopped.
845 *
846 * @returns 0 on success.
847 * @returns VBox error code on failure.
848 * @param pVM VM to suspend.
849 * @thread Any thread.
850 * @vmstate Running
851 * @vmstateto Suspended
852 */
853VMR3DECL(int) VMR3SuspendNoSave(PVM pVM)
854{
855 pVM->vm.s.fPreventSaveState = true;
856 return VMR3Suspend(pVM);
857}
858
859/**
860 * Suspends a running VM.
861 *
862 * @returns 0 on success.
863 * @returns VBox error code on failure.
864 * @param pVM VM to suspend.
865 * @thread EMT
866 */
867static DECLCALLBACK(int) vmR3Suspend(PVM pVM)
868{
869 LogFlow(("vmR3Suspend: pVM=%p\n", pVM));
870
871 /*
872 * Validate input.
873 */
874 if (pVM->enmVMState != VMSTATE_RUNNING)
875 {
876 AssertMsgFailed(("Invalid VM state %d\n", pVM->enmVMState));
877 return VERR_VM_INVALID_VM_STATE;
878 }
879
880 /*
881 * Change the state, notify the components and resume the execution.
882 */
883 vmR3SetState(pVM, VMSTATE_SUSPENDED);
884 PDMR3Suspend(pVM);
885
886 return VINF_EM_SUSPEND;
887}
888
889
890/**
891 * Resume VM execution.
892 *
893 * @returns 0 on success.
894 * @returns VBox error code on failure.
895 * @param pVM The VM to resume.
896 * @thread Any thread.
897 * @vmstate Suspended
898 * @vmstateto Running
899 */
900VMR3DECL(int) VMR3Resume(PVM pVM)
901{
902 LogFlow(("VMR3Resume: pVM=%p\n", pVM));
903
904 /*
905 * Validate input.
906 */
907 if (!pVM)
908 {
909 AssertMsgFailed(("Invalid VM pointer\n"));
910 return VERR_INVALID_PARAMETER;
911 }
912
913 /*
914 * Request the operation in EMT.
915 */
916 PVMREQ pReq;
917 int rc = VMR3ReqCall(pVM, &pReq, RT_INDEFINITE_WAIT, (PFNRT)vmR3Resume, 1, pVM);
918 if (VBOX_SUCCESS(rc))
919 {
920 rc = pReq->iStatus;
921 VMR3ReqFree(pReq);
922 }
923
924 LogFlow(("VMR3Resume: returns %Vrc\n", rc));
925 return rc;
926}
927
928
929/**
930 * Resume VM execution.
931 *
932 * @returns 0 on success.
933 * @returns VBox error code on failure.
934 * @param pVM The VM to resume.
935 * @thread EMT
936 */
937static DECLCALLBACK(int) vmR3Resume(PVM pVM)
938{
939 LogFlow(("vmR3Resume: pVM=%p\n", pVM));
940
941 /*
942 * Validate input.
943 */
944 if (pVM->enmVMState != VMSTATE_SUSPENDED)
945 {
946 AssertMsgFailed(("Invalid VM state %d\n", pVM->enmVMState));
947 return VERR_VM_INVALID_VM_STATE;
948 }
949
950 /*
951 * Change the state, notify the components and resume the execution.
952 */
953 pVM->vm.s.fPreventSaveState = false;
954 vmR3SetState(pVM, VMSTATE_RUNNING);
955 PDMR3Resume(pVM);
956
957 return VINF_EM_RESUME;
958}
959
960
961/**
962 * Save current VM state.
963 *
964 * To save and terminate the VM, the VM must be suspended before the call.
965 *
966 * @returns 0 on success.
967 * @returns VBox error code on failure.
968 * @param pVM VM which state should be saved.
969 * @param pszFilename Name of the save state file.
970 * @param pfnProgress Progress callback. Optional.
971 * @param pvUser User argument for the progress callback.
972 * @thread Any thread.
973 * @vmstate Suspended
974 * @vmstateto Unchanged state.
975 */
976VMR3DECL(int) VMR3Save(PVM pVM, const char *pszFilename, PFNVMPROGRESS pfnProgress, void *pvUser)
977{
978 LogFlow(("VMR3Save: pVM=%p pszFilename=%p:{%s} pfnProgress=%p pvUser=%p\n", pVM, pszFilename, pszFilename, pfnProgress, pvUser));
979
980 /*
981 * Validate input.
982 */
983 if (!pVM)
984 {
985 AssertMsgFailed(("Invalid VM pointer\n"));
986 return VERR_INVALID_PARAMETER;
987 }
988 if (!pszFilename)
989 {
990 AssertMsgFailed(("Must specify a filename to save the state to, wise guy!\n"));
991 return VERR_INVALID_PARAMETER;
992 }
993
994 /*
995 * Request the operation in EMT.
996 */
997 PVMREQ pReq;
998 int rc = VMR3ReqCall(pVM, &pReq, RT_INDEFINITE_WAIT, (PFNRT)vmR3Save, 4, pVM, pszFilename, pfnProgress, pvUser);
999 if (VBOX_SUCCESS(rc))
1000 {
1001 rc = pReq->iStatus;
1002 VMR3ReqFree(pReq);
1003 }
1004
1005 LogFlow(("VMR3Save: returns %Vrc\n", rc));
1006 return rc;
1007}
1008
1009
1010/**
1011 * Save current VM state.
1012 *
1013 * To save and terminate the VM, the VM must be suspended before the call.
1014 *
1015 * @returns 0 on success.
1016 * @returns VBox error code on failure.
1017 * @param pVM VM which state should be saved.
1018 * @param pszFilename Name of the save state file.
1019 * @param pfnProgress Progress callback. Optional.
1020 * @param pvUser User argument for the progress callback.
1021 * @thread EMT
1022 */
1023static DECLCALLBACK(int) vmR3Save(PVM pVM, const char *pszFilename, PFNVMPROGRESS pfnProgress, void *pvUser)
1024{
1025 LogFlow(("vmR3Save: pVM=%p pszFilename=%p:{%s} pfnProgress=%p pvUser=%p\n", pVM, pszFilename, pszFilename, pfnProgress, pvUser));
1026
1027 /*
1028 * Validate input.
1029 */
1030 if (pVM->enmVMState != VMSTATE_SUSPENDED)
1031 {
1032 AssertMsgFailed(("Invalid VM state %d\n", pVM->enmVMState));
1033 return VERR_VM_INVALID_VM_STATE;
1034 }
1035
1036 /* If we are in an inconsistent state, then we don't allow state saving. */
1037 if (pVM->vm.s.fPreventSaveState)
1038 {
1039 LogRel(("VMM: vmR3Save: saving the VM state is not allowed at this moment\n"));
1040 return VERR_VM_SAVE_STATE_NOT_ALLOWED;
1041 }
1042
1043 /*
1044 * Change the state and perform the save.
1045 */
1046 /** @todo implement progress support in SSM */
1047 vmR3SetState(pVM, VMSTATE_SAVING);
1048 int rc = SSMR3Save(pVM, pszFilename, SSMAFTER_CONTINUE, pfnProgress, pvUser);
1049 vmR3SetState(pVM, VMSTATE_SUSPENDED);
1050
1051 return rc;
1052}
1053
1054
1055/**
1056 * Loads a new VM state.
1057 *
1058 * To restore a saved state on VM startup, call this function and then
1059 * resume the VM instead of powering it on.
1060 *
1061 * @returns 0 on success.
1062 * @returns VBox error code on failure.
1063 * @param pVM VM which state should be saved.
1064 * @param pszFilename Name of the save state file.
1065 * @param pfnProgress Progress callback. Optional.
1066 * @param pvUser User argument for the progress callback.
1067 * @thread Any thread.
1068 * @vmstate Created, Suspended
1069 * @vmstateto Suspended
1070 */
1071VMR3DECL(int) VMR3Load(PVM pVM, const char *pszFilename, PFNVMPROGRESS pfnProgress, void *pvUser)
1072{
1073 LogFlow(("VMR3Load: pVM=%p pszFilename=%p:{%s} pfnProgress=%p pvUser=%p\n", pVM, pszFilename, pszFilename, pfnProgress, pvUser));
1074
1075 /*
1076 * Validate input.
1077 */
1078 if (!pVM)
1079 {
1080 AssertMsgFailed(("Invalid VM pointer\n"));
1081 return VERR_INVALID_PARAMETER;
1082 }
1083 if (!pszFilename)
1084 {
1085 AssertMsgFailed(("Must specify a filename to load the state from, wise guy!\n"));
1086 return VERR_INVALID_PARAMETER;
1087 }
1088
1089 /*
1090 * Request the operation in EMT.
1091 */
1092 PVMREQ pReq;
1093 int rc = VMR3ReqCall(pVM, &pReq, RT_INDEFINITE_WAIT, (PFNRT)vmR3Load, 4, pVM, pszFilename, pfnProgress, pvUser);
1094 if (VBOX_SUCCESS(rc))
1095 {
1096 rc = pReq->iStatus;
1097 VMR3ReqFree(pReq);
1098 }
1099
1100 LogFlow(("VMR3Load: returns %Vrc\n", rc));
1101 return rc;
1102}
1103
1104
1105/**
1106 * Loads a new VM state.
1107 *
1108 * To restore a saved state on VM startup, call this function and then
1109 * resume the VM instead of powering it on.
1110 *
1111 * @returns 0 on success.
1112 * @returns VBox error code on failure.
1113 * @param pVM VM which state should be saved.
1114 * @param pszFilename Name of the save state file.
1115 * @param pfnProgress Progress callback. Optional.
1116 * @param pvUser User argument for the progress callback.
1117 * @thread EMT.
1118 */
1119static DECLCALLBACK(int) vmR3Load(PVM pVM, const char *pszFilename, PFNVMPROGRESS pfnProgress, void *pvUser)
1120{
1121 LogFlow(("vmR3Load: pVM=%p pszFilename=%p:{%s} pfnProgress=%p pvUser=%p\n", pVM, pszFilename, pszFilename, pfnProgress, pvUser));
1122
1123 /*
1124 * Validate input.
1125 */
1126 if ( pVM->enmVMState != VMSTATE_SUSPENDED
1127 && pVM->enmVMState != VMSTATE_CREATED)
1128 {
1129 AssertMsgFailed(("Invalid VM state %d\n", pVM->enmVMState));
1130 return VMSetError(pVM, VERR_VM_INVALID_VM_STATE, RT_SRC_POS, N_("Invalid VM state (%s) for restoring state from '%s'"),
1131 VMR3GetStateName(pVM->enmVMState), pszFilename);
1132 }
1133
1134 /*
1135 * Change the state and perform the load.
1136 */
1137 vmR3SetState(pVM, VMSTATE_LOADING);
1138 int rc = SSMR3Load(pVM, pszFilename, SSMAFTER_RESUME, pfnProgress, pvUser);
1139 if (VBOX_SUCCESS(rc))
1140 {
1141 /* Not paranoia anymore; the saved guest might use different hypervisor selectors. We must call VMR3Relocate. */
1142 VMR3Relocate(pVM, 0);
1143 vmR3SetState(pVM, VMSTATE_SUSPENDED);
1144 }
1145 else
1146 {
1147 vmR3SetState(pVM, VMSTATE_LOAD_FAILURE);
1148 rc = VMSetError(pVM, rc, RT_SRC_POS, N_("Failed to restore VM state from '%s' (%Vrc)"), pszFilename, rc);
1149 }
1150
1151 return rc;
1152}
1153
1154
1155/**
1156 * Power Off the VM.
1157 *
1158 * @returns 0 on success.
1159 * @returns VBox error code on failure.
1160 * @param pVM VM which should be destroyed.
1161 * @thread Any thread.
1162 * @vmstate Suspended, Running, Guru Mediation, Load Failure
1163 * @vmstateto Off
1164 */
1165VMR3DECL(int) VMR3PowerOff(PVM pVM)
1166{
1167 LogFlow(("VMR3PowerOff: pVM=%p\n", pVM));
1168
1169 /*
1170 * Validate input.
1171 */
1172 if (!pVM)
1173 {
1174 AssertMsgFailed(("Invalid VM pointer\n"));
1175 return VERR_INVALID_PARAMETER;
1176 }
1177
1178 /*
1179 * Request the operation in EMT.
1180 */
1181 PVMREQ pReq;
1182 int rc = VMR3ReqCall(pVM, &pReq, RT_INDEFINITE_WAIT, (PFNRT)vmR3PowerOff, 1, pVM);
1183 if (VBOX_SUCCESS(rc))
1184 {
1185 rc = pReq->iStatus;
1186 VMR3ReqFree(pReq);
1187 }
1188
1189 LogFlow(("VMR3PowerOff: returns %Vrc\n", rc));
1190 return rc;
1191}
1192
1193
1194/**
1195 * Power Off the VM.
1196 *
1197 * @returns 0 on success.
1198 * @returns VBox error code on failure.
1199 * @param pVM VM which should be destroyed.
1200 * @thread EMT.
1201 */
1202static DECLCALLBACK(int) vmR3PowerOff(PVM pVM)
1203{
1204 LogFlow(("vmR3PowerOff: pVM=%p\n", pVM));
1205
1206 /*
1207 * Validate input.
1208 */
1209 if ( pVM->enmVMState != VMSTATE_RUNNING
1210 && pVM->enmVMState != VMSTATE_SUSPENDED
1211 && pVM->enmVMState != VMSTATE_LOAD_FAILURE
1212 && pVM->enmVMState != VMSTATE_GURU_MEDITATION)
1213 {
1214 AssertMsgFailed(("Invalid VM state %d\n", pVM->enmVMState));
1215 return VERR_VM_INVALID_VM_STATE;
1216 }
1217
1218 /*
1219 * For debugging purposes, we will log a summary of the guest state at this point.
1220 */
1221 if (pVM->enmVMState != VMSTATE_GURU_MEDITATION)
1222 {
1223 /** @todo make the state dumping at VMR3PowerOff optional. */
1224 RTLogRelPrintf("****************** Guest state at power off ******************\n");
1225 DBGFR3Info(pVM, "cpumguest", "verbose", DBGFR3InfoLogRelHlp());
1226 RTLogRelPrintf("***\n");
1227 DBGFR3Info(pVM, "mode", NULL, DBGFR3InfoLogRelHlp());
1228 RTLogRelPrintf("***\n");
1229 DBGFR3Info(pVM, "activetimers", NULL, DBGFR3InfoLogRelHlp());
1230 RTLogRelPrintf("***\n");
1231 DBGFR3Info(pVM, "gdt", NULL, DBGFR3InfoLogRelHlp());
1232 /** @todo dump guest call stack. */
1233#if 1 // temporary while debugging #1589
1234 RTLogRelPrintf("***\n");
1235 uint32_t esp = CPUMGetGuestESP(pVM);
1236 if ( CPUMGetGuestSS(pVM) == 0
1237 && esp < _64K)
1238 {
1239 RTLogRelPrintf("***\n"
1240 "ss:sp=0000:%04x ", esp);
1241 void *pv;
1242 int rc = PGMPhysGCPtr2HCPtr(pVM, esp, &pv);
1243 if (VBOX_SUCCESS(rc))
1244 {
1245 const uint8_t *pb = (uint8_t *)((uintptr_t)pv & ~(uintptr_t)0x3f);
1246 RTLogRelPrintf("pb=%p pv=%p\n"
1247 "%.*Rhxd\n", pb, pv,
1248 PAGE_SIZE - ((uintptr_t)pb & PAGE_OFFSET_MASK), pb);
1249 }
1250 else
1251 RTLogRelPrintf("rc=%Vrc\n", rc);
1252 /* grub ... */
1253 if (esp < 0x2000 && esp > 0x1fc0)
1254 {
1255 int rc = PGMPhysGCPtr2HCPtr(pVM, 0x8000, &pv);
1256 if (VBOX_SUCCESS(rc))
1257 RTLogRelPrintf("0000:8000 TO 0000:87ff: pv=%p\n"
1258 "%.*Rhxd\n", pv, 0x8000, pv);
1259 }
1260 /* microsoft cdrom hang ... */
1261 if (true)
1262 {
1263 int rc = PGMPhysGCPtr2HCPtr(pVM, 0x20000, &pv);
1264 if (VBOX_SUCCESS(rc))
1265 RTLogRelPrintf("2000:0000 TO 2000:01ff: pv=%p\n"
1266 "%.*Rhxd\n", pv, 0x200, pv);
1267 }
1268 }
1269#endif
1270 RTLogRelPrintf("************** End of Guest state at power off ***************\n");
1271 }
1272
1273 /*
1274 * Change the state to OFF and notify the components.
1275 */
1276 vmR3SetState(pVM, VMSTATE_OFF);
1277 PDMR3PowerOff(pVM);
1278
1279 return VINF_EM_OFF;
1280}
1281
1282
1283/**
1284 * Destroys the VM.
1285 * The VM must be powered off (or never really powered on) to call this function.
1286 * The VM handle is destroyed and can no longer be used up successful return.
1287 *
1288 * @returns 0 on success.
1289 * @returns VBox error code on failure.
1290 * @param pVM VM which should be destroyed.
1291 * @thread Any thread but the emulation thread.
1292 * @vmstate Off, Created
1293 * @vmstateto N/A
1294 */
1295VMR3DECL(int) VMR3Destroy(PVM pVM)
1296{
1297 LogFlow(("VMR3Destroy: pVM=%p\n", pVM));
1298
1299 /*
1300 * Validate input.
1301 */
1302 if (!pVM)
1303 return VERR_INVALID_PARAMETER;
1304 if ( pVM->enmVMState != VMSTATE_OFF
1305 && pVM->enmVMState != VMSTATE_CREATED)
1306 {
1307 AssertMsgFailed(("Invalid VM state %d\n", pVM->enmVMState));
1308 return VERR_VM_INVALID_VM_STATE;
1309 }
1310
1311 /*
1312 * Unlink the VM and change it's state to destroying.
1313 */
1314/** @todo lock this when we start having multiple machines in a process... */
1315 PVM pPrev = NULL;
1316 PVM pCur = g_pVMsHead;
1317 while (pCur && pCur != pVM)
1318 {
1319 pPrev = pCur;
1320 pCur = pCur->pNext;
1321 }
1322 if (!pCur)
1323 {
1324 AssertMsgFailed(("pVM=%p is INVALID!\n", pVM));
1325 return VERR_INVALID_PARAMETER;
1326 }
1327 if (pPrev)
1328 pPrev->pNext = pCur->pNext;
1329 else
1330 g_pVMsHead = pCur->pNext;
1331
1332 vmR3SetState(pVM, VMSTATE_DESTROYING);
1333
1334
1335 /*
1336 * Notify registered at destruction listeners.
1337 * (That's the debugger console.)
1338 */
1339 vmR3AtDtor(pVM);
1340
1341 pVM->pNext = g_pVMsHead;
1342 g_pVMsHead = pVM;
1343
1344 /*
1345 * If we are the EMT we'll delay the cleanup till later.
1346 */
1347 if (VM_IS_EMT(pVM))
1348 {
1349 pVM->vm.s.fEMTDoesTheCleanup = true;
1350 VM_FF_SET(pVM, VM_FF_TERMINATE);
1351 }
1352 else
1353 {
1354 /*
1355 * Request EMT to do the larger part of the destruction.
1356 */
1357 PVMREQ pReq = NULL;
1358 int rc = VMR3ReqCall(pVM, &pReq, 0, (PFNRT)vmR3Destroy, 1, pVM);
1359 while (rc == VERR_TIMEOUT)
1360 rc = VMR3ReqWait(pReq, RT_INDEFINITE_WAIT);
1361 if (VBOX_SUCCESS(rc))
1362 rc = pReq->iStatus;
1363 VMR3ReqFree(pReq);
1364
1365 /*
1366 * Wait for the EMT thread to terminate.
1367 */
1368 VM_FF_SET(pVM, VM_FF_TERMINATE);
1369 uint64_t u64Start = RTTimeMilliTS();
1370 do
1371 {
1372 VMR3NotifyFF(pVM, false);
1373 rc = RTThreadWait(pVM->ThreadEMT, 1000, NULL);
1374 } while ( RTTimeMilliTS() - u64Start < 30000 /* 30 sec */
1375 && rc == VERR_TIMEOUT);
1376 AssertMsgRC(rc, ("EMT thread wait failed, rc=%Vrc\n", rc));
1377
1378 /*
1379 * Now do the final bit where the heap and VM structures are freed up.
1380 */
1381 vmR3DestroyFinalBit(pVM);
1382 }
1383
1384 LogFlow(("VMR3Destroy: returns VINF_SUCCESS\n"));
1385 return VINF_SUCCESS;
1386}
1387
1388
1389/**
1390 * Internal destruction worker. This will do nearly all of the
1391 * job, including quitting the emulation thread.
1392 *
1393 * @returns VBox status.
1394 * @param pVM VM handle.
1395 */
1396DECLCALLBACK(int) vmR3Destroy(PVM pVM)
1397{
1398 LogFlow(("vmR3Destroy: pVM=%p\n", pVM));
1399 VM_ASSERT_EMT(pVM);
1400
1401 /*
1402 * Dump statistics to the log.
1403 */
1404#if defined(VBOX_WITH_STATISTICS) || defined(LOG_ENABLED)
1405 RTLogFlags(NULL, "nodisabled nobuffered");
1406#endif
1407#ifdef VBOX_WITH_STATISTICS
1408 STAMR3Dump(pVM, "*");
1409#else
1410 LogRel(("************************* Statistics *************************\n"));
1411 STAMR3DumpToReleaseLog(pVM, "*");
1412 LogRel(("********************* End of statistics **********************\n"));
1413#endif
1414
1415 /*
1416 * Destroy the VM components.
1417 */
1418 int rc = TMR3Term(pVM);
1419 AssertRC(rc);
1420 rc = DBGCTcpTerminate(pVM, pVM->vm.s.pvDBGC);
1421 pVM->vm.s.pvDBGC = NULL;
1422 AssertRC(rc);
1423 rc = DBGFR3Term(pVM);
1424 AssertRC(rc);
1425 rc = PDMR3Term(pVM);
1426 AssertRC(rc);
1427 rc = EMR3Term(pVM);
1428 AssertRC(rc);
1429 rc = IOMR3Term(pVM);
1430 AssertRC(rc);
1431 rc = CSAMR3Term(pVM);
1432 AssertRC(rc);
1433 rc = PATMR3Term(pVM);
1434 AssertRC(rc);
1435 rc = TRPMR3Term(pVM);
1436 AssertRC(rc);
1437 rc = SELMR3Term(pVM);
1438 AssertRC(rc);
1439 rc = REMR3Term(pVM);
1440 AssertRC(rc);
1441 rc = HWACCMR3Term(pVM);
1442 AssertRC(rc);
1443 rc = VMMR3Term(pVM);
1444 AssertRC(rc);
1445 rc = PGMR3Term(pVM);
1446 AssertRC(rc);
1447 rc = CPUMR3Term(pVM);
1448 AssertRC(rc);
1449 rc = STAMR3Term(pVM);
1450 AssertRC(rc);
1451 rc = PDMR3CritSectTerm(pVM);
1452 AssertRC(rc);
1453 /* MM is destroyed later in vmR3DestroyFinalBit() for heap reasons. */
1454
1455 /*
1456 * We're done in this thread.
1457 */
1458 pVM->fForcedActions = VM_FF_TERMINATE;
1459 LogFlow(("vmR3Destroy: returning %Vrc\n", VINF_EM_TERMINATE));
1460 return VINF_EM_TERMINATE;
1461}
1462
1463
1464/**
1465 * Does the final part of the VM destruction.
1466 * This is called by EMT in it's final stage or by the VMR3Destroy caller.
1467 *
1468 * @param pVM VM Handle.
1469 */
1470void vmR3DestroyFinalBit(PVM pVM)
1471{
1472 /*
1473 * Free the event semaphores associated with the request packets.s
1474 */
1475 unsigned cReqs = 0;
1476 for (unsigned i = 0; i < ELEMENTS(pVM->vm.s.apReqFree); i++)
1477 {
1478 PVMREQ pReq = pVM->vm.s.apReqFree[i];
1479 pVM->vm.s.apReqFree[i] = NULL;
1480 for (; pReq; pReq = pReq->pNext, cReqs++)
1481 {
1482 pReq->enmState = VMREQSTATE_INVALID;
1483 RTSemEventDestroy(pReq->EventSem);
1484 }
1485 }
1486 Assert(cReqs == pVM->vm.s.cReqFree); NOREF(cReqs);
1487
1488 /*
1489 * Kill all queued requests. (There really shouldn't be any!)
1490 */
1491 for (unsigned i = 0; i < 10; i++)
1492 {
1493 PVMREQ pReqHead = (PVMREQ)ASMAtomicXchgPtr((void *volatile *)&pVM->vm.s.pReqs, NULL);
1494 AssertMsg(!pReqHead, ("This isn't supposed to happen! VMR3Destroy caller has to serialize this.\n"));
1495 if (!pReqHead)
1496 break;
1497 for (PVMREQ pReq = pReqHead; pReq; pReq = pReq->pNext)
1498 {
1499 ASMAtomicXchgSize(&pReq->iStatus, VERR_INTERNAL_ERROR);
1500 ASMAtomicXchgSize(&pReq->enmState, VMREQSTATE_INVALID);
1501 RTSemEventSignal(pReq->EventSem);
1502 RTThreadSleep(2);
1503 RTSemEventDestroy(pReq->EventSem);
1504 }
1505 /* give them a chance to respond before we free the request memory. */
1506 RTThreadSleep(32);
1507 }
1508
1509 /*
1510 * Modify state and then terminate MM.
1511 * (MM must be delayed until this point so we don't destroy the callbacks and the request packet.)
1512 */
1513 vmR3SetState(pVM, VMSTATE_TERMINATED);
1514 int rc = MMR3Term(pVM);
1515 AssertRC(rc);
1516
1517 /*
1518 * Free the VM structure.
1519 */
1520 rc = SUPLowFree(pVM, RT_ALIGN_Z(sizeof(*pVM), PAGE_SIZE) >> PAGE_SHIFT);
1521 AssertRC(rc);
1522 rc = SUPTerm();
1523 AssertRC(rc);
1524
1525 RTLogFlush(NULL);
1526}
1527
1528
1529/**
1530 * Enumerates the VMs in this process.
1531 *
1532 * @returns Pointer to the next VM.
1533 * @returns NULL when no more VMs.
1534 * @param pVMPrev The previous VM
1535 * Use NULL to start the enumeration.
1536 */
1537VMR3DECL(PVM) VMR3EnumVMs(PVM pVMPrev)
1538{
1539 /*
1540 * This is quick and dirty. It has issues with VM being
1541 * destroyed during the enumeration.
1542 */
1543 if (pVMPrev)
1544 return pVMPrev->pNext;
1545 return g_pVMsHead;
1546}
1547
1548
1549/**
1550 * Registers an at VM destruction callback.
1551 *
1552 * @returns VBox status code.
1553 * @param pfnAtDtor Pointer to callback.
1554 * @param pvUser User argument.
1555 */
1556VMR3DECL(int) VMR3AtDtorRegister(PFNVMATDTOR pfnAtDtor, void *pvUser)
1557{
1558 /*
1559 * Check if already registered.
1560 */
1561 VM_ATDTOR_LOCK();
1562 PVMATDTOR pCur = g_pVMAtDtorHead;
1563 while (pCur)
1564 {
1565 if (pfnAtDtor == pCur->pfnAtDtor)
1566 {
1567 VM_ATDTOR_UNLOCK();
1568 AssertMsgFailed(("Already registered at destruction callback %p!\n", pfnAtDtor));
1569 return VERR_INVALID_PARAMETER;
1570 }
1571
1572 /* next */
1573 pCur = pCur->pNext;
1574 }
1575 VM_ATDTOR_UNLOCK();
1576
1577 /*
1578 * Allocate new entry.
1579 */
1580 PVMATDTOR pVMAtDtor = (PVMATDTOR)RTMemAlloc(sizeof(*pVMAtDtor));
1581 if (!pVMAtDtor)
1582 return VERR_NO_MEMORY;
1583
1584 VM_ATDTOR_LOCK();
1585 pVMAtDtor->pfnAtDtor = pfnAtDtor;
1586 pVMAtDtor->pvUser = pvUser;
1587 pVMAtDtor->pNext = g_pVMAtDtorHead;
1588 g_pVMAtDtorHead = pVMAtDtor;
1589 VM_ATDTOR_UNLOCK();
1590
1591 return VINF_SUCCESS;
1592}
1593
1594
1595/**
1596 * Deregisters an at VM destruction callback.
1597 *
1598 * @returns VBox status code.
1599 * @param pfnAtDtor Pointer to callback.
1600 */
1601VMR3DECL(int) VMR3AtDtorDeregister(PFNVMATDTOR pfnAtDtor)
1602{
1603 /*
1604 * Find it, unlink it and free it.
1605 */
1606 VM_ATDTOR_LOCK();
1607 PVMATDTOR pPrev = NULL;
1608 PVMATDTOR pCur = g_pVMAtDtorHead;
1609 while (pCur)
1610 {
1611 if (pfnAtDtor == pCur->pfnAtDtor)
1612 {
1613 if (pPrev)
1614 pPrev->pNext = pCur->pNext;
1615 else
1616 g_pVMAtDtorHead = pCur->pNext;
1617 pCur->pNext = NULL;
1618 VM_ATDTOR_UNLOCK();
1619
1620 RTMemFree(pCur);
1621 return VINF_SUCCESS;
1622 }
1623
1624 /* next */
1625 pPrev = pCur;
1626 pCur = pCur->pNext;
1627 }
1628 VM_ATDTOR_UNLOCK();
1629
1630 return VERR_INVALID_PARAMETER;
1631}
1632
1633
1634/**
1635 * Walks the list of at VM destructor callbacks.
1636 * @param pVM The VM which is about to be destroyed.
1637 */
1638static void vmR3AtDtor(PVM pVM)
1639{
1640 /*
1641 * Find it, unlink it and free it.
1642 */
1643 VM_ATDTOR_LOCK();
1644 for (PVMATDTOR pCur = g_pVMAtDtorHead; pCur; pCur = pCur->pNext)
1645 pCur->pfnAtDtor(pVM, pCur->pvUser);
1646 VM_ATDTOR_UNLOCK();
1647}
1648
1649
1650/**
1651 * Reset the current VM.
1652 *
1653 * @returns VBox status code.
1654 * @param pVM VM to reset.
1655 */
1656VMR3DECL(int) VMR3Reset(PVM pVM)
1657{
1658 int rc = VINF_SUCCESS;
1659
1660 /*
1661 * Check the state.
1662 */
1663 if (!pVM)
1664 return VERR_INVALID_PARAMETER;
1665 if ( pVM->enmVMState != VMSTATE_RUNNING
1666 && pVM->enmVMState != VMSTATE_SUSPENDED)
1667 {
1668 AssertMsgFailed(("Invalid VM state %d\n", pVM->enmVMState));
1669 return VERR_VM_INVALID_VM_STATE;
1670 }
1671
1672 /*
1673 * Queue reset request to the emulation thread
1674 * and wait for it to be processed.
1675 */
1676 PVMREQ pReq = NULL;
1677 rc = VMR3ReqCall(pVM, &pReq, 0, (PFNRT)vmR3Reset, 1, pVM);
1678 while (rc == VERR_TIMEOUT)
1679 rc = VMR3ReqWait(pReq, RT_INDEFINITE_WAIT);
1680 if (VBOX_SUCCESS(rc))
1681 rc = pReq->iStatus;
1682 VMR3ReqFree(pReq);
1683
1684 return rc;
1685}
1686
1687
1688/**
1689 * Worker which checks integrity of some internal structures.
1690 * This is yet another attempt to track down that AVL tree crash.
1691 */
1692static void vmR3CheckIntegrity(PVM pVM)
1693{
1694#ifdef VBOX_STRICT
1695 int rc = PGMR3CheckIntegrity(pVM);
1696 AssertReleaseRC(rc);
1697#endif
1698}
1699
1700
1701/**
1702 * Reset request processor.
1703 *
1704 * This is called by the emulation thread as a response to the
1705 * reset request issued by VMR3Reset().
1706 *
1707 * @returns VBox status code.
1708 * @param pVM VM to reset.
1709 */
1710static DECLCALLBACK(int) vmR3Reset(PVM pVM)
1711{
1712 /*
1713 * As a safety precaution we temporarily change the state while resetting.
1714 * (If VMR3Reset was not called from EMT we might have change state... let's ignore that fact for now.)
1715 */
1716 VMSTATE enmVMState = pVM->enmVMState;
1717 Assert(enmVMState == VMSTATE_SUSPENDED || enmVMState == VMSTATE_RUNNING);
1718 vmR3SetState(pVM, VMSTATE_RESETTING);
1719 vmR3CheckIntegrity(pVM);
1720
1721
1722 /*
1723 * Reset the VM components.
1724 */
1725 PATMR3Reset(pVM);
1726 CSAMR3Reset(pVM);
1727 PGMR3Reset(pVM); /* We clear VM RAM in PGMR3Reset. It's vital PDMR3Reset is executed
1728 * _afterwards_. E.g. ACPI sets up RAM tables during init/reset. */
1729 PDMR3Reset(pVM);
1730 SELMR3Reset(pVM);
1731 TRPMR3Reset(pVM);
1732 vmR3AtReset(pVM);
1733 REMR3Reset(pVM);
1734 IOMR3Reset(pVM);
1735 CPUMR3Reset(pVM);
1736 TMR3Reset(pVM);
1737 EMR3Reset(pVM);
1738 HWACCMR3Reset(pVM); /* This must come *after* PATM, CSAM, CPUM, SELM and TRPM. */
1739
1740#ifdef LOG_ENABLED
1741 /*
1742 * Debug logging.
1743 */
1744 RTLogPrintf("\n\nThe VM was reset:\n");
1745 DBGFR3Info(pVM, "cpum", "verbose", NULL);
1746#endif
1747
1748 /*
1749 * Restore the state.
1750 */
1751 vmR3CheckIntegrity(pVM);
1752 Assert(pVM->enmVMState == VMSTATE_RESETTING);
1753 vmR3SetState(pVM, enmVMState);
1754
1755 return VINF_EM_RESET;
1756}
1757
1758
1759/**
1760 * Walks the list of at VM reset callbacks and calls them
1761 *
1762 * @returns VBox status code.
1763 * Any failure is fatal.
1764 * @param pVM The VM which is being reset.
1765 */
1766static int vmR3AtReset(PVM pVM)
1767{
1768 /*
1769 * Walk the list and call them all.
1770 */
1771 int rc = VINF_SUCCESS;
1772 for (PVMATRESET pCur = pVM->vm.s.pAtReset; pCur; pCur = pCur->pNext)
1773 {
1774 /* do the call */
1775 switch (pCur->enmType)
1776 {
1777 case VMATRESETTYPE_DEV:
1778 rc = pCur->u.Dev.pfnCallback(pCur->u.Dev.pDevIns, pCur->pvUser);
1779 break;
1780 case VMATRESETTYPE_INTERNAL:
1781 rc = pCur->u.Internal.pfnCallback(pVM, pCur->pvUser);
1782 break;
1783 case VMATRESETTYPE_EXTERNAL:
1784 pCur->u.External.pfnCallback(pCur->pvUser);
1785 break;
1786 default:
1787 AssertMsgFailed(("Invalid at-reset type %d!\n", pCur->enmType));
1788 return VERR_INTERNAL_ERROR;
1789 }
1790
1791 if (VBOX_FAILURE(rc))
1792 {
1793 AssertMsgFailed(("At-reset handler %s failed with rc=%d\n", pCur->pszDesc, rc));
1794 return rc;
1795 }
1796 }
1797
1798 return VINF_SUCCESS;
1799}
1800
1801
1802/**
1803 * Internal registration function
1804 */
1805static int vmr3AtResetRegister(PVM pVM, void *pvUser, const char *pszDesc, PVMATRESET *ppNew)
1806{
1807 /*
1808 * Allocate restration structure.
1809 */
1810 PVMATRESET pNew = (PVMATRESET)MMR3HeapAlloc(pVM, MM_TAG_VM, sizeof(*pNew));
1811 if (pNew)
1812 {
1813 /* fill data. */
1814 pNew->pNext = NULL;
1815 pNew->pszDesc = pszDesc;
1816 pNew->pvUser = pvUser;
1817
1818 /* insert */
1819 *pVM->vm.s.ppAtResetNext = pNew;
1820 pVM->vm.s.ppAtResetNext = &pNew->pNext;
1821
1822 return VINF_SUCCESS;
1823 }
1824 return VERR_NO_MEMORY;
1825}
1826
1827
1828/**
1829 * Registers an at VM reset callback.
1830 *
1831 * @returns VBox status code.
1832 * @param pVM The VM.
1833 * @param pDevInst Device instance.
1834 * @param pfnCallback Callback function.
1835 * @param pvUser User argument.
1836 * @param pszDesc Description (optional).
1837 */
1838VMR3DECL(int) VMR3AtResetRegister(PVM pVM, PPDMDEVINS pDevInst, PFNVMATRESET pfnCallback, void *pvUser, const char *pszDesc)
1839{
1840 /*
1841 * Validate.
1842 */
1843 if (!pDevInst)
1844 {
1845 AssertMsgFailed(("pDevIns is NULL!\n"));
1846 return VERR_INVALID_PARAMETER;
1847 }
1848
1849 /*
1850 * Create the new entry.
1851 */
1852 PVMATRESET pNew;
1853 int rc = vmr3AtResetRegister(pVM, pvUser, pszDesc, &pNew);
1854 if (VBOX_SUCCESS(rc))
1855 {
1856 /*
1857 * Fill in type data.
1858 */
1859 pNew->enmType = VMATRESETTYPE_DEV;
1860 pNew->u.Dev.pfnCallback = pfnCallback;
1861 pNew->u.Dev.pDevIns = pDevInst;
1862 }
1863
1864 return rc;
1865}
1866
1867
1868/**
1869 * Registers an at VM reset internal callback.
1870 *
1871 * @returns VBox status code.
1872 * @param pVM The VM.
1873 * @param pfnCallback Callback function.
1874 * @param pvUser User argument.
1875 * @param pszDesc Description (optional).
1876 */
1877VMR3DECL(int) VMR3AtResetRegisterInternal(PVM pVM, PFNVMATRESETINT pfnCallback, void *pvUser, const char *pszDesc)
1878{
1879 /*
1880 * Validate.
1881 */
1882 if (!pfnCallback)
1883 {
1884 AssertMsgFailed(("pfnCallback is NULL!\n"));
1885 return VERR_INVALID_PARAMETER;
1886 }
1887
1888 /*
1889 * Create the new entry.
1890 */
1891 PVMATRESET pNew;
1892 int rc = vmr3AtResetRegister(pVM, pvUser, pszDesc, &pNew);
1893 if (VBOX_SUCCESS(rc))
1894 {
1895 /*
1896 * Fill in type data.
1897 */
1898 pNew->enmType = VMATRESETTYPE_INTERNAL;
1899 pNew->u.Internal.pfnCallback = pfnCallback;
1900 }
1901
1902 return rc;
1903}
1904
1905
1906/**
1907 * Registers an at VM reset external callback.
1908 *
1909 * @returns VBox status code.
1910 * @param pVM The VM.
1911 * @param pfnCallback Callback function.
1912 * @param pvUser User argument.
1913 * @param pszDesc Description (optional).
1914 */
1915VMR3DECL(int) VMR3AtResetRegisterExternal(PVM pVM, PFNVMATRESETEXT pfnCallback, void *pvUser, const char *pszDesc)
1916{
1917 /*
1918 * Validate.
1919 */
1920 if (!pfnCallback)
1921 {
1922 AssertMsgFailed(("pfnCallback is NULL!\n"));
1923 return VERR_INVALID_PARAMETER;
1924 }
1925
1926 /*
1927 * Create the new entry.
1928 */
1929 PVMATRESET pNew;
1930 int rc = vmr3AtResetRegister(pVM, pvUser, pszDesc, &pNew);
1931 if (VBOX_SUCCESS(rc))
1932 {
1933 /*
1934 * Fill in type data.
1935 */
1936 pNew->enmType = VMATRESETTYPE_EXTERNAL;
1937 pNew->u.External.pfnCallback = pfnCallback;
1938 }
1939
1940 return rc;
1941}
1942
1943
1944/**
1945 * Unlinks and frees a callback.
1946 *
1947 * @returns Pointer to the next callback structure.
1948 * @param pVM The VM.
1949 * @param pCur The one to free.
1950 * @param pPrev The one before pCur.
1951 */
1952static PVMATRESET vmr3AtResetFree(PVM pVM, PVMATRESET pCur, PVMATRESET pPrev)
1953{
1954 /*
1955 * Unlink it.
1956 */
1957 PVMATRESET pNext = pCur->pNext;
1958 if (pPrev)
1959 {
1960 pPrev->pNext = pNext;
1961 if (!pNext)
1962 pVM->vm.s.ppAtResetNext = &pPrev->pNext;
1963 }
1964 else
1965 {
1966 pVM->vm.s.pAtReset = pNext;
1967 if (!pNext)
1968 pVM->vm.s.ppAtResetNext = &pVM->vm.s.pAtReset;
1969 }
1970
1971 /*
1972 * Free it.
1973 */
1974 MMR3HeapFree(pCur);
1975
1976 return pNext;
1977}
1978
1979
1980/**
1981 * Deregisters an at VM reset callback.
1982 *
1983 * @returns VBox status code.
1984 * @param pVM The VM.
1985 * @param pDevInst Device instance.
1986 * @param pfnCallback Callback function.
1987 */
1988VMR3DECL(int) VMR3AtResetDeregister(PVM pVM, PPDMDEVINS pDevInst, PFNVMATRESET pfnCallback)
1989{
1990 int rc = VERR_VM_ATRESET_NOT_FOUND;
1991 PVMATRESET pPrev = NULL;
1992 PVMATRESET pCur = pVM->vm.s.pAtReset;
1993 while (pCur)
1994 {
1995 if ( pCur->enmType == VMATRESETTYPE_DEV
1996 && pCur->u.Dev.pDevIns == pDevInst
1997 && (!pfnCallback || pCur->u.Dev.pfnCallback == pfnCallback))
1998 {
1999 pCur = vmr3AtResetFree(pVM, pCur, pPrev);
2000 rc = VINF_SUCCESS;
2001 }
2002 else
2003 {
2004 pPrev = pCur;
2005 pCur = pCur->pNext;
2006 }
2007 }
2008
2009 AssertRC(rc);
2010 return rc;
2011}
2012
2013
2014/**
2015 * Deregisters an at VM reset internal callback.
2016 *
2017 * @returns VBox status code.
2018 * @param pVM The VM.
2019 * @param pfnCallback Callback function.
2020 */
2021VMR3DECL(int) VMR3AtResetDeregisterInternal(PVM pVM, PFNVMATRESETINT pfnCallback)
2022{
2023 int rc = VERR_VM_ATRESET_NOT_FOUND;
2024 PVMATRESET pPrev = NULL;
2025 PVMATRESET pCur = pVM->vm.s.pAtReset;
2026 while (pCur)
2027 {
2028 if ( pCur->enmType == VMATRESETTYPE_INTERNAL
2029 && pCur->u.Internal.pfnCallback == pfnCallback)
2030 {
2031 pCur = vmr3AtResetFree(pVM, pCur, pPrev);
2032 rc = VINF_SUCCESS;
2033 }
2034 else
2035 {
2036 pPrev = pCur;
2037 pCur = pCur->pNext;
2038 }
2039 }
2040
2041 AssertRC(rc);
2042 return rc;
2043}
2044
2045
2046/**
2047 * Deregisters an at VM reset external callback.
2048 *
2049 * @returns VBox status code.
2050 * @param pVM The VM.
2051 * @param pfnCallback Callback function.
2052 */
2053VMR3DECL(int) VMR3AtResetDeregisterExternal(PVM pVM, PFNVMATRESETEXT pfnCallback)
2054{
2055 int rc = VERR_VM_ATRESET_NOT_FOUND;
2056 PVMATRESET pPrev = NULL;
2057 PVMATRESET pCur = pVM->vm.s.pAtReset;
2058 while (pCur)
2059 {
2060 if ( pCur->enmType == VMATRESETTYPE_INTERNAL
2061 && pCur->u.External.pfnCallback == pfnCallback)
2062 {
2063 pCur = vmr3AtResetFree(pVM, pCur, pPrev);
2064 rc = VINF_SUCCESS;
2065 }
2066 else
2067 {
2068 pPrev = pCur;
2069 pCur = pCur->pNext;
2070 }
2071 }
2072
2073 AssertRC(rc);
2074 return rc;
2075}
2076
2077
2078/**
2079 * Gets the current VM state.
2080 *
2081 * @returns The current VM state.
2082 * @param pVM VM handle.
2083 * @thread Any
2084 */
2085VMR3DECL(VMSTATE) VMR3GetState(PVM pVM)
2086{
2087 return pVM->enmVMState;
2088}
2089
2090
2091/**
2092 * Gets the state name string for a VM state.
2093 *
2094 * @returns Pointer to the state name. (readonly)
2095 * @param enmState The state.
2096 */
2097VMR3DECL(const char *) VMR3GetStateName(VMSTATE enmState)
2098{
2099 switch (enmState)
2100 {
2101 case VMSTATE_CREATING: return "CREATING";
2102 case VMSTATE_CREATED: return "CREATED";
2103 case VMSTATE_RUNNING: return "RUNNING";
2104 case VMSTATE_LOADING: return "LOADING";
2105 case VMSTATE_LOAD_FAILURE: return "LOAD_FAILURE";
2106 case VMSTATE_SAVING: return "SAVING";
2107 case VMSTATE_SUSPENDED: return "SUSPENDED";
2108 case VMSTATE_RESETTING: return "RESETTING";
2109 case VMSTATE_GURU_MEDITATION: return "GURU_MEDIATION";
2110 case VMSTATE_OFF: return "OFF";
2111 case VMSTATE_DESTROYING: return "DESTROYING";
2112 case VMSTATE_TERMINATED: return "TERMINATED";
2113 default:
2114 AssertMsgFailed(("Unknown state %d\n", enmState));
2115 return "Unknown!\n";
2116 }
2117}
2118
2119
2120/**
2121 * Sets the current VM state.
2122 *
2123 * @returns The current VM state.
2124 * @param pVM VM handle.
2125 * @param enmStateNew The new state.
2126 */
2127static void vmR3SetState(PVM pVM, VMSTATE enmStateNew)
2128{
2129 VMSTATE enmStateOld = pVM->enmVMState;
2130 pVM->enmVMState = enmStateNew;
2131 LogRel(("Changing the VM state from '%s' to '%s'.\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)));
2132
2133 /*
2134 * Call the at state change callbacks.
2135 */
2136 for (PVMATSTATE pCur = pVM->vm.s.pAtState; pCur; pCur = pCur->pNext)
2137 {
2138 pCur->pfnAtState(pVM, enmStateNew, enmStateOld, pCur->pvUser);
2139 if (pVM->enmVMState == VMSTATE_DESTROYING)
2140 break;
2141 AssertMsg(pVM->enmVMState == enmStateNew,
2142 ("You are not allowed to change the state while in the change callback, except "
2143 "from destroying the VM. There are restrictions in the way the state changes "
2144 "are propagated up to the EM execution loop and it makes the program flow very "
2145 "difficult to follow.\n"));
2146 }
2147}
2148
2149
2150/**
2151 * Registers a VM state change callback.
2152 *
2153 * You are not allowed to call any function which changes the VM state from a
2154 * state callback, except VMR3Destroy().
2155 *
2156 * @returns VBox status code.
2157 * @param pVM VM handle.
2158 * @param pfnAtState Pointer to callback.
2159 * @param pvUser User argument.
2160 * @thread Any.
2161 */
2162VMR3DECL(int) VMR3AtStateRegister(PVM pVM, PFNVMATSTATE pfnAtState, void *pvUser)
2163{
2164 LogFlow(("VMR3AtStateRegister: pfnAtState=%p pvUser=%p\n", pfnAtState, pvUser));
2165
2166 /*
2167 * Validate input.
2168 */
2169 if (!pfnAtState)
2170 {
2171 AssertMsgFailed(("callback is required\n"));
2172 return VERR_INVALID_PARAMETER;
2173 }
2174
2175 /*
2176 * Make sure we're in EMT (to avoid the logging).
2177 */
2178 PVMREQ pReq;
2179 int rc = VMR3ReqCall(pVM, &pReq, RT_INDEFINITE_WAIT, (PFNRT)vmR3AtStateRegister, 3, pVM, pfnAtState, pvUser);
2180 if (VBOX_FAILURE(rc))
2181 return rc;
2182 rc = pReq->iStatus;
2183 VMR3ReqFree(pReq);
2184
2185 LogFlow(("VMR3AtStateRegister: returns %Vrc\n", rc));
2186 return rc;
2187}
2188
2189
2190/**
2191 * Registers a VM state change callback.
2192 *
2193 * @returns VBox status code.
2194 * @param pVM VM handle.
2195 * @param pfnAtState Pointer to callback.
2196 * @param pvUser User argument.
2197 * @thread EMT
2198 */
2199static DECLCALLBACK(int) vmR3AtStateRegister(PVM pVM, PFNVMATSTATE pfnAtState, void *pvUser)
2200{
2201 /*
2202 * Allocate a new record.
2203 */
2204
2205 PVMATSTATE pNew = (PVMATSTATE)MMR3HeapAlloc(pVM, MM_TAG_VM, sizeof(*pNew));
2206 if (!pNew)
2207 return VERR_NO_MEMORY;
2208
2209 /* fill */
2210 pNew->pfnAtState = pfnAtState;
2211 pNew->pvUser = pvUser;
2212 pNew->pNext = NULL;
2213
2214 /* insert */
2215 *pVM->vm.s.ppAtStateNext = pNew;
2216 pVM->vm.s.ppAtStateNext = &pNew->pNext;
2217
2218 return VINF_SUCCESS;
2219}
2220
2221
2222/**
2223 * Deregisters a VM state change callback.
2224 *
2225 * @returns VBox status code.
2226 * @param pVM VM handle.
2227 * @param pfnAtState Pointer to callback.
2228 * @param pvUser User argument.
2229 * @thread Any.
2230 */
2231VMR3DECL(int) VMR3AtStateDeregister(PVM pVM, PFNVMATSTATE pfnAtState, void *pvUser)
2232{
2233 LogFlow(("VMR3AtStateDeregister: pfnAtState=%p pvUser=%p\n", pfnAtState, pvUser));
2234
2235 /*
2236 * Validate input.
2237 */
2238 if (!pfnAtState)
2239 {
2240 AssertMsgFailed(("callback is required\n"));
2241 return VERR_INVALID_PARAMETER;
2242 }
2243
2244 /*
2245 * Make sure we're in EMT (to avoid the logging).
2246 */
2247 PVMREQ pReq;
2248 int rc = VMR3ReqCall(pVM, &pReq, RT_INDEFINITE_WAIT, (PFNRT)vmR3AtStateDeregister, 3, pVM, pfnAtState, pvUser);
2249 if (VBOX_FAILURE(rc))
2250 return rc;
2251 rc = pReq->iStatus;
2252 VMR3ReqFree(pReq);
2253
2254 LogFlow(("VMR3AtStateDeregister: returns %Vrc\n", rc));
2255 return rc;
2256}
2257
2258
2259/**
2260 * Deregisters a VM state change callback.
2261 *
2262 * @returns VBox status code.
2263 * @param pVM VM handle.
2264 * @param pfnAtState Pointer to callback.
2265 * @param pvUser User argument.
2266 * @thread EMT
2267 */
2268static DECLCALLBACK(int) vmR3AtStateDeregister(PVM pVM, PFNVMATSTATE pfnAtState, void *pvUser)
2269{
2270 LogFlow(("vmR3AtStateDeregister: pfnAtState=%p pvUser=%p\n", pfnAtState, pvUser));
2271
2272 /*
2273 * Search the list for the entry.
2274 */
2275 PVMATSTATE pPrev = NULL;
2276 PVMATSTATE pCur = pVM->vm.s.pAtState;
2277 while ( pCur
2278 && pCur->pfnAtState == pfnAtState
2279 && pCur->pvUser == pvUser)
2280 {
2281 pPrev = pCur;
2282 pCur = pCur->pNext;
2283 }
2284 if (!pCur)
2285 {
2286 AssertMsgFailed(("pfnAtState=%p was not found\n", pfnAtState));
2287 return VERR_FILE_NOT_FOUND;
2288 }
2289
2290 /*
2291 * Unlink it.
2292 */
2293 if (pPrev)
2294 {
2295 pPrev->pNext = pCur->pNext;
2296 if (!pCur->pNext)
2297 pVM->vm.s.ppAtStateNext = &pPrev->pNext;
2298 }
2299 else
2300 {
2301 pVM->vm.s.pAtState = pCur->pNext;
2302 if (!pCur->pNext)
2303 pVM->vm.s.ppAtStateNext = &pVM->vm.s.pAtState;
2304 }
2305
2306 /*
2307 * Free it.
2308 */
2309 pCur->pfnAtState = NULL;
2310 pCur->pNext = NULL;
2311 MMR3HeapFree(pCur);
2312
2313 return VINF_SUCCESS;
2314}
2315
2316
2317/**
2318 * Registers a VM error callback.
2319 *
2320 * @returns VBox status code.
2321 * @param pVM The VM handle.
2322 * @param pfnAtError Pointer to callback.
2323 * @param pvUser User argument.
2324 * @thread Any.
2325 */
2326VMR3DECL(int) VMR3AtErrorRegister(PVM pVM, PFNVMATERROR pfnAtError, void *pvUser)
2327{
2328 LogFlow(("VMR3AtErrorRegister: pfnAtError=%p pvUser=%p\n", pfnAtError, pvUser));
2329
2330 /*
2331 * Validate input.
2332 */
2333 if (!pfnAtError)
2334 {
2335 AssertMsgFailed(("callback is required\n"));
2336 return VERR_INVALID_PARAMETER;
2337 }
2338
2339 /*
2340 * Make sure we're in EMT (to avoid the logging).
2341 */
2342 PVMREQ pReq;
2343 int rc = VMR3ReqCall(pVM, &pReq, RT_INDEFINITE_WAIT, (PFNRT)vmR3AtErrorRegister, 3, pVM, pfnAtError, pvUser);
2344 if (VBOX_FAILURE(rc))
2345 return rc;
2346 rc = pReq->iStatus;
2347 VMR3ReqFree(pReq);
2348
2349 LogFlow(("VMR3AtErrorRegister: returns %Vrc\n", rc));
2350 return rc;
2351}
2352
2353
2354/**
2355 * Registers a VM error callback.
2356 *
2357 * @returns VBox status code.
2358 * @param pVM The VM handle.
2359 * @param pfnAtError Pointer to callback.
2360 * @param pvUser User argument.
2361 * @thread EMT
2362 */
2363static DECLCALLBACK(int) vmR3AtErrorRegister(PVM pVM, PFNVMATERROR pfnAtError, void *pvUser)
2364{
2365 /*
2366 * Allocate a new record.
2367 */
2368
2369 PVMATERROR pNew = (PVMATERROR)MMR3HeapAlloc(pVM, MM_TAG_VM, sizeof(*pNew));
2370 if (!pNew)
2371 return VERR_NO_MEMORY;
2372
2373 /* fill */
2374 pNew->pfnAtError = pfnAtError;
2375 pNew->pvUser = pvUser;
2376 pNew->pNext = NULL;
2377
2378 /* insert */
2379 *pVM->vm.s.ppAtErrorNext = pNew;
2380 pVM->vm.s.ppAtErrorNext = &pNew->pNext;
2381
2382 return VINF_SUCCESS;
2383}
2384
2385
2386/**
2387 * Deregisters a VM error callback.
2388 *
2389 * @returns VBox status code.
2390 * @param pVM The VM handle.
2391 * @param pfnAtError Pointer to callback.
2392 * @param pvUser User argument.
2393 * @thread Any.
2394 */
2395VMR3DECL(int) VMR3AtErrorDeregister(PVM pVM, PFNVMATERROR pfnAtError, void *pvUser)
2396{
2397 LogFlow(("VMR3AtErrorDeregister: pfnAtError=%p pvUser=%p\n", pfnAtError, pvUser));
2398
2399 /*
2400 * Validate input.
2401 */
2402 if (!pfnAtError)
2403 {
2404 AssertMsgFailed(("callback is required\n"));
2405 return VERR_INVALID_PARAMETER;
2406 }
2407
2408 /*
2409 * Make sure we're in EMT (to avoid the logging).
2410 */
2411 PVMREQ pReq;
2412 int rc = VMR3ReqCall(pVM, &pReq, RT_INDEFINITE_WAIT, (PFNRT)vmR3AtErrorDeregister, 3, pVM, pfnAtError, pvUser);
2413 if (VBOX_FAILURE(rc))
2414 return rc;
2415 rc = pReq->iStatus;
2416 VMR3ReqFree(pReq);
2417
2418 LogFlow(("VMR3AtErrorDeregister: returns %Vrc\n", rc));
2419 return rc;
2420}
2421
2422
2423/**
2424 * Deregisters a VM error callback.
2425 *
2426 * @returns VBox status code.
2427 * @param pVM The VM handle.
2428 * @param pfnAtError Pointer to callback.
2429 * @param pvUser User argument.
2430 * @thread EMT
2431 */
2432static DECLCALLBACK(int) vmR3AtErrorDeregister(PVM pVM, PFNVMATERROR pfnAtError, void *pvUser)
2433{
2434 LogFlow(("vmR3AtErrorDeregister: pfnAtError=%p pvUser=%p\n", pfnAtError, pvUser));
2435
2436 /*
2437 * Search the list for the entry.
2438 */
2439 PVMATERROR pPrev = NULL;
2440 PVMATERROR pCur = pVM->vm.s.pAtError;
2441 while ( pCur
2442 && pCur->pfnAtError == pfnAtError
2443 && pCur->pvUser == pvUser)
2444 {
2445 pPrev = pCur;
2446 pCur = pCur->pNext;
2447 }
2448 if (!pCur)
2449 {
2450 AssertMsgFailed(("pfnAtError=%p was not found\n", pfnAtError));
2451 return VERR_FILE_NOT_FOUND;
2452 }
2453
2454 /*
2455 * Unlink it.
2456 */
2457 if (pPrev)
2458 {
2459 pPrev->pNext = pCur->pNext;
2460 if (!pCur->pNext)
2461 pVM->vm.s.ppAtErrorNext = &pPrev->pNext;
2462 }
2463 else
2464 {
2465 pVM->vm.s.pAtError = pCur->pNext;
2466 if (!pCur->pNext)
2467 pVM->vm.s.ppAtErrorNext = &pVM->vm.s.pAtError;
2468 }
2469
2470 /*
2471 * Free it.
2472 */
2473 pCur->pfnAtError = NULL;
2474 pCur->pNext = NULL;
2475 MMR3HeapFree(pCur);
2476
2477 return VINF_SUCCESS;
2478}
2479
2480
2481/**
2482 * Ellipsis to va_list wrapper for calling pfnAtError.
2483 */
2484static void vmR3SetErrorWorkerDoCall(PVM pVM, PVMATERROR pCur, int rc, RT_SRC_POS_DECL, const char *pszFormat, ...)
2485{
2486 va_list va;
2487 va_start(va, pszFormat);
2488 pCur->pfnAtError(pVM, pCur->pvUser, rc, RT_SRC_POS_ARGS, pszFormat, va);
2489 va_end(va);
2490}
2491
2492
2493/**
2494 * This is a worker function for GC and Ring-0 calls to VMSetError and VMSetErrorV.
2495 * The message is found in VMINT.
2496 *
2497 * @param pVM The VM handle.
2498 * @thread EMT.
2499 */
2500VMR3DECL(void) VMR3SetErrorWorker(PVM pVM)
2501{
2502 VM_ASSERT_EMT(pVM);
2503 AssertReleaseMsgFailed(("And we have a winner! You get to implement Ring-0 and GC VMSetErrorV! Contrats!\n"));
2504
2505 /*
2506 * Unpack the error (if we managed to format one).
2507 */
2508 PVMERROR pErr = pVM->vm.s.pErrorR3;
2509 const char *pszFile = NULL;
2510 const char *pszFunction = NULL;
2511 uint32_t iLine = 0;
2512 const char *pszMessage;
2513 int32_t rc = VERR_MM_HYPER_NO_MEMORY;
2514 if (pErr)
2515 {
2516 AssertCompile(sizeof(const char) == sizeof(uint8_t));
2517 if (pErr->offFile)
2518 pszFile = (const char *)pErr + pErr->offFile;
2519 iLine = pErr->iLine;
2520 if (pErr->offFunction)
2521 pszFunction = (const char *)pErr + pErr->offFunction;
2522 if (pErr->offMessage)
2523 pszMessage = (const char *)pErr + pErr->offMessage;
2524 else
2525 pszMessage = "No message!";
2526 }
2527 else
2528 pszMessage = "No message! (Failed to allocate memory to put the error message in!)";
2529
2530 /*
2531 * Call the at error callbacks.
2532 */
2533 for (PVMATERROR pCur = pVM->vm.s.pAtError; pCur; pCur = pCur->pNext)
2534 vmR3SetErrorWorkerDoCall(pVM, pCur, rc, RT_SRC_POS_ARGS, "%s", pszMessage);
2535}
2536
2537
2538/**
2539 * Worker which calls everyone listening to the VM error messages.
2540 *
2541 * @param pVM The VM handle.
2542 * @param rc The VBox status code.
2543 * @param RT_SRC_POS_DECL The source position of this error.
2544 * @param pszFormat Format string.
2545 * @param pArgs Pointer to the format arguments.
2546 * @thread EMT
2547 */
2548DECLCALLBACK(void) vmR3SetErrorV(PVM pVM, int rc, RT_SRC_POS_DECL, const char *pszFormat, va_list *pArgs)
2549{
2550#ifdef LOG_ENABLED
2551 /*
2552 * Log the error.
2553 */
2554 RTLogPrintf("VMSetError: %s(%d) %s\n", pszFile, iLine, pszFunction);
2555 va_list va3;
2556 va_copy(va3, *pArgs);
2557 RTLogPrintfV(pszFormat, va3);
2558 va_end(va3);
2559#endif
2560
2561 /*
2562 * Make a copy of the message.
2563 */
2564 vmSetErrorCopy(pVM, rc, RT_SRC_POS_ARGS, pszFormat, *pArgs);
2565
2566 /*
2567 * Call the at error callbacks.
2568 */
2569 for (PVMATERROR pCur = pVM->vm.s.pAtError; pCur; pCur = pCur->pNext)
2570 {
2571 va_list va2;
2572 va_copy(va2, *pArgs);
2573 pCur->pfnAtError(pVM, pCur->pvUser, rc, RT_SRC_POS_ARGS, pszFormat, va2);
2574 va_end(va2);
2575 }
2576}
2577
2578
2579/**
2580 * Registers a VM runtime error callback.
2581 *
2582 * @returns VBox status code.
2583 * @param pVM The VM handle.
2584 * @param pfnAtRuntimeError Pointer to callback.
2585 * @param pvUser User argument.
2586 * @thread Any.
2587 */
2588VMR3DECL(int) VMR3AtRuntimeErrorRegister(PVM pVM, PFNVMATRUNTIMEERROR pfnAtRuntimeError, void *pvUser)
2589{
2590 LogFlow(("VMR3AtRuntimeErrorRegister: pfnAtRuntimeError=%p pvUser=%p\n", pfnAtRuntimeError, pvUser));
2591
2592 /*
2593 * Validate input.
2594 */
2595 if (!pfnAtRuntimeError)
2596 {
2597 AssertMsgFailed(("callback is required\n"));
2598 return VERR_INVALID_PARAMETER;
2599 }
2600
2601 /*
2602 * Make sure we're in EMT (to avoid the logging).
2603 */
2604 PVMREQ pReq;
2605 int rc = VMR3ReqCall(pVM, &pReq, RT_INDEFINITE_WAIT, (PFNRT)vmR3AtRuntimeErrorRegister, 3, pVM, pfnAtRuntimeError, pvUser);
2606 if (VBOX_FAILURE(rc))
2607 return rc;
2608 rc = pReq->iStatus;
2609 VMR3ReqFree(pReq);
2610
2611 LogFlow(("VMR3AtRuntimeErrorRegister: returns %Vrc\n", rc));
2612 return rc;
2613}
2614
2615
2616/**
2617 * Registers a VM runtime error callback.
2618 *
2619 * @returns VBox status code.
2620 * @param pVM The VM handle.
2621 * @param pfnAtRuntimeError Pointer to callback.
2622 * @param pvUser User argument.
2623 * @thread EMT
2624 */
2625static DECLCALLBACK(int) vmR3AtRuntimeErrorRegister(PVM pVM, PFNVMATRUNTIMEERROR pfnAtRuntimeError, void *pvUser)
2626{
2627 /*
2628 * Allocate a new record.
2629 */
2630
2631 PVMATRUNTIMEERROR pNew = (PVMATRUNTIMEERROR)MMR3HeapAlloc(pVM, MM_TAG_VM, sizeof(*pNew));
2632 if (!pNew)
2633 return VERR_NO_MEMORY;
2634
2635 /* fill */
2636 pNew->pfnAtRuntimeError = pfnAtRuntimeError;
2637 pNew->pvUser = pvUser;
2638 pNew->pNext = NULL;
2639
2640 /* insert */
2641 *pVM->vm.s.ppAtRuntimeErrorNext = pNew;
2642 pVM->vm.s.ppAtRuntimeErrorNext = &pNew->pNext;
2643
2644 return VINF_SUCCESS;
2645}
2646
2647
2648/**
2649 * Deregisters a VM runtime error callback.
2650 *
2651 * @returns VBox status code.
2652 * @param pVM The VM handle.
2653 * @param pfnAtRuntimeError Pointer to callback.
2654 * @param pvUser User argument.
2655 * @thread Any.
2656 */
2657VMR3DECL(int) VMR3AtRuntimeErrorDeregister(PVM pVM, PFNVMATRUNTIMEERROR pfnAtRuntimeError, void *pvUser)
2658{
2659 LogFlow(("VMR3AtRuntimeErrorDeregister: pfnAtRuntimeError=%p pvUser=%p\n", pfnAtRuntimeError, pvUser));
2660
2661 /*
2662 * Validate input.
2663 */
2664 if (!pfnAtRuntimeError)
2665 {
2666 AssertMsgFailed(("callback is required\n"));
2667 return VERR_INVALID_PARAMETER;
2668 }
2669
2670 /*
2671 * Make sure we're in EMT (to avoid the logging).
2672 */
2673 PVMREQ pReq;
2674 int rc = VMR3ReqCall(pVM, &pReq, RT_INDEFINITE_WAIT, (PFNRT)vmR3AtRuntimeErrorDeregister, 3, pVM, pfnAtRuntimeError, pvUser);
2675 if (VBOX_FAILURE(rc))
2676 return rc;
2677 rc = pReq->iStatus;
2678 VMR3ReqFree(pReq);
2679
2680 LogFlow(("VMR3AtRuntimeErrorDeregister: returns %Vrc\n", rc));
2681 return rc;
2682}
2683
2684
2685/**
2686 * Deregisters a VM runtime error callback.
2687 *
2688 * @returns VBox status code.
2689 * @param pVM The VM handle.
2690 * @param pfnAtRuntimeError Pointer to callback.
2691 * @param pvUser User argument.
2692 * @thread EMT
2693 */
2694static DECLCALLBACK(int) vmR3AtRuntimeErrorDeregister(PVM pVM, PFNVMATRUNTIMEERROR pfnAtRuntimeError, void *pvUser)
2695{
2696 LogFlow(("vmR3AtRuntimeErrorDeregister: pfnAtRuntimeError=%p pvUser=%p\n", pfnAtRuntimeError, pvUser));
2697
2698 /*
2699 * Search the list for the entry.
2700 */
2701 PVMATRUNTIMEERROR pPrev = NULL;
2702 PVMATRUNTIMEERROR pCur = pVM->vm.s.pAtRuntimeError;
2703 while ( pCur
2704 && pCur->pfnAtRuntimeError == pfnAtRuntimeError
2705 && pCur->pvUser == pvUser)
2706 {
2707 pPrev = pCur;
2708 pCur = pCur->pNext;
2709 }
2710 if (!pCur)
2711 {
2712 AssertMsgFailed(("pfnAtRuntimeError=%p was not found\n", pfnAtRuntimeError));
2713 return VERR_FILE_NOT_FOUND;
2714 }
2715
2716 /*
2717 * Unlink it.
2718 */
2719 if (pPrev)
2720 {
2721 pPrev->pNext = pCur->pNext;
2722 if (!pCur->pNext)
2723 pVM->vm.s.ppAtRuntimeErrorNext = &pPrev->pNext;
2724 }
2725 else
2726 {
2727 pVM->vm.s.pAtRuntimeError = pCur->pNext;
2728 if (!pCur->pNext)
2729 pVM->vm.s.ppAtRuntimeErrorNext = &pVM->vm.s.pAtRuntimeError;
2730 }
2731
2732 /*
2733 * Free it.
2734 */
2735 pCur->pfnAtRuntimeError = NULL;
2736 pCur->pNext = NULL;
2737 MMR3HeapFree(pCur);
2738
2739 return VINF_SUCCESS;
2740}
2741
2742
2743/**
2744 * Ellipsis to va_list wrapper for calling pfnAtRuntimeError.
2745 */
2746static void vmR3SetRuntimeErrorWorkerDoCall(PVM pVM, PVMATRUNTIMEERROR pCur, bool fFatal,
2747 const char *pszErrorID,
2748 const char *pszFormat, ...)
2749{
2750 va_list va;
2751 va_start(va, pszFormat);
2752 pCur->pfnAtRuntimeError(pVM, pCur->pvUser, fFatal, pszErrorID, pszFormat, va);
2753 va_end(va);
2754}
2755
2756
2757/**
2758 * This is a worker function for GC and Ring-0 calls to VMSetError and VMSetErrorV.
2759 * The message is found in VMINT.
2760 *
2761 * @param pVM The VM handle.
2762 * @thread EMT.
2763 */
2764VMR3DECL(void) VMR3SetRuntimeErrorWorker(PVM pVM)
2765{
2766 VM_ASSERT_EMT(pVM);
2767 AssertReleaseMsgFailed(("And we have a winner! You get to implement Ring-0 and GC VMSetRuntimeErrorV! Contrats!\n"));
2768
2769 /*
2770 * Unpack the error (if we managed to format one).
2771 */
2772 PVMRUNTIMEERROR pErr = pVM->vm.s.pRuntimeErrorR3;
2773 const char *pszErrorID = NULL;
2774 const char *pszMessage;
2775 bool fFatal = false;
2776 if (pErr)
2777 {
2778 AssertCompile(sizeof(const char) == sizeof(uint8_t));
2779 if (pErr->offErrorID)
2780 pszErrorID = (const char *)pErr + pErr->offErrorID;
2781 if (pErr->offMessage)
2782 pszMessage = (const char *)pErr + pErr->offMessage;
2783 else
2784 pszMessage = "No message!";
2785 fFatal = pErr->fFatal;
2786 }
2787 else
2788 pszMessage = "No message! (Failed to allocate memory to put the error message in!)";
2789
2790 /*
2791 * Call the at runtime error callbacks.
2792 */
2793 for (PVMATRUNTIMEERROR pCur = pVM->vm.s.pAtRuntimeError; pCur; pCur = pCur->pNext)
2794 vmR3SetRuntimeErrorWorkerDoCall(pVM, pCur, fFatal, pszErrorID, "%s", pszMessage);
2795}
2796
2797
2798/**
2799 * Worker which calls everyone listening to the VM runtime error messages.
2800 *
2801 * @param pVM The VM handle.
2802 * @param fFatal Whether it is a fatal error or not.
2803 * @param pszErrorID Error ID string.
2804 * @param pszFormat Format string.
2805 * @param pArgs Pointer to the format arguments.
2806 * @thread EMT
2807 */
2808DECLCALLBACK(void) vmR3SetRuntimeErrorV(PVM pVM, bool fFatal,
2809 const char *pszErrorID,
2810 const char *pszFormat, va_list *pArgs)
2811{
2812 /*
2813 * Make a copy of the message.
2814 */
2815 vmSetRuntimeErrorCopy(pVM, fFatal, pszErrorID, pszFormat, *pArgs);
2816
2817 /*
2818 * Call the at error callbacks.
2819 */
2820 for (PVMATRUNTIMEERROR pCur = pVM->vm.s.pAtRuntimeError; pCur; pCur = pCur->pNext)
2821 {
2822 va_list va2;
2823 va_copy(va2, *pArgs);
2824 pCur->pfnAtRuntimeError(pVM, pCur->pvUser, fFatal, pszErrorID, pszFormat, va2);
2825 va_end(va2);
2826 }
2827}
2828
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