VirtualBox

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

Last change on this file since 2069 was 2054, checked in by vboxsync, 18 years ago

Think I found the problem with the double shutdown mess. Removing the workaround.

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