VirtualBox

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

Last change on this file since 18790 was 18767, checked in by vboxsync, 16 years ago

typo

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 101.1 KB
Line 
1/* $Id: VM.cpp 18767 2009-04-06 14:44:05Z vboxsync $ */
2/** @file
3 * VM - Virtual Machine
4 */
5
6/*
7 * Copyright (C) 2006-2007 Sun Microsystems, Inc.
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 *
17 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
18 * Clara, CA 95054 USA or visit http://www.sun.com if you need
19 * additional information or have any questions.
20 */
21
22/** @page pg_vm VM API
23 *
24 * This is the encapsulating bit. It provides the APIs that Main and VBoxBFE
25 * use to create a VMM instance for running a guest in. It also provides
26 * facilities for queuing request for execution in EMT (serialization purposes
27 * mostly) and for reporting error back to the VMM user (Main/VBoxBFE).
28 *
29 *
30 * @section sec_vm_design Design Critique / Things To Do
31 *
32 * In hindsight this component is a big design mistake, all this stuff really
33 * belongs in the VMM component. It just seemed like a kind of ok idea at a
34 * time when the VMM bit was a bit vague. 'VM' also happend to be the name of
35 * the per-VM instance structure (see vm.h), so it kind of made sense. However
36 * as it turned out, VMM(.cpp) is almost empty all it provides in ring-3 is some
37 * minor functionally and some "routing" services.
38 *
39 * Fixing this is just a matter of some more or less straight forward
40 * refactoring, the question is just when someone will get to it.
41 *
42 */
43
44/*******************************************************************************
45* Header Files *
46*******************************************************************************/
47#define LOG_GROUP LOG_GROUP_VM
48#include <VBox/cfgm.h>
49#include <VBox/vmm.h>
50#include <VBox/gvmm.h>
51#include <VBox/mm.h>
52#include <VBox/cpum.h>
53#include <VBox/selm.h>
54#include <VBox/trpm.h>
55#include <VBox/dbgf.h>
56#include <VBox/pgm.h>
57#include <VBox/pdmapi.h>
58#include <VBox/pdmcritsect.h>
59#include <VBox/em.h>
60#include <VBox/rem.h>
61#include <VBox/tm.h>
62#include <VBox/stam.h>
63#include <VBox/patm.h>
64#ifdef VBOX_WITH_VMI
65# include <VBox/parav.h>
66#endif
67#include <VBox/csam.h>
68#include <VBox/iom.h>
69#include <VBox/ssm.h>
70#include <VBox/hwaccm.h>
71#include "VMInternal.h"
72#include <VBox/vm.h>
73#include <VBox/uvm.h>
74
75#include <VBox/sup.h>
76#include <VBox/dbg.h>
77#include <VBox/err.h>
78#include <VBox/param.h>
79#include <VBox/log.h>
80#include <iprt/assert.h>
81#include <iprt/alloc.h>
82#include <iprt/asm.h>
83#include <iprt/env.h>
84#include <iprt/string.h>
85#include <iprt/time.h>
86#include <iprt/semaphore.h>
87#include <iprt/thread.h>
88
89
90/*******************************************************************************
91* Structures and Typedefs *
92*******************************************************************************/
93/**
94 * VM destruction callback registration record.
95 */
96typedef struct VMATDTOR
97{
98 /** Pointer to the next record in the list. */
99 struct VMATDTOR *pNext;
100 /** Pointer to the callback function. */
101 PFNVMATDTOR pfnAtDtor;
102 /** The user argument. */
103 void *pvUser;
104} VMATDTOR;
105/** Pointer to a VM destruction callback registration record. */
106typedef VMATDTOR *PVMATDTOR;
107
108
109/*******************************************************************************
110* Global Variables *
111*******************************************************************************/
112/** Pointer to the list of VMs. */
113static PUVM g_pUVMsHead = NULL;
114
115/** Pointer to the list of at VM destruction callbacks. */
116static PVMATDTOR g_pVMAtDtorHead = NULL;
117/** Lock the g_pVMAtDtorHead list. */
118#define VM_ATDTOR_LOCK() do { } while (0)
119/** Unlock the g_pVMAtDtorHead list. */
120#define VM_ATDTOR_UNLOCK() do { } while (0)
121
122
123/*******************************************************************************
124* Internal Functions *
125*******************************************************************************/
126static int vmR3CreateUVM(uint32_t cCPUs, PUVM *ppUVM);
127static int vmR3CreateU(PUVM pUVM, uint32_t cCPUs, PFNCFGMCONSTRUCTOR pfnCFGMConstructor, void *pvUserCFGM);
128static int vmR3InitRing3(PVM pVM, PUVM pUVM);
129static int vmR3InitVMCpu(PVM pVM);
130static int vmR3InitRing0(PVM pVM);
131static int vmR3InitGC(PVM pVM);
132static int vmR3InitDoCompleted(PVM pVM, VMINITCOMPLETED enmWhat);
133static DECLCALLBACK(int) vmR3PowerOn(PVM pVM);
134static DECLCALLBACK(int) vmR3Suspend(PVM pVM);
135static DECLCALLBACK(int) vmR3Resume(PVM pVM);
136static DECLCALLBACK(int) vmR3Save(PVM pVM, const char *pszFilename, PFNVMPROGRESS pfnProgress, void *pvUser);
137static DECLCALLBACK(int) vmR3Load(PVM pVM, const char *pszFilename, PFNVMPROGRESS pfnProgress, void *pvUser);
138static DECLCALLBACK(int) vmR3PowerOff(PVM pVM);
139static void vmR3DestroyUVM(PUVM pUVM);
140static void vmR3AtDtor(PVM pVM);
141static int vmR3AtResetU(PUVM pUVM);
142static DECLCALLBACK(int) vmR3Reset(PVM pVM);
143static DECLCALLBACK(int) vmR3AtStateRegisterU(PUVM pUVM, PFNVMATSTATE pfnAtState, void *pvUser);
144static DECLCALLBACK(int) vmR3AtStateDeregisterU(PUVM pUVM, PFNVMATSTATE pfnAtState, void *pvUser);
145static DECLCALLBACK(int) vmR3AtErrorRegisterU(PUVM pUVM, PFNVMATERROR pfnAtError, void *pvUser);
146static DECLCALLBACK(int) vmR3AtErrorDeregisterU(PUVM pUVM, PFNVMATERROR pfnAtError, void *pvUser);
147static int vmR3SetErrorU(PUVM pUVM, int rc, RT_SRC_POS_DECL, const char *pszFormat, ...);
148static DECLCALLBACK(int) vmR3AtRuntimeErrorRegisterU(PUVM pUVM, PFNVMATRUNTIMEERROR pfnAtRuntimeError, void *pvUser);
149static DECLCALLBACK(int) vmR3AtRuntimeErrorDeregisterU(PUVM pUVM, PFNVMATRUNTIMEERROR pfnAtRuntimeError, void *pvUser);
150
151
152/**
153 * Do global VMM init.
154 *
155 * @returns VBox status code.
156 */
157VMMR3DECL(int) VMR3GlobalInit(void)
158{
159 /*
160 * Only once.
161 */
162 static bool volatile s_fDone = false;
163 if (s_fDone)
164 return VINF_SUCCESS;
165
166 /*
167 * We're done.
168 */
169 s_fDone = true;
170 return VINF_SUCCESS;
171}
172
173
174
175/**
176 * Creates a virtual machine by calling the supplied configuration constructor.
177 *
178 * On successful returned the VM is powered, i.e. VMR3PowerOn() should be
179 * called to start the execution.
180 *
181 * @returns 0 on success.
182 * @returns VBox error code on failure.
183 * @param cCPUs Number of virtual CPUs for the new VM.
184 * @param pfnVMAtError Pointer to callback function for setting VM
185 * errors. This was added as an implicit call to
186 * VMR3AtErrorRegister() since there is no way the
187 * caller can get to the VM handle early enough to
188 * do this on its own.
189 * This is called in the context of an EMT.
190 * @param pvUserVM The user argument passed to pfnVMAtError.
191 * @param pfnCFGMConstructor Pointer to callback function for constructing the VM configuration tree.
192 * This is called in the context of an EMT0.
193 * @param pvUserCFGM The user argument passed to pfnCFGMConstructor.
194 * @param ppVM Where to store the 'handle' of the created VM.
195 */
196VMMR3DECL(int) VMR3Create(uint32_t cCPUs, PFNVMATERROR pfnVMAtError, void *pvUserVM, PFNCFGMCONSTRUCTOR pfnCFGMConstructor, void *pvUserCFGM, PVM *ppVM)
197{
198 LogFlow(("VMR3Create: cCPUs=%RU32 pfnVMAtError=%p pvUserVM=%p pfnCFGMConstructor=%p pvUserCFGM=%p ppVM=%p\n", cCPUs, pfnVMAtError, pvUserVM, pfnCFGMConstructor, pvUserCFGM, ppVM));
199
200 /*
201 * Because of the current hackiness of the applications
202 * we'll have to initialize global stuff from here.
203 * Later the applications will take care of this in a proper way.
204 */
205 static bool fGlobalInitDone = false;
206 if (!fGlobalInitDone)
207 {
208 int rc = VMR3GlobalInit();
209 if (RT_FAILURE(rc))
210 return rc;
211 fGlobalInitDone = true;
212 }
213
214 /*
215 * Validate input.
216 */
217#ifdef VBOX_WITH_SMP_GUESTS
218 AssertLogRelMsgReturn(cCPUs > 0 && cCPUs <= VMCPU_MAX_CPU_COUNT, ("%RU32\n", cCPUs), VERR_INVALID_PARAMETER);
219#else
220 AssertLogRelMsgReturn(cCPUs == 1, ("%RU32\n", cCPUs), VERR_INVALID_PARAMETER);
221#endif
222
223 /*
224 * Create the UVM so we can register the at-error callback
225 * and consoliate a bit of cleanup code.
226 */
227 PUVM pUVM;
228 int rc = vmR3CreateUVM(cCPUs, &pUVM);
229 if (RT_FAILURE(rc))
230 return rc;
231 if (pfnVMAtError)
232 rc = VMR3AtErrorRegisterU(pUVM, pfnVMAtError, pvUserVM);
233 if (RT_SUCCESS(rc))
234 {
235 /*
236 * Initialize the support library creating the session for this VM.
237 */
238 rc = SUPR3Init(&pUVM->vm.s.pSession);
239 if (RT_SUCCESS(rc))
240 {
241 /*
242 * Call vmR3CreateU in the EMT thread and wait for it to finish.
243 */
244 PVMREQ pReq;
245 /** @todo SMP: VMREQDEST_ANY -> VMREQDEST_CPU0 */
246 rc = VMR3ReqCallU(pUVM, VMREQDEST_ANY, &pReq, RT_INDEFINITE_WAIT, 0, (PFNRT)vmR3CreateU,
247 4, pUVM, cCPUs, pfnCFGMConstructor, pvUserCFGM);
248 if (RT_SUCCESS(rc))
249 {
250 rc = pReq->iStatus;
251 VMR3ReqFree(pReq);
252 if (RT_SUCCESS(rc))
253 {
254 /*
255 * Success!
256 */
257 *ppVM = pUVM->pVM;
258 LogFlow(("VMR3Create: returns VINF_SUCCESS *ppVM=%p\n", *ppVM));
259 return VINF_SUCCESS;
260 }
261 }
262 else
263 AssertMsgFailed(("VMR3ReqCall failed rc=%Rrc\n", rc));
264
265 /*
266 * An error occurred during VM creation. Set the error message directly
267 * using the initial callback, as the callback list doesn't exist yet.
268 */
269 const char *pszError = NULL;
270 switch (rc)
271 {
272 case VERR_VMX_IN_VMX_ROOT_MODE:
273#ifdef RT_OS_LINUX
274 pszError = N_("VirtualBox can't operate in VMX root mode. "
275 "Please disable the KVM kernel extension, recompile your kernel and reboot");
276#else
277 pszError = N_("VirtualBox can't operate in VMX root mode. Please close all other virtualization programs.");
278#endif
279 break;
280
281 case VERR_VERSION_MISMATCH:
282 pszError = N_("VMMR0 driver version mismatch. Please terminate all VMs, make sure that "
283 "VBoxNetDHCP is not running and try again. If you still get this error, "
284 "re-install VirtualBox");
285 break;
286
287 default:
288 pszError = N_("Unknown error creating VM");
289 break;
290 }
291 vmR3SetErrorU(pUVM, rc, RT_SRC_POS, pszError, rc);
292 }
293 else
294 {
295 /*
296 * An error occurred at support library initialization time (before the
297 * VM could be created). Set the error message directly using the
298 * initial callback, as the callback list doesn't exist yet.
299 */
300 const char *pszError;
301 switch (rc)
302 {
303 case VERR_VM_DRIVER_LOAD_ERROR:
304#ifdef RT_OS_LINUX
305 pszError = N_("VirtualBox kernel driver not loaded. The vboxdrv kernel module "
306 "was either not loaded or /dev/vboxdrv is not set up properly. "
307 "Re-setup the kernel module by executing "
308 "'/etc/init.d/vboxdrv setup' as root");
309#else
310 pszError = N_("VirtualBox kernel driver not loaded");
311#endif
312 break;
313 case VERR_VM_DRIVER_OPEN_ERROR:
314 pszError = N_("VirtualBox kernel driver cannot be opened");
315 break;
316 case VERR_VM_DRIVER_NOT_ACCESSIBLE:
317#ifdef VBOX_WITH_HARDENING
318 /* This should only happen if the executable wasn't hardened - bad code/build. */
319 pszError = N_("VirtualBox kernel driver not accessible, permission problem. "
320 "Re-install VirtualBox. If you are building it yourself, you "
321 "should make sure it installed correctly and that the setuid "
322 "bit is set on the executables calling VMR3Create.");
323#else
324 /* This should only happen when mixing builds or with the usual /dev/vboxdrv access issues. */
325# if defined(RT_OS_DARWIN)
326 pszError = N_("VirtualBox KEXT is not accessible, permission problem. "
327 "If you have built VirtualBox yourself, make sure that you do not "
328 "have the vboxdrv KEXT from a different build or installation loaded.");
329# elif defined(RT_OS_LINUX)
330 pszError = N_("VirtualBox kernel driver is not accessible, permission problem. "
331 "If you have built VirtualBox yourself, make sure that you do "
332 "not have the vboxdrv kernel module from a different build or "
333 "installation loaded. Also, make sure the vboxdrv udev rule gives "
334 "you the permission you need to access the device.");
335# elif defined(RT_OS_WINDOWS)
336 pszError = N_("VirtualBox kernel driver is not accessible, permission problem.");
337# else /* solaris, freebsd, ++. */
338 pszError = N_("VirtualBox kernel module is not accessible, permission problem. "
339 "If you have built VirtualBox yourself, make sure that you do "
340 "not have the vboxdrv kernel module from a different install loaded.");
341# endif
342#endif
343 break;
344 case VERR_INVALID_HANDLE: /** @todo track down and fix this error. */
345 case VERR_VM_DRIVER_NOT_INSTALLED:
346#ifdef RT_OS_LINUX
347 pszError = N_("VirtualBox kernel driver not installed. The vboxdrv kernel module "
348 "was either not loaded or /dev/vboxdrv was not created for some "
349 "reason. Re-setup the kernel module by executing "
350 "'/etc/init.d/vboxdrv setup' as root");
351#else
352 pszError = N_("VirtualBox kernel driver not installed");
353#endif
354 break;
355 case VERR_NO_MEMORY:
356 pszError = N_("VirtualBox support library out of memory");
357 break;
358 case VERR_VERSION_MISMATCH:
359 case VERR_VM_DRIVER_VERSION_MISMATCH:
360 pszError = N_("The VirtualBox support driver which is running is from a different "
361 "version of VirtualBox. You can correct this by stopping all "
362 "running instances of VirtualBox and reinstalling the software.");
363 break;
364 default:
365 pszError = N_("Unknown error initializing kernel driver");
366 AssertMsgFailed(("Add error message for rc=%d (%Rrc)\n", rc, rc));
367 }
368 vmR3SetErrorU(pUVM, rc, RT_SRC_POS, pszError, rc);
369 }
370 }
371
372 /* cleanup */
373 vmR3DestroyUVM(pUVM);
374 LogFlow(("VMR3Create: returns %Rrc\n", rc));
375 return rc;
376}
377
378
379/**
380 * Creates the UVM.
381 *
382 * This will not initialize the support library even if vmR3DestroyUVM
383 * will terminate that.
384 *
385 * @returns VBox status code.
386 * @param cCPUs Number of virtual CPUs
387 * @param ppUVM Where to store the UVM pointer.
388 */
389static int vmR3CreateUVM(uint32_t cCPUs, PUVM *ppUVM)
390{
391 uint32_t i;
392
393 /*
394 * Create and initialize the UVM.
395 */
396 PUVM pUVM = (PUVM)RTMemAllocZ(RT_OFFSETOF(UVM, aCpus[cCPUs]));
397 AssertReturn(pUVM, VERR_NO_MEMORY);
398 pUVM->u32Magic = UVM_MAGIC;
399
400 AssertCompile(sizeof(pUVM->vm.s) <= sizeof(pUVM->vm.padding));
401 AssertRelease(sizeof(pUVM->vm.s) <= sizeof(pUVM->vm.padding));
402
403 pUVM->vm.s.ppAtResetNext = &pUVM->vm.s.pAtReset;
404 pUVM->vm.s.ppAtStateNext = &pUVM->vm.s.pAtState;
405 pUVM->vm.s.ppAtErrorNext = &pUVM->vm.s.pAtError;
406 pUVM->vm.s.ppAtRuntimeErrorNext = &pUVM->vm.s.pAtRuntimeError;
407 pUVM->vm.s.enmHaltMethod = VMHALTMETHOD_BOOTSTRAP;
408
409 /* Initialize the VMCPU array in the UVM. */
410 for (i = 0; i < cCPUs; i++)
411 {
412 pUVM->aCpus[i].pUVM = pUVM;
413 pUVM->aCpus[i].idCpu = i;
414 }
415
416 /* Allocate a TLS entry to store the VMINTUSERPERVMCPU pointer. */
417 int rc = RTTlsAllocEx(&pUVM->vm.s.idxTLS, NULL);
418 AssertRC(rc);
419 if (RT_SUCCESS(rc))
420 {
421 rc = RTSemEventCreate(&pUVM->vm.s.EventSemWait);
422 if (RT_SUCCESS(rc))
423 {
424 /*
425 * Init fundamental (sub-)components - STAM, MMR3Heap and PDMLdr.
426 */
427 rc = STAMR3InitUVM(pUVM);
428 if (RT_SUCCESS(rc))
429 {
430 rc = MMR3InitUVM(pUVM);
431 if (RT_SUCCESS(rc))
432 {
433 rc = PDMR3InitUVM(pUVM);
434 if (RT_SUCCESS(rc))
435 {
436 /*
437 * Start the emulation threads for all VMCPUs.
438 */
439 for (i = 0; i < cCPUs; i++)
440 {
441 rc = RTThreadCreate(&pUVM->aCpus[i].vm.s.ThreadEMT, vmR3EmulationThread, &pUVM->aCpus[i], _1M,
442 RTTHREADTYPE_EMULATION, RTTHREADFLAGS_WAITABLE, "EMT");
443 if (RT_FAILURE(rc))
444 break;
445
446 pUVM->aCpus[i].vm.s.NativeThreadEMT = RTThreadGetNative(pUVM->aCpus[i].vm.s.ThreadEMT);
447 }
448
449 if (RT_SUCCESS(rc))
450 {
451 *ppUVM = pUVM;
452 return VINF_SUCCESS;
453 }
454
455 /* bail out. */
456 while (i-- > 0)
457 {
458 /** @todo rainy day: terminate the EMTs. */
459 }
460 PDMR3TermUVM(pUVM);
461 }
462 MMR3TermUVM(pUVM);
463 }
464 STAMR3TermUVM(pUVM);
465 }
466 RTSemEventDestroy(pUVM->vm.s.EventSemWait);
467 }
468 RTTlsFree(pUVM->vm.s.idxTLS);
469 }
470 RTMemFree(pUVM);
471 return rc;
472}
473
474
475/**
476 * Creates and initializes the VM.
477 *
478 * @thread EMT
479 */
480static int vmR3CreateU(PUVM pUVM, uint32_t cCPUs, PFNCFGMCONSTRUCTOR pfnCFGMConstructor, void *pvUserCFGM)
481{
482 int rc = VINF_SUCCESS;
483
484 /*
485 * Load the VMMR0.r0 module so that we can call GVMMR0CreateVM.
486 */
487 rc = PDMR3LdrLoadVMMR0U(pUVM);
488 if (RT_FAILURE(rc))
489 {
490 /** @todo we need a cleaner solution for this (VERR_VMX_IN_VMX_ROOT_MODE).
491 * bird: what about moving the message down here? Main picks the first message, right? */
492 if (rc == VERR_VMX_IN_VMX_ROOT_MODE)
493 return rc; /* proper error message set later on */
494 return vmR3SetErrorU(pUVM, rc, RT_SRC_POS, N_("Failed to load VMMR0.r0"));
495 }
496
497 /*
498 * Request GVMM to create a new VM for us.
499 */
500 GVMMCREATEVMREQ CreateVMReq;
501 CreateVMReq.Hdr.u32Magic = SUPVMMR0REQHDR_MAGIC;
502 CreateVMReq.Hdr.cbReq = sizeof(CreateVMReq);
503 CreateVMReq.pSession = pUVM->vm.s.pSession;
504 CreateVMReq.pVMR0 = NIL_RTR0PTR;
505 CreateVMReq.pVMR3 = NULL;
506 CreateVMReq.cCPUs = cCPUs;
507 rc = SUPCallVMMR0Ex(NIL_RTR0PTR, VMMR0_DO_GVMM_CREATE_VM, 0, &CreateVMReq.Hdr);
508 if (RT_SUCCESS(rc))
509 {
510 PVM pVM = pUVM->pVM = CreateVMReq.pVMR3;
511 AssertRelease(VALID_PTR(pVM));
512 AssertRelease(pVM->pVMR0 == CreateVMReq.pVMR0);
513 AssertRelease(pVM->pSession == pUVM->vm.s.pSession);
514 AssertRelease(pVM->cCPUs == cCPUs);
515 AssertRelease(pVM->offVMCPU == RT_UOFFSETOF(VM, aCpus));
516
517 Log(("VMR3Create: Created pUVM=%p pVM=%p pVMR0=%p hSelf=%#x cCPUs=%RU32\n",
518 pUVM, pVM, pVM->pVMR0, pVM->hSelf, pVM->cCPUs));
519
520 /*
521 * Initialize the VM structure and our internal data (VMINT).
522 */
523 pVM->pUVM = pUVM;
524
525 for (uint32_t i = 0; i < pVM->cCPUs; i++)
526 {
527 pVM->aCpus[i].hNativeThread = pUVM->aCpus[i].vm.s.NativeThreadEMT;
528 Assert(pVM->aCpus[i].hNativeThread != NIL_RTNATIVETHREAD);
529 }
530
531
532 /*
533 * Init the configuration.
534 */
535 rc = CFGMR3Init(pVM, pfnCFGMConstructor, pvUserCFGM);
536 if (RT_SUCCESS(rc))
537 {
538 rc = CFGMR3QueryBoolDef(CFGMR3GetRoot(pVM), "HwVirtExtForced", &pVM->fHwVirtExtForced, false);
539 if (RT_SUCCESS(rc) && pVM->fHwVirtExtForced)
540 pVM->fHWACCMEnabled = true;
541
542 /*
543 * If executing in fake suplib mode disable RR3 and RR0 in the config.
544 */
545 const char *psz = RTEnvGet("VBOX_SUPLIB_FAKE");
546 if (psz && !strcmp(psz, "fake"))
547 {
548 CFGMR3RemoveValue(CFGMR3GetRoot(pVM), "RawR3Enabled");
549 CFGMR3InsertInteger(CFGMR3GetRoot(pVM), "RawR3Enabled", 0);
550 CFGMR3RemoveValue(CFGMR3GetRoot(pVM), "RawR0Enabled");
551 CFGMR3InsertInteger(CFGMR3GetRoot(pVM), "RawR0Enabled", 0);
552 }
553
554 /*
555 * Make sure the CPU count in the config data matches.
556 */
557 if (RT_SUCCESS(rc))
558 {
559 uint32_t cCPUsCfg;
560 rc = CFGMR3QueryU32Def(CFGMR3GetRoot(pVM), "NumCPUs", &cCPUsCfg, 1);
561 AssertLogRelMsgRC(rc, ("Configuration error: Querying \"NumCPUs\" as integer failed, rc=%Rrc\n", rc));
562 if (RT_SUCCESS(rc) && cCPUsCfg != cCPUs)
563 {
564 AssertLogRelMsgFailed(("Configuration error: \"NumCPUs\"=%RU32 and VMR3CreateVM::cCPUs=%RU32 does not match!\n",
565 cCPUsCfg, cCPUs));
566 rc = VERR_INVALID_PARAMETER;
567 }
568 }
569 if (RT_SUCCESS(rc))
570 {
571 /*
572 * Init the ring-3 components and ring-3 per cpu data, finishing it off
573 * by a relocation round (intermediate context finalization will do this).
574 */
575 rc = vmR3InitRing3(pVM, pUVM);
576 if (RT_SUCCESS(rc))
577 {
578 rc = vmR3InitVMCpu(pVM);
579 if (RT_SUCCESS(rc))
580 rc = PGMR3FinalizeMappings(pVM);
581 if (RT_SUCCESS(rc))
582 {
583
584 LogFlow(("Ring-3 init succeeded\n"));
585
586 /*
587 * Init the Ring-0 components.
588 */
589 rc = vmR3InitRing0(pVM);
590 if (RT_SUCCESS(rc))
591 {
592 /* Relocate again, because some switcher fixups depends on R0 init results. */
593 VMR3Relocate(pVM, 0);
594
595#ifdef VBOX_WITH_DEBUGGER
596 /*
597 * Init the tcp debugger console if we're building
598 * with debugger support.
599 */
600 void *pvUser = NULL;
601 rc = DBGCTcpCreate(pVM, &pvUser);
602 if ( RT_SUCCESS(rc)
603 || rc == VERR_NET_ADDRESS_IN_USE)
604 {
605 pUVM->vm.s.pvDBGC = pvUser;
606#endif
607 /*
608 * Init the Guest Context components.
609 */
610 rc = vmR3InitGC(pVM);
611 if (RT_SUCCESS(rc))
612 {
613 /*
614 * Now we can safely set the VM halt method to default.
615 */
616 rc = vmR3SetHaltMethodU(pUVM, VMHALTMETHOD_DEFAULT);
617 if (RT_SUCCESS(rc))
618 {
619 /*
620 * Set the state and link into the global list.
621 */
622 vmR3SetState(pVM, VMSTATE_CREATED);
623 pUVM->pNext = g_pUVMsHead;
624 g_pUVMsHead = pUVM;
625 return VINF_SUCCESS;
626 }
627 }
628#ifdef VBOX_WITH_DEBUGGER
629 DBGCTcpTerminate(pVM, pUVM->vm.s.pvDBGC);
630 pUVM->vm.s.pvDBGC = NULL;
631 }
632#endif
633 //..
634 }
635 }
636 vmR3Destroy(pVM);
637 }
638 }
639 //..
640
641 /* Clean CFGM. */
642 int rc2 = CFGMR3Term(pVM);
643 AssertRC(rc2);
644 }
645
646 /* Tell GVMM that it can destroy the VM now. */
647 int rc2 = SUPCallVMMR0Ex(CreateVMReq.pVMR0, VMMR0_DO_GVMM_DESTROY_VM, 0, NULL);
648 AssertRC(rc2);
649 pUVM->pVM = NULL;
650 }
651 else
652 vmR3SetErrorU(pUVM, rc, RT_SRC_POS, N_("VM creation failed (GVMM)"));
653
654 LogFlow(("vmR3Create: returns %Rrc\n", rc));
655 return rc;
656}
657
658
659/**
660 * Initializes all R3 components of the VM
661 */
662static int vmR3InitRing3(PVM pVM, PUVM pUVM)
663{
664 int rc;
665
666 /*
667 * Init all R3 components, the order here might be important.
668 */
669 rc = MMR3Init(pVM);
670 if (RT_SUCCESS(rc))
671 {
672 STAM_REG(pVM, &pVM->StatTotalInGC, STAMTYPE_PROFILE_ADV, "/PROF/VM/InGC", STAMUNIT_TICKS_PER_CALL, "Profiling the total time spent in GC.");
673 STAM_REG(pVM, &pVM->StatSwitcherToGC, STAMTYPE_PROFILE_ADV, "/PROF/VM/SwitchToGC", STAMUNIT_TICKS_PER_CALL, "Profiling switching to GC.");
674 STAM_REG(pVM, &pVM->StatSwitcherToHC, STAMTYPE_PROFILE_ADV, "/PROF/VM/SwitchToHC", STAMUNIT_TICKS_PER_CALL, "Profiling switching to HC.");
675 STAM_REG(pVM, &pVM->StatSwitcherSaveRegs, STAMTYPE_PROFILE_ADV, "/VM/Switcher/ToGC/SaveRegs", STAMUNIT_TICKS_PER_CALL,"Profiling switching to GC.");
676 STAM_REG(pVM, &pVM->StatSwitcherSysEnter, STAMTYPE_PROFILE_ADV, "/VM/Switcher/ToGC/SysEnter", STAMUNIT_TICKS_PER_CALL,"Profiling switching to GC.");
677 STAM_REG(pVM, &pVM->StatSwitcherDebug, STAMTYPE_PROFILE_ADV, "/VM/Switcher/ToGC/Debug", STAMUNIT_TICKS_PER_CALL,"Profiling switching to GC.");
678 STAM_REG(pVM, &pVM->StatSwitcherCR0, STAMTYPE_PROFILE_ADV, "/VM/Switcher/ToGC/CR0", STAMUNIT_TICKS_PER_CALL, "Profiling switching to GC.");
679 STAM_REG(pVM, &pVM->StatSwitcherCR4, STAMTYPE_PROFILE_ADV, "/VM/Switcher/ToGC/CR4", STAMUNIT_TICKS_PER_CALL, "Profiling switching to GC.");
680 STAM_REG(pVM, &pVM->StatSwitcherLgdt, STAMTYPE_PROFILE_ADV, "/VM/Switcher/ToGC/Lgdt", STAMUNIT_TICKS_PER_CALL, "Profiling switching to GC.");
681 STAM_REG(pVM, &pVM->StatSwitcherLidt, STAMTYPE_PROFILE_ADV, "/VM/Switcher/ToGC/Lidt", STAMUNIT_TICKS_PER_CALL, "Profiling switching to GC.");
682 STAM_REG(pVM, &pVM->StatSwitcherLldt, STAMTYPE_PROFILE_ADV, "/VM/Switcher/ToGC/Lldt", STAMUNIT_TICKS_PER_CALL, "Profiling switching to GC.");
683 STAM_REG(pVM, &pVM->StatSwitcherTSS, STAMTYPE_PROFILE_ADV, "/VM/Switcher/ToGC/TSS", STAMUNIT_TICKS_PER_CALL, "Profiling switching to GC.");
684 STAM_REG(pVM, &pVM->StatSwitcherJmpCR3, STAMTYPE_PROFILE_ADV, "/VM/Switcher/ToGC/JmpCR3", STAMUNIT_TICKS_PER_CALL,"Profiling switching to GC.");
685 STAM_REG(pVM, &pVM->StatSwitcherRstrRegs, STAMTYPE_PROFILE_ADV, "/VM/Switcher/ToGC/RstrRegs", STAMUNIT_TICKS_PER_CALL,"Profiling switching to GC.");
686
687 STAM_REL_REG(pVM, &pUVM->vm.s.StatHaltYield, STAMTYPE_PROFILE, "/PROF/VM/Halt/Yield", STAMUNIT_TICKS_PER_CALL, "Profiling halted state yielding.");
688 STAM_REL_REG(pVM, &pUVM->vm.s.StatHaltBlock, STAMTYPE_PROFILE, "/PROF/VM/Halt/Block", STAMUNIT_TICKS_PER_CALL, "Profiling halted state blocking.");
689 STAM_REL_REG(pVM, &pUVM->vm.s.StatHaltTimers,STAMTYPE_PROFILE, "/PROF/VM/Halt/Timers", STAMUNIT_TICKS_PER_CALL, "Profiling halted state timer tasks.");
690
691 STAM_REG(pVM, &pUVM->vm.s.StatReqAllocNew, STAMTYPE_COUNTER, "/VM/Req/AllocNew", STAMUNIT_OCCURENCES, "Number of VMR3ReqAlloc returning a new packet.");
692 STAM_REG(pVM, &pUVM->vm.s.StatReqAllocRaces, STAMTYPE_COUNTER, "/VM/Req/AllocRaces", STAMUNIT_OCCURENCES, "Number of VMR3ReqAlloc causing races.");
693 STAM_REG(pVM, &pUVM->vm.s.StatReqAllocRecycled, STAMTYPE_COUNTER, "/VM/Req/AllocRecycled", STAMUNIT_OCCURENCES, "Number of VMR3ReqAlloc returning a recycled packet.");
694 STAM_REG(pVM, &pUVM->vm.s.StatReqFree, STAMTYPE_COUNTER, "/VM/Req/Free", STAMUNIT_OCCURENCES, "Number of VMR3ReqFree calls.");
695 STAM_REG(pVM, &pUVM->vm.s.StatReqFreeOverflow, STAMTYPE_COUNTER, "/VM/Req/FreeOverflow", STAMUNIT_OCCURENCES, "Number of times the request was actually freed.");
696
697 rc = CPUMR3Init(pVM);
698 if (RT_SUCCESS(rc))
699 {
700 rc = HWACCMR3Init(pVM);
701 if (RT_SUCCESS(rc))
702 {
703 rc = PGMR3Init(pVM);
704 if (RT_SUCCESS(rc))
705 {
706 rc = REMR3Init(pVM);
707 if (RT_SUCCESS(rc))
708 {
709 rc = MMR3InitPaging(pVM);
710 if (RT_SUCCESS(rc))
711 rc = TMR3Init(pVM);
712 if (RT_SUCCESS(rc))
713 {
714 rc = VMMR3Init(pVM);
715 if (RT_SUCCESS(rc))
716 {
717 rc = SELMR3Init(pVM);
718 if (RT_SUCCESS(rc))
719 {
720 rc = TRPMR3Init(pVM);
721 if (RT_SUCCESS(rc))
722 {
723 rc = CSAMR3Init(pVM);
724 if (RT_SUCCESS(rc))
725 {
726 rc = PATMR3Init(pVM);
727 if (RT_SUCCESS(rc))
728 {
729#ifdef VBOX_WITH_VMI
730 rc = PARAVR3Init(pVM);
731 if (RT_SUCCESS(rc))
732 {
733#endif
734 rc = IOMR3Init(pVM);
735 if (RT_SUCCESS(rc))
736 {
737 rc = EMR3Init(pVM);
738 if (RT_SUCCESS(rc))
739 {
740 rc = DBGFR3Init(pVM);
741 if (RT_SUCCESS(rc))
742 {
743 rc = PDMR3Init(pVM);
744 if (RT_SUCCESS(rc))
745 {
746 rc = PGMR3InitDynMap(pVM);
747 if (RT_SUCCESS(rc))
748 rc = MMR3HyperInitFinalize(pVM);
749 if (RT_SUCCESS(rc))
750 rc = PATMR3InitFinalize(pVM);
751 if (RT_SUCCESS(rc))
752 rc = PGMR3InitFinalize(pVM);
753 if (RT_SUCCESS(rc))
754 rc = SELMR3InitFinalize(pVM);
755 if (RT_SUCCESS(rc))
756 rc = TMR3InitFinalize(pVM);
757 if (RT_SUCCESS(rc))
758 rc = VMMR3InitFinalize(pVM);
759 if (RT_SUCCESS(rc))
760 rc = REMR3InitFinalize(pVM);
761 if (RT_SUCCESS(rc))
762 rc = vmR3InitDoCompleted(pVM, VMINITCOMPLETED_RING3);
763 if (RT_SUCCESS(rc))
764 {
765 LogFlow(("vmR3InitRing3: returns %Rrc\n", VINF_SUCCESS));
766 return VINF_SUCCESS;
767 }
768 int rc2 = PDMR3Term(pVM);
769 AssertRC(rc2);
770 }
771 int rc2 = DBGFR3Term(pVM);
772 AssertRC(rc2);
773 }
774 int rc2 = EMR3Term(pVM);
775 AssertRC(rc2);
776 }
777 int rc2 = IOMR3Term(pVM);
778 AssertRC(rc2);
779 }
780#ifdef VBOX_WITH_VMI
781 int rc2 = PARAVR3Term(pVM);
782 AssertRC(rc2);
783 }
784#endif
785 int rc2 = PATMR3Term(pVM);
786 AssertRC(rc2);
787 }
788 int rc2 = CSAMR3Term(pVM);
789 AssertRC(rc2);
790 }
791 int rc2 = TRPMR3Term(pVM);
792 AssertRC(rc2);
793 }
794 int rc2 = SELMR3Term(pVM);
795 AssertRC(rc2);
796 }
797 int rc2 = VMMR3Term(pVM);
798 AssertRC(rc2);
799 }
800 int rc2 = TMR3Term(pVM);
801 AssertRC(rc2);
802 }
803 int rc2 = REMR3Term(pVM);
804 AssertRC(rc2);
805 }
806 int rc2 = PGMR3Term(pVM);
807 AssertRC(rc2);
808 }
809 int rc2 = HWACCMR3Term(pVM);
810 AssertRC(rc2);
811 }
812 //int rc2 = CPUMR3Term(pVM);
813 //AssertRC(rc2);
814 }
815 /* MMR3Term is not called here because it'll kill the heap. */
816 }
817
818 LogFlow(("vmR3InitRing3: returns %Rrc\n", rc));
819 return rc;
820}
821
822
823/**
824 * Initializes all VM CPU components of the VM
825 */
826static int vmR3InitVMCpu(PVM pVM)
827{
828 int rc = VINF_SUCCESS;
829 int rc2;
830
831 rc = CPUMR3InitCPU(pVM);
832 if (RT_SUCCESS(rc))
833 {
834 rc = HWACCMR3InitCPU(pVM);
835 if (RT_SUCCESS(rc))
836 {
837 rc = PGMR3InitCPU(pVM);
838 if (RT_SUCCESS(rc))
839 {
840 rc = TMR3InitCPU(pVM);
841 if (RT_SUCCESS(rc))
842 {
843 rc = VMMR3InitCPU(pVM);
844 if (RT_SUCCESS(rc))
845 {
846 rc = EMR3InitCPU(pVM);
847 if (RT_SUCCESS(rc))
848 {
849 LogFlow(("vmR3InitVMCpu: returns %Rrc\n", VINF_SUCCESS));
850 return VINF_SUCCESS;
851 }
852
853 rc2 = VMMR3TermCPU(pVM);
854 AssertRC(rc2);
855 }
856 rc2 = TMR3TermCPU(pVM);
857 AssertRC(rc2);
858 }
859 rc2 = PGMR3TermCPU(pVM);
860 AssertRC(rc2);
861 }
862 rc2 = HWACCMR3TermCPU(pVM);
863 AssertRC(rc2);
864 }
865 rc2 = CPUMR3TermCPU(pVM);
866 AssertRC(rc2);
867 }
868 LogFlow(("vmR3InitVMCpu: returns %Rrc\n", rc));
869 return rc;
870}
871
872
873/**
874 * Initializes all R0 components of the VM
875 */
876static int vmR3InitRing0(PVM pVM)
877{
878 LogFlow(("vmR3InitRing0:\n"));
879
880 /*
881 * Check for FAKE suplib mode.
882 */
883 int rc = VINF_SUCCESS;
884 const char *psz = RTEnvGet("VBOX_SUPLIB_FAKE");
885 if (!psz || strcmp(psz, "fake"))
886 {
887 /*
888 * Call the VMMR0 component and let it do the init.
889 */
890 rc = VMMR3InitR0(pVM);
891 }
892 else
893 Log(("vmR3InitRing0: skipping because of VBOX_SUPLIB_FAKE=fake\n"));
894
895 /*
896 * Do notifications and return.
897 */
898 if (RT_SUCCESS(rc))
899 rc = vmR3InitDoCompleted(pVM, VMINITCOMPLETED_RING0);
900
901 /** todo: move this to the VMINITCOMPLETED_RING0 notification handler once implemented */
902 if (RT_SUCCESS(rc))
903 rc = HWACCMR3InitFinalizeR0(pVM);
904
905 LogFlow(("vmR3InitRing0: returns %Rrc\n", rc));
906 return rc;
907}
908
909
910/**
911 * Initializes all GC components of the VM
912 */
913static int vmR3InitGC(PVM pVM)
914{
915 LogFlow(("vmR3InitGC:\n"));
916
917 /*
918 * Check for FAKE suplib mode.
919 */
920 int rc = VINF_SUCCESS;
921 const char *psz = RTEnvGet("VBOX_SUPLIB_FAKE");
922 if (!psz || strcmp(psz, "fake"))
923 {
924 /*
925 * Call the VMMR0 component and let it do the init.
926 */
927 rc = VMMR3InitRC(pVM);
928 }
929 else
930 Log(("vmR3InitGC: skipping because of VBOX_SUPLIB_FAKE=fake\n"));
931
932 /*
933 * Do notifications and return.
934 */
935 if (RT_SUCCESS(rc))
936 rc = vmR3InitDoCompleted(pVM, VMINITCOMPLETED_GC);
937 LogFlow(("vmR3InitGC: returns %Rrc\n", rc));
938 return rc;
939}
940
941
942/**
943 * Do init completed notifications.
944 * This notifications can fail.
945 *
946 * @param pVM The VM handle.
947 * @param enmWhat What's completed.
948 */
949static int vmR3InitDoCompleted(PVM pVM, VMINITCOMPLETED enmWhat)
950{
951
952 return VINF_SUCCESS;
953}
954
955
956/**
957 * Calls the relocation functions for all VMM components so they can update
958 * any GC pointers. When this function is called all the basic VM members
959 * have been updated and the actual memory relocation have been done
960 * by the PGM/MM.
961 *
962 * This is used both on init and on runtime relocations.
963 *
964 * @param pVM VM handle.
965 * @param offDelta Relocation delta relative to old location.
966 */
967VMMR3DECL(void) VMR3Relocate(PVM pVM, RTGCINTPTR offDelta)
968{
969 LogFlow(("VMR3Relocate: offDelta=%RGv\n", offDelta));
970
971 /*
972 * The order here is very important!
973 */
974 PGMR3Relocate(pVM, offDelta);
975 PDMR3LdrRelocateU(pVM->pUVM, offDelta);
976 PGMR3Relocate(pVM, 0); /* Repeat after PDM relocation. */
977 CPUMR3Relocate(pVM);
978 HWACCMR3Relocate(pVM);
979 SELMR3Relocate(pVM);
980 VMMR3Relocate(pVM, offDelta);
981 SELMR3Relocate(pVM); /* !hack! fix stack! */
982 TRPMR3Relocate(pVM, offDelta);
983 PATMR3Relocate(pVM);
984 CSAMR3Relocate(pVM, offDelta);
985 IOMR3Relocate(pVM, offDelta);
986 EMR3Relocate(pVM);
987 TMR3Relocate(pVM, offDelta);
988 DBGFR3Relocate(pVM, offDelta);
989 PDMR3Relocate(pVM, offDelta);
990}
991
992
993/**
994 * Power on the virtual machine.
995 *
996 * @returns 0 on success.
997 * @returns VBox error code on failure.
998 * @param pVM VM to power on.
999 * @thread Any thread.
1000 * @vmstate Created
1001 * @vmstateto Running
1002 */
1003VMMR3DECL(int) VMR3PowerOn(PVM pVM)
1004{
1005 LogFlow(("VMR3PowerOn: pVM=%p\n", pVM));
1006
1007 /*
1008 * Validate input.
1009 */
1010 if (!pVM)
1011 {
1012 AssertMsgFailed(("Invalid VM pointer\n"));
1013 return VERR_INVALID_PARAMETER;
1014 }
1015
1016 /*
1017 * Request the operation in EMT.
1018 */
1019 PVMREQ pReq;
1020 int rc = VMR3ReqCall(pVM, VMREQDEST_ANY, &pReq, RT_INDEFINITE_WAIT, (PFNRT)vmR3PowerOn, 1, pVM);
1021 if (RT_SUCCESS(rc))
1022 {
1023 rc = pReq->iStatus;
1024 VMR3ReqFree(pReq);
1025 }
1026
1027 LogFlow(("VMR3PowerOn: returns %Rrc\n", rc));
1028 return rc;
1029}
1030
1031
1032/**
1033 * Power on the virtual machine.
1034 *
1035 * @returns 0 on success.
1036 * @returns VBox error code on failure.
1037 * @param pVM VM to power on.
1038 * @thread EMT
1039 */
1040static DECLCALLBACK(int) vmR3PowerOn(PVM pVM)
1041{
1042 LogFlow(("vmR3PowerOn: pVM=%p\n", pVM));
1043
1044 /*
1045 * Validate input.
1046 */
1047 if (pVM->enmVMState != VMSTATE_CREATED)
1048 {
1049 AssertMsgFailed(("Invalid VM state %d\n", pVM->enmVMState));
1050 return VERR_VM_INVALID_VM_STATE;
1051 }
1052
1053 /*
1054 * Change the state, notify the components and resume the execution.
1055 */
1056 vmR3SetState(pVM, VMSTATE_RUNNING);
1057 PDMR3PowerOn(pVM);
1058
1059 return VINF_SUCCESS;
1060}
1061
1062
1063/**
1064 * Suspends a running VM.
1065 *
1066 * @returns 0 on success.
1067 * @returns VBox error code on failure.
1068 * @param pVM VM to suspend.
1069 * @thread Any thread.
1070 * @vmstate Running
1071 * @vmstateto Suspended
1072 */
1073VMMR3DECL(int) VMR3Suspend(PVM pVM)
1074{
1075 LogFlow(("VMR3Suspend: pVM=%p\n", pVM));
1076
1077 /*
1078 * Validate input.
1079 */
1080 if (!pVM)
1081 {
1082 AssertMsgFailed(("Invalid VM pointer\n"));
1083 return VERR_INVALID_PARAMETER;
1084 }
1085
1086 /*
1087 * Request the operation in EMT.
1088 */
1089 PVMREQ pReq;
1090 int rc = VMR3ReqCall(pVM, VMREQDEST_ANY, &pReq, RT_INDEFINITE_WAIT, (PFNRT)vmR3Suspend, 1, pVM);
1091 if (RT_SUCCESS(rc))
1092 {
1093 rc = pReq->iStatus;
1094 VMR3ReqFree(pReq);
1095 }
1096
1097 LogFlow(("VMR3Suspend: returns %Rrc\n", rc));
1098 return rc;
1099}
1100
1101
1102/**
1103 * Suspends a running VM and prevent state saving until the VM is resumed or stopped.
1104 *
1105 * @returns 0 on success.
1106 * @returns VBox error code on failure.
1107 * @param pVM VM to suspend.
1108 * @thread Any thread.
1109 * @vmstate Running
1110 * @vmstateto Suspended
1111 */
1112VMMR3DECL(int) VMR3SuspendNoSave(PVM pVM)
1113{
1114 pVM->vm.s.fPreventSaveState = true;
1115 return VMR3Suspend(pVM);
1116}
1117
1118
1119/**
1120 * Suspends a running VM.
1121 *
1122 * @returns 0 on success.
1123 * @returns VBox error code on failure.
1124 * @param pVM VM to suspend.
1125 * @thread EMT
1126 */
1127static DECLCALLBACK(int) vmR3Suspend(PVM pVM)
1128{
1129 LogFlow(("vmR3Suspend: pVM=%p\n", pVM));
1130
1131 /*
1132 * Validate input.
1133 */
1134 if (pVM->enmVMState != VMSTATE_RUNNING)
1135 {
1136 AssertMsgFailed(("Invalid VM state %d\n", pVM->enmVMState));
1137 return VERR_VM_INVALID_VM_STATE;
1138 }
1139
1140 /*
1141 * Change the state, notify the components and resume the execution.
1142 */
1143 vmR3SetState(pVM, VMSTATE_SUSPENDED);
1144 PDMR3Suspend(pVM);
1145
1146 return VINF_EM_SUSPEND;
1147}
1148
1149
1150/**
1151 * Resume VM execution.
1152 *
1153 * @returns 0 on success.
1154 * @returns VBox error code on failure.
1155 * @param pVM The VM to resume.
1156 * @thread Any thread.
1157 * @vmstate Suspended
1158 * @vmstateto Running
1159 */
1160VMMR3DECL(int) VMR3Resume(PVM pVM)
1161{
1162 LogFlow(("VMR3Resume: pVM=%p\n", pVM));
1163
1164 /*
1165 * Validate input.
1166 */
1167 if (!pVM)
1168 {
1169 AssertMsgFailed(("Invalid VM pointer\n"));
1170 return VERR_INVALID_PARAMETER;
1171 }
1172
1173 /*
1174 * Request the operation in EMT.
1175 */
1176 PVMREQ pReq;
1177 int rc = VMR3ReqCall(pVM, VMREQDEST_ANY, &pReq, RT_INDEFINITE_WAIT, (PFNRT)vmR3Resume, 1, pVM);
1178 if (RT_SUCCESS(rc))
1179 {
1180 rc = pReq->iStatus;
1181 VMR3ReqFree(pReq);
1182 }
1183
1184 LogFlow(("VMR3Resume: returns %Rrc\n", rc));
1185 return rc;
1186}
1187
1188
1189/**
1190 * Resume VM execution.
1191 *
1192 * @returns 0 on success.
1193 * @returns VBox error code on failure.
1194 * @param pVM The VM to resume.
1195 * @thread EMT
1196 */
1197static DECLCALLBACK(int) vmR3Resume(PVM pVM)
1198{
1199 LogFlow(("vmR3Resume: pVM=%p\n", pVM));
1200
1201 /*
1202 * Validate input.
1203 */
1204 if (pVM->enmVMState != VMSTATE_SUSPENDED)
1205 {
1206 AssertMsgFailed(("Invalid VM state %d\n", pVM->enmVMState));
1207 return VERR_VM_INVALID_VM_STATE;
1208 }
1209
1210 /*
1211 * Change the state, notify the components and resume the execution.
1212 */
1213 pVM->vm.s.fPreventSaveState = false;
1214 vmR3SetState(pVM, VMSTATE_RUNNING);
1215 PDMR3Resume(pVM);
1216
1217 return VINF_EM_RESUME;
1218}
1219
1220
1221/**
1222 * Save current VM state.
1223 *
1224 * To save and terminate the VM, the VM must be suspended before the call.
1225 *
1226 * @returns 0 on success.
1227 * @returns VBox error code on failure.
1228 * @param pVM VM which state should be saved.
1229 * @param pszFilename Name of the save state file.
1230 * @param pfnProgress Progress callback. Optional.
1231 * @param pvUser User argument for the progress callback.
1232 * @thread Any thread.
1233 * @vmstate Suspended
1234 * @vmstateto Unchanged state.
1235 */
1236VMMR3DECL(int) VMR3Save(PVM pVM, const char *pszFilename, PFNVMPROGRESS pfnProgress, void *pvUser)
1237{
1238 LogFlow(("VMR3Save: pVM=%p pszFilename=%p:{%s} pfnProgress=%p pvUser=%p\n", pVM, pszFilename, pszFilename, pfnProgress, pvUser));
1239
1240 /*
1241 * Validate input.
1242 */
1243 if (!pVM)
1244 {
1245 AssertMsgFailed(("Invalid VM pointer\n"));
1246 return VERR_INVALID_PARAMETER;
1247 }
1248 if (!pszFilename)
1249 {
1250 AssertMsgFailed(("Must specify a filename to save the state to, wise guy!\n"));
1251 return VERR_INVALID_PARAMETER;
1252 }
1253
1254 /*
1255 * Request the operation in EMT.
1256 */
1257 PVMREQ pReq;
1258 int rc = VMR3ReqCall(pVM, VMREQDEST_ANY, &pReq, RT_INDEFINITE_WAIT, (PFNRT)vmR3Save, 4, pVM, pszFilename, pfnProgress, pvUser);
1259 if (RT_SUCCESS(rc))
1260 {
1261 rc = pReq->iStatus;
1262 VMR3ReqFree(pReq);
1263 }
1264
1265 LogFlow(("VMR3Save: returns %Rrc\n", rc));
1266 return rc;
1267}
1268
1269
1270/**
1271 * Save current VM state.
1272 *
1273 * To save and terminate the VM, the VM must be suspended before the call.
1274 *
1275 * @returns 0 on success.
1276 * @returns VBox error code on failure.
1277 * @param pVM VM which state should be saved.
1278 * @param pszFilename Name of the save state file.
1279 * @param pfnProgress Progress callback. Optional.
1280 * @param pvUser User argument for the progress callback.
1281 * @thread EMT
1282 */
1283static DECLCALLBACK(int) vmR3Save(PVM pVM, const char *pszFilename, PFNVMPROGRESS pfnProgress, void *pvUser)
1284{
1285 LogFlow(("vmR3Save: pVM=%p pszFilename=%p:{%s} pfnProgress=%p pvUser=%p\n", pVM, pszFilename, pszFilename, pfnProgress, pvUser));
1286
1287 /*
1288 * Validate input.
1289 */
1290 if (pVM->enmVMState != VMSTATE_SUSPENDED)
1291 {
1292 AssertMsgFailed(("Invalid VM state %d\n", pVM->enmVMState));
1293 return VERR_VM_INVALID_VM_STATE;
1294 }
1295
1296 /* If we are in an inconsistent state, then we don't allow state saving. */
1297 if (pVM->vm.s.fPreventSaveState)
1298 {
1299 LogRel(("VMM: vmR3Save: saving the VM state is not allowed at this moment\n"));
1300 return VERR_VM_SAVE_STATE_NOT_ALLOWED;
1301 }
1302
1303 /*
1304 * Change the state and perform the save.
1305 */
1306 /** @todo implement progress support in SSM */
1307 vmR3SetState(pVM, VMSTATE_SAVING);
1308 int rc = SSMR3Save(pVM, pszFilename, SSMAFTER_CONTINUE, pfnProgress, pvUser);
1309 vmR3SetState(pVM, VMSTATE_SUSPENDED);
1310
1311 return rc;
1312}
1313
1314
1315/**
1316 * Loads a new VM state.
1317 *
1318 * To restore a saved state on VM startup, call this function and then
1319 * resume the VM instead of powering it on.
1320 *
1321 * @returns 0 on success.
1322 * @returns VBox error code on failure.
1323 * @param pVM VM which state should be saved.
1324 * @param pszFilename Name of the save state file.
1325 * @param pfnProgress Progress callback. Optional.
1326 * @param pvUser User argument for the progress callback.
1327 * @thread Any thread.
1328 * @vmstate Created, Suspended
1329 * @vmstateto Suspended
1330 */
1331VMMR3DECL(int) VMR3Load(PVM pVM, const char *pszFilename, PFNVMPROGRESS pfnProgress, void *pvUser)
1332{
1333 LogFlow(("VMR3Load: pVM=%p pszFilename=%p:{%s} pfnProgress=%p pvUser=%p\n", pVM, pszFilename, pszFilename, pfnProgress, pvUser));
1334
1335 /*
1336 * Validate input.
1337 */
1338 if (!pVM)
1339 {
1340 AssertMsgFailed(("Invalid VM pointer\n"));
1341 return VERR_INVALID_PARAMETER;
1342 }
1343 if (!pszFilename)
1344 {
1345 AssertMsgFailed(("Must specify a filename to load the state from, wise guy!\n"));
1346 return VERR_INVALID_PARAMETER;
1347 }
1348
1349 /*
1350 * Request the operation in EMT.
1351 */
1352 PVMREQ pReq;
1353 int rc = VMR3ReqCall(pVM, VMREQDEST_ANY, &pReq, RT_INDEFINITE_WAIT, (PFNRT)vmR3Load, 4, pVM, pszFilename, pfnProgress, pvUser);
1354 if (RT_SUCCESS(rc))
1355 {
1356 rc = pReq->iStatus;
1357 VMR3ReqFree(pReq);
1358 }
1359
1360 LogFlow(("VMR3Load: returns %Rrc\n", rc));
1361 return rc;
1362}
1363
1364
1365/**
1366 * Loads a new VM state.
1367 *
1368 * To restore a saved state on VM startup, call this function and then
1369 * resume the VM instead of powering it on.
1370 *
1371 * @returns 0 on success.
1372 * @returns VBox error code on failure.
1373 * @param pVM VM which state should be saved.
1374 * @param pszFilename Name of the save state file.
1375 * @param pfnProgress Progress callback. Optional.
1376 * @param pvUser User argument for the progress callback.
1377 * @thread EMT.
1378 */
1379static DECLCALLBACK(int) vmR3Load(PVM pVM, const char *pszFilename, PFNVMPROGRESS pfnProgress, void *pvUser)
1380{
1381 LogFlow(("vmR3Load: pVM=%p pszFilename=%p:{%s} pfnProgress=%p pvUser=%p\n", pVM, pszFilename, pszFilename, pfnProgress, pvUser));
1382
1383 /*
1384 * Validate input.
1385 */
1386 if ( pVM->enmVMState != VMSTATE_SUSPENDED
1387 && pVM->enmVMState != VMSTATE_CREATED)
1388 {
1389 AssertMsgFailed(("Invalid VM state %d\n", pVM->enmVMState));
1390 return VMSetError(pVM, VERR_VM_INVALID_VM_STATE, RT_SRC_POS, N_("Invalid VM state (%s) for restoring state from '%s'"),
1391 VMR3GetStateName(pVM->enmVMState), pszFilename);
1392 }
1393
1394 /*
1395 * Change the state and perform the load.
1396 */
1397 vmR3SetState(pVM, VMSTATE_LOADING);
1398 int rc = SSMR3Load(pVM, pszFilename, SSMAFTER_RESUME, pfnProgress, pvUser);
1399 if (RT_SUCCESS(rc))
1400 {
1401 /* Not paranoia anymore; the saved guest might use different hypervisor selectors. We must call VMR3Relocate. */
1402 VMR3Relocate(pVM, 0);
1403 vmR3SetState(pVM, VMSTATE_SUSPENDED);
1404 }
1405 else
1406 {
1407 vmR3SetState(pVM, VMSTATE_LOAD_FAILURE);
1408 rc = VMSetError(pVM, rc, RT_SRC_POS, N_("Unable to restore the virtual machine's saved state from '%s'. It may be damaged or from an older version of VirtualBox. Please discard the saved state before starting the virtual machine"), pszFilename);
1409 }
1410
1411 return rc;
1412}
1413
1414
1415/**
1416 * Power Off the VM.
1417 *
1418 * @returns 0 on success.
1419 * @returns VBox error code on failure.
1420 * @param pVM VM which should be destroyed.
1421 * @thread Any thread.
1422 * @vmstate Suspended, Running, Guru Meditation, Load Failure
1423 * @vmstateto Off
1424 */
1425VMMR3DECL(int) VMR3PowerOff(PVM pVM)
1426{
1427 LogFlow(("VMR3PowerOff: pVM=%p\n", pVM));
1428
1429 /*
1430 * Validate input.
1431 */
1432 if (!pVM)
1433 {
1434 AssertMsgFailed(("Invalid VM pointer\n"));
1435 return VERR_INVALID_PARAMETER;
1436 }
1437
1438 /*
1439 * Request the operation in EMT.
1440 */
1441 PVMREQ pReq;
1442 int rc = VMR3ReqCall(pVM, VMREQDEST_ANY, &pReq, RT_INDEFINITE_WAIT, (PFNRT)vmR3PowerOff, 1, pVM);
1443 if (RT_SUCCESS(rc))
1444 {
1445 rc = pReq->iStatus;
1446 VMR3ReqFree(pReq);
1447 }
1448
1449 LogFlow(("VMR3PowerOff: returns %Rrc\n", rc));
1450 return rc;
1451}
1452
1453
1454/**
1455 * Power Off the VM.
1456 *
1457 * @returns 0 on success.
1458 * @returns VBox error code on failure.
1459 * @param pVM VM which should be destroyed.
1460 * @thread EMT.
1461 */
1462static DECLCALLBACK(int) vmR3PowerOff(PVM pVM)
1463{
1464 LogFlow(("vmR3PowerOff: pVM=%p\n", pVM));
1465
1466 /*
1467 * Validate input.
1468 */
1469 if ( pVM->enmVMState != VMSTATE_RUNNING
1470 && pVM->enmVMState != VMSTATE_SUSPENDED
1471 && pVM->enmVMState != VMSTATE_LOAD_FAILURE
1472 && pVM->enmVMState != VMSTATE_GURU_MEDITATION)
1473 {
1474 AssertMsgFailed(("Invalid VM state %d\n", pVM->enmVMState));
1475 return VERR_VM_INVALID_VM_STATE;
1476 }
1477
1478 /*
1479 * For debugging purposes, we will log a summary of the guest state at this point.
1480 */
1481 if (pVM->enmVMState != VMSTATE_GURU_MEDITATION)
1482 {
1483 /** @todo make the state dumping at VMR3PowerOff optional. */
1484 RTLogRelPrintf("****************** Guest state at power off ******************\n");
1485 DBGFR3Info(pVM, "cpumguest", "verbose", DBGFR3InfoLogRelHlp());
1486 RTLogRelPrintf("***\n");
1487 DBGFR3Info(pVM, "mode", NULL, DBGFR3InfoLogRelHlp());
1488 RTLogRelPrintf("***\n");
1489 DBGFR3Info(pVM, "activetimers", NULL, DBGFR3InfoLogRelHlp());
1490 RTLogRelPrintf("***\n");
1491 DBGFR3Info(pVM, "gdt", NULL, DBGFR3InfoLogRelHlp());
1492 /** @todo dump guest call stack. */
1493#if 1 // temporary while debugging #1589
1494 RTLogRelPrintf("***\n");
1495 uint32_t esp = CPUMGetGuestESP(pVM);
1496 if ( CPUMGetGuestSS(pVM) == 0
1497 && esp < _64K)
1498 {
1499 uint8_t abBuf[PAGE_SIZE];
1500 RTLogRelPrintf("***\n"
1501 "ss:sp=0000:%04x ", esp);
1502 uint32_t Start = esp & ~(uint32_t)63;
1503 int rc = PGMPhysSimpleReadGCPhys(pVM, abBuf, Start, 0x100);
1504 if (RT_SUCCESS(rc))
1505 RTLogRelPrintf("0000:%04x TO 0000:%04x:\n"
1506 "%.*Rhxd\n",
1507 Start, Start + 0x100 - 1,
1508 0x100, abBuf);
1509 else
1510 RTLogRelPrintf("rc=%Rrc\n", rc);
1511
1512 /* grub ... */
1513 if (esp < 0x2000 && esp > 0x1fc0)
1514 {
1515 rc = PGMPhysSimpleReadGCPhys(pVM, abBuf, 0x8000, 0x800);
1516 if (RT_SUCCESS(rc))
1517 RTLogRelPrintf("0000:8000 TO 0000:87ff:\n"
1518 "%.*Rhxd\n",
1519 0x800, abBuf);
1520 }
1521 /* microsoft cdrom hang ... */
1522 if (true)
1523 {
1524 rc = PGMPhysSimpleReadGCPhys(pVM, abBuf, 0x8000, 0x200);
1525 if (RT_SUCCESS(rc))
1526 RTLogRelPrintf("2000:0000 TO 2000:01ff:\n"
1527 "%.*Rhxd\n",
1528 0x200, abBuf);
1529 }
1530 }
1531#endif
1532 RTLogRelPrintf("************** End of Guest state at power off ***************\n");
1533 }
1534
1535 /*
1536 * Change the state to OFF and notify the components.
1537 */
1538 vmR3SetState(pVM, VMSTATE_OFF);
1539 PDMR3PowerOff(pVM);
1540
1541 return VINF_EM_OFF;
1542}
1543
1544
1545/**
1546 * Destroys the VM.
1547 * The VM must be powered off (or never really powered on) to call this function.
1548 * The VM handle is destroyed and can no longer be used up successful return.
1549 *
1550 * @returns VBox status code.
1551 * @param pVM VM which should be destroyed.
1552 * @thread Any thread but the emulation thread.
1553 * @vmstate Off, Created
1554 * @vmstateto N/A
1555 */
1556VMMR3DECL(int) VMR3Destroy(PVM pVM)
1557{
1558 LogFlow(("VMR3Destroy: pVM=%p\n", pVM));
1559
1560 /*
1561 * Validate input.
1562 */
1563 if (!pVM)
1564 return VERR_INVALID_PARAMETER;
1565 AssertPtrReturn(pVM, VERR_INVALID_POINTER);
1566 AssertMsgReturn( pVM->enmVMState == VMSTATE_OFF
1567 || pVM->enmVMState == VMSTATE_CREATED,
1568 ("Invalid VM state %d\n", pVM->enmVMState),
1569 VERR_VM_INVALID_VM_STATE);
1570
1571 /*
1572 * Change VM state to destroying and unlink the VM.
1573 */
1574 vmR3SetState(pVM, VMSTATE_DESTROYING);
1575
1576 /** @todo lock this when we start having multiple machines in a process... */
1577 PUVM pUVM = pVM->pUVM; AssertPtr(pUVM);
1578 if (g_pUVMsHead == pUVM)
1579 g_pUVMsHead = pUVM->pNext;
1580 else
1581 {
1582 PUVM pPrev = g_pUVMsHead;
1583 while (pPrev && pPrev->pNext != pUVM)
1584 pPrev = pPrev->pNext;
1585 AssertMsgReturn(pPrev, ("pUVM=%p / pVM=%p is INVALID!\n", pUVM, pVM), VERR_INVALID_PARAMETER);
1586
1587 pPrev->pNext = pUVM->pNext;
1588 }
1589 pUVM->pNext = NULL;
1590
1591 /*
1592 * Notify registered at destruction listeners.
1593 * (That's the debugger console.)
1594 */
1595 vmR3AtDtor(pVM);
1596
1597 /*
1598 * If we are the EMT we'll delay the cleanup till later.
1599 */
1600 if (VM_IS_EMT(pVM))
1601 {
1602 pUVM->vm.s.fEMTDoesTheCleanup = true;
1603 pUVM->vm.s.fTerminateEMT = true;
1604 VM_FF_SET(pVM, VM_FF_TERMINATE);
1605 }
1606 else
1607 {
1608 /*
1609 * Request EMT to do the larger part of the destruction.
1610 */
1611 PVMREQ pReq = NULL;
1612 int rc = VMR3ReqCallU(pUVM, VMREQDEST_ANY, &pReq, RT_INDEFINITE_WAIT, 0, (PFNRT)vmR3Destroy, 1, pVM);
1613 if (RT_SUCCESS(rc))
1614 rc = pReq->iStatus;
1615 AssertRC(rc);
1616 VMR3ReqFree(pReq);
1617
1618 /*
1619 * Wait for the EMT thread to terminate.
1620 */
1621 Assert(pUVM->vm.s.fTerminateEMT);
1622 /** @todo SMP */
1623 rc = RTThreadWait(pUVM->aCpus[0].vm.s.ThreadEMT, 30000, NULL);
1624 AssertMsgRC(rc, ("EMT thread wait failed, rc=%Rrc\n", rc));
1625
1626 /*
1627 * Now do the final bit where the heap and VM structures are freed up.
1628 */
1629 vmR3DestroyUVM(pUVM);
1630 }
1631
1632 LogFlow(("VMR3Destroy: returns VINF_SUCCESS\n"));
1633 return VINF_SUCCESS;
1634}
1635
1636
1637/**
1638 * Internal destruction worker.
1639 *
1640 * This will do nearly all of the job, including sacking the EMT.
1641 *
1642 * @returns VBox status.
1643 * @param pVM VM handle.
1644 */
1645DECLCALLBACK(int) vmR3Destroy(PVM pVM)
1646{
1647 PUVM pUVM = pVM->pUVM;
1648 NOREF(pUVM);
1649 LogFlow(("vmR3Destroy: pVM=%p pUVM=%p\n", pVM, pUVM));
1650 VM_ASSERT_EMT(pVM);
1651
1652 /*
1653 * Dump statistics to the log.
1654 */
1655#if defined(VBOX_WITH_STATISTICS) || defined(LOG_ENABLED)
1656 RTLogFlags(NULL, "nodisabled nobuffered");
1657#endif
1658#ifdef VBOX_WITH_STATISTICS
1659 STAMR3Dump(pVM, "*");
1660#else
1661 LogRel(("************************* Statistics *************************\n"));
1662 STAMR3DumpToReleaseLog(pVM, "*");
1663 LogRel(("********************* End of statistics **********************\n"));
1664#endif
1665
1666 /*
1667 * Destroy the VM components.
1668 */
1669 int rc = TMR3Term(pVM);
1670 AssertRC(rc);
1671#ifdef VBOX_WITH_DEBUGGER
1672 rc = DBGCTcpTerminate(pVM, pUVM->vm.s.pvDBGC);
1673 pVM->pUVM->vm.s.pvDBGC = NULL;
1674#endif
1675 AssertRC(rc);
1676 rc = DBGFR3Term(pVM);
1677 AssertRC(rc);
1678 rc = PDMR3Term(pVM);
1679 AssertRC(rc);
1680 rc = EMR3Term(pVM);
1681 AssertRC(rc);
1682 rc = IOMR3Term(pVM);
1683 AssertRC(rc);
1684 rc = CSAMR3Term(pVM);
1685 AssertRC(rc);
1686 rc = PATMR3Term(pVM);
1687 AssertRC(rc);
1688 rc = TRPMR3Term(pVM);
1689 AssertRC(rc);
1690 rc = SELMR3Term(pVM);
1691 AssertRC(rc);
1692 rc = REMR3Term(pVM);
1693 AssertRC(rc);
1694 rc = HWACCMR3Term(pVM);
1695 AssertRC(rc);
1696 rc = PGMR3Term(pVM);
1697 AssertRC(rc);
1698 rc = VMMR3Term(pVM); /* Terminates the ring-0 code! */
1699 AssertRC(rc);
1700 rc = CPUMR3Term(pVM);
1701 AssertRC(rc);
1702 rc = PDMR3CritSectTerm(pVM);
1703 AssertRC(rc);
1704 rc = MMR3Term(pVM);
1705 AssertRC(rc);
1706
1707 /*
1708 * We're done in this thread (EMT).
1709 */
1710 ASMAtomicUoWriteBool(&pVM->pUVM->vm.s.fTerminateEMT, true);
1711 ASMAtomicWriteU32(&pVM->fForcedActions, VM_FF_TERMINATE);
1712 LogFlow(("vmR3Destroy: returning %Rrc\n", VINF_EM_TERMINATE));
1713 return VINF_EM_TERMINATE;
1714}
1715
1716
1717/**
1718 * Destroys the shared VM structure, leaving only UVM behind.
1719 *
1720 * This is called by EMT right before terminating.
1721 *
1722 * @param pUVM The UVM handle.
1723 */
1724void vmR3DestroyFinalBitFromEMT(PUVM pUVM)
1725{
1726 if (pUVM->pVM)
1727 {
1728 /*
1729 * Modify state and then terminate MM.
1730 * (MM must be delayed until this point so we don't destroy the callbacks and the request packet.)
1731 */
1732 vmR3SetState(pUVM->pVM, VMSTATE_TERMINATED);
1733
1734 /*
1735 * Tell GVMM to destroy the VM and free its resources.
1736 */
1737 int rc = SUPCallVMMR0Ex(pUVM->pVM->pVMR0, VMMR0_DO_GVMM_DESTROY_VM, 0, NULL);
1738 AssertRC(rc);
1739 pUVM->pVM = NULL;
1740 }
1741
1742 /*
1743 * Did EMT call VMR3Destroy and have to do it all?
1744 */
1745 if (pUVM->vm.s.fEMTDoesTheCleanup)
1746 vmR3DestroyUVM(pUVM);
1747}
1748
1749
1750/**
1751 * Destroys the UVM portion.
1752 *
1753 * This is called as the final step in the VM destruction or as the cleanup
1754 * in case of a creation failure. If EMT called VMR3Destroy, meaning
1755 * VMINTUSERPERVM::fEMTDoesTheCleanup is true, it will call this as
1756 * vmR3DestroyFinalBitFromEMT completes.
1757 *
1758 * @param pVM VM Handle.
1759 */
1760static void vmR3DestroyUVM(PUVM pUVM)
1761{
1762 /*
1763 * Terminate the EMT if still running (creation failure only).
1764 */
1765 if (!pUVM->vm.s.fTerminateEMT)
1766 {
1767 ASMAtomicUoWriteBool(&pUVM->vm.s.fTerminateEMT, true);
1768 if (pUVM->pVM)
1769 {
1770 VM_FF_SET(pUVM->pVM, VM_FF_TERMINATE);
1771 VMR3NotifyFF(pUVM->pVM, false);
1772 }
1773 RTSemEventSignal(pUVM->vm.s.EventSemWait);
1774
1775 /** @todo SMP */
1776 int rc2 = RTThreadWait(pUVM->aCpus[0].vm.s.ThreadEMT, 2000, NULL);
1777 AssertRC(rc2);
1778 }
1779 RTSemEventDestroy(pUVM->vm.s.EventSemWait);
1780 pUVM->vm.s.EventSemWait = NIL_RTSEMEVENT;
1781
1782 /*
1783 * Free the event semaphores associated with the request packets.
1784 */
1785 unsigned cReqs = 0;
1786 for (unsigned i = 0; i < RT_ELEMENTS(pUVM->vm.s.apReqFree); i++)
1787 {
1788 PVMREQ pReq = pUVM->vm.s.apReqFree[i];
1789 pUVM->vm.s.apReqFree[i] = NULL;
1790 for (; pReq; pReq = pReq->pNext, cReqs++)
1791 {
1792 pReq->enmState = VMREQSTATE_INVALID;
1793 RTSemEventDestroy(pReq->EventSem);
1794 }
1795 }
1796 Assert(cReqs == pUVM->vm.s.cReqFree); NOREF(cReqs);
1797
1798 /*
1799 * Kill all queued requests. (There really shouldn't be any!)
1800 */
1801 for (unsigned i = 0; i < 10; i++)
1802 {
1803 PVMREQ pReqHead = (PVMREQ)ASMAtomicXchgPtr((void *volatile *)&pUVM->vm.s.pReqs, NULL);
1804 AssertMsg(!pReqHead, ("This isn't supposed to happen! VMR3Destroy caller has to serialize this.\n"));
1805 if (!pReqHead)
1806 break;
1807 for (PVMREQ pReq = pReqHead; pReq; pReq = pReq->pNext)
1808 {
1809 ASMAtomicUoWriteSize(&pReq->iStatus, VERR_INTERNAL_ERROR);
1810 ASMAtomicWriteSize(&pReq->enmState, VMREQSTATE_INVALID);
1811 RTSemEventSignal(pReq->EventSem);
1812 RTThreadSleep(2);
1813 RTSemEventDestroy(pReq->EventSem);
1814 }
1815 /* give them a chance to respond before we free the request memory. */
1816 RTThreadSleep(32);
1817 }
1818
1819 /*
1820 * Make sure the VMMR0.r0 module and whatever else is unloaded.
1821 */
1822 PDMR3TermUVM(pUVM);
1823
1824 /*
1825 * Terminate the support library if initialized.
1826 */
1827 if (pUVM->vm.s.pSession)
1828 {
1829 int rc = SUPTerm();
1830 AssertRC(rc);
1831 pUVM->vm.s.pSession = NIL_RTR0PTR;
1832 }
1833
1834 /*
1835 * Destroy the MM heap and free the UVM structure.
1836 */
1837 MMR3TermUVM(pUVM);
1838 STAMR3TermUVM(pUVM);
1839
1840 RTTlsFree(pUVM->vm.s.idxTLS);
1841
1842 ASMAtomicUoWriteU32(&pUVM->u32Magic, UINT32_MAX);
1843 RTMemFree(pUVM);
1844
1845 RTLogFlush(NULL);
1846}
1847
1848
1849/**
1850 * Enumerates the VMs in this process.
1851 *
1852 * @returns Pointer to the next VM.
1853 * @returns NULL when no more VMs.
1854 * @param pVMPrev The previous VM
1855 * Use NULL to start the enumeration.
1856 */
1857VMMR3DECL(PVM) VMR3EnumVMs(PVM pVMPrev)
1858{
1859 /*
1860 * This is quick and dirty. It has issues with VM being
1861 * destroyed during the enumeration.
1862 */
1863 PUVM pNext;
1864 if (pVMPrev)
1865 pNext = pVMPrev->pUVM->pNext;
1866 else
1867 pNext = g_pUVMsHead;
1868 return pNext ? pNext->pVM : NULL;
1869}
1870
1871
1872/**
1873 * Registers an at VM destruction callback.
1874 *
1875 * @returns VBox status code.
1876 * @param pfnAtDtor Pointer to callback.
1877 * @param pvUser User argument.
1878 */
1879VMMR3DECL(int) VMR3AtDtorRegister(PFNVMATDTOR pfnAtDtor, void *pvUser)
1880{
1881 /*
1882 * Check if already registered.
1883 */
1884 VM_ATDTOR_LOCK();
1885 PVMATDTOR pCur = g_pVMAtDtorHead;
1886 while (pCur)
1887 {
1888 if (pfnAtDtor == pCur->pfnAtDtor)
1889 {
1890 VM_ATDTOR_UNLOCK();
1891 AssertMsgFailed(("Already registered at destruction callback %p!\n", pfnAtDtor));
1892 return VERR_INVALID_PARAMETER;
1893 }
1894
1895 /* next */
1896 pCur = pCur->pNext;
1897 }
1898 VM_ATDTOR_UNLOCK();
1899
1900 /*
1901 * Allocate new entry.
1902 */
1903 PVMATDTOR pVMAtDtor = (PVMATDTOR)RTMemAlloc(sizeof(*pVMAtDtor));
1904 if (!pVMAtDtor)
1905 return VERR_NO_MEMORY;
1906
1907 VM_ATDTOR_LOCK();
1908 pVMAtDtor->pfnAtDtor = pfnAtDtor;
1909 pVMAtDtor->pvUser = pvUser;
1910 pVMAtDtor->pNext = g_pVMAtDtorHead;
1911 g_pVMAtDtorHead = pVMAtDtor;
1912 VM_ATDTOR_UNLOCK();
1913
1914 return VINF_SUCCESS;
1915}
1916
1917
1918/**
1919 * Deregisters an at VM destruction callback.
1920 *
1921 * @returns VBox status code.
1922 * @param pfnAtDtor Pointer to callback.
1923 */
1924VMMR3DECL(int) VMR3AtDtorDeregister(PFNVMATDTOR pfnAtDtor)
1925{
1926 /*
1927 * Find it, unlink it and free it.
1928 */
1929 VM_ATDTOR_LOCK();
1930 PVMATDTOR pPrev = NULL;
1931 PVMATDTOR pCur = g_pVMAtDtorHead;
1932 while (pCur)
1933 {
1934 if (pfnAtDtor == pCur->pfnAtDtor)
1935 {
1936 if (pPrev)
1937 pPrev->pNext = pCur->pNext;
1938 else
1939 g_pVMAtDtorHead = pCur->pNext;
1940 pCur->pNext = NULL;
1941 VM_ATDTOR_UNLOCK();
1942
1943 RTMemFree(pCur);
1944 return VINF_SUCCESS;
1945 }
1946
1947 /* next */
1948 pPrev = pCur;
1949 pCur = pCur->pNext;
1950 }
1951 VM_ATDTOR_UNLOCK();
1952
1953 return VERR_INVALID_PARAMETER;
1954}
1955
1956
1957/**
1958 * Walks the list of at VM destructor callbacks.
1959 * @param pVM The VM which is about to be destroyed.
1960 */
1961static void vmR3AtDtor(PVM pVM)
1962{
1963 /*
1964 * Find it, unlink it and free it.
1965 */
1966 VM_ATDTOR_LOCK();
1967 for (PVMATDTOR pCur = g_pVMAtDtorHead; pCur; pCur = pCur->pNext)
1968 pCur->pfnAtDtor(pVM, pCur->pvUser);
1969 VM_ATDTOR_UNLOCK();
1970}
1971
1972
1973/**
1974 * Reset the current VM.
1975 *
1976 * @returns VBox status code.
1977 * @param pVM VM to reset.
1978 */
1979VMMR3DECL(int) VMR3Reset(PVM pVM)
1980{
1981 int rc = VINF_SUCCESS;
1982
1983 /*
1984 * Check the state.
1985 */
1986 if (!pVM)
1987 return VERR_INVALID_PARAMETER;
1988 if ( pVM->enmVMState != VMSTATE_RUNNING
1989 && pVM->enmVMState != VMSTATE_SUSPENDED)
1990 {
1991 AssertMsgFailed(("Invalid VM state %d\n", pVM->enmVMState));
1992 return VERR_VM_INVALID_VM_STATE;
1993 }
1994
1995 /*
1996 * Queue reset request to the emulation thread
1997 * and wait for it to be processed.
1998 */
1999 PVMREQ pReq = NULL;
2000 rc = VMR3ReqCall(pVM, VMREQDEST_ANY, &pReq, 0, (PFNRT)vmR3Reset, 1, pVM);
2001 while (rc == VERR_TIMEOUT)
2002 rc = VMR3ReqWait(pReq, RT_INDEFINITE_WAIT);
2003 if (RT_SUCCESS(rc))
2004 rc = pReq->iStatus;
2005 VMR3ReqFree(pReq);
2006
2007 return rc;
2008}
2009
2010
2011/**
2012 * Worker which checks integrity of some internal structures.
2013 * This is yet another attempt to track down that AVL tree crash.
2014 */
2015static void vmR3CheckIntegrity(PVM pVM)
2016{
2017#ifdef VBOX_STRICT
2018 int rc = PGMR3CheckIntegrity(pVM);
2019 AssertReleaseRC(rc);
2020#endif
2021}
2022
2023
2024/**
2025 * Reset request processor.
2026 *
2027 * This is called by the emulation thread as a response to the
2028 * reset request issued by VMR3Reset().
2029 *
2030 * @returns VBox status code.
2031 * @param pVM VM to reset.
2032 */
2033static DECLCALLBACK(int) vmR3Reset(PVM pVM)
2034{
2035 /*
2036 * As a safety precaution we temporarily change the state while resetting.
2037 * (If VMR3Reset was not called from EMT we might have change state... let's ignore that fact for now.)
2038 */
2039 VMSTATE enmVMState = pVM->enmVMState;
2040 Assert(enmVMState == VMSTATE_SUSPENDED || enmVMState == VMSTATE_RUNNING);
2041 vmR3SetState(pVM, VMSTATE_RESETTING);
2042 vmR3CheckIntegrity(pVM);
2043
2044
2045 /*
2046 * Reset the VM components.
2047 */
2048 PATMR3Reset(pVM);
2049 CSAMR3Reset(pVM);
2050 PGMR3Reset(pVM); /* We clear VM RAM in PGMR3Reset. It's vital PDMR3Reset is executed
2051 * _afterwards_. E.g. ACPI sets up RAM tables during init/reset. */
2052 MMR3Reset(pVM);
2053 PDMR3Reset(pVM);
2054 SELMR3Reset(pVM);
2055 TRPMR3Reset(pVM);
2056 vmR3AtResetU(pVM->pUVM);
2057 REMR3Reset(pVM);
2058 IOMR3Reset(pVM);
2059 CPUMR3Reset(pVM);
2060 TMR3Reset(pVM);
2061 EMR3Reset(pVM);
2062 HWACCMR3Reset(pVM); /* This must come *after* PATM, CSAM, CPUM, SELM and TRPM. */
2063
2064#ifdef LOG_ENABLED
2065 /*
2066 * Debug logging.
2067 */
2068 RTLogPrintf("\n\nThe VM was reset:\n");
2069 DBGFR3Info(pVM, "cpum", "verbose", NULL);
2070#endif
2071
2072 /*
2073 * Restore the state.
2074 */
2075 vmR3CheckIntegrity(pVM);
2076 Assert(pVM->enmVMState == VMSTATE_RESETTING);
2077 vmR3SetState(pVM, enmVMState);
2078
2079 return VINF_EM_RESET;
2080}
2081
2082
2083/**
2084 * Walks the list of at VM reset callbacks and calls them
2085 *
2086 * @returns VBox status code.
2087 * Any failure is fatal.
2088 * @param pUVM Pointe to the user mode VM structure.
2089 */
2090static int vmR3AtResetU(PUVM pUVM)
2091{
2092 /*
2093 * Walk the list and call them all.
2094 */
2095 int rc = VINF_SUCCESS;
2096 for (PVMATRESET pCur = pUVM->vm.s.pAtReset; pCur; pCur = pCur->pNext)
2097 {
2098 /* do the call */
2099 switch (pCur->enmType)
2100 {
2101 case VMATRESETTYPE_DEV:
2102 rc = pCur->u.Dev.pfnCallback(pCur->u.Dev.pDevIns, pCur->pvUser);
2103 break;
2104 case VMATRESETTYPE_INTERNAL:
2105 rc = pCur->u.Internal.pfnCallback(pUVM->pVM, pCur->pvUser);
2106 break;
2107 case VMATRESETTYPE_EXTERNAL:
2108 pCur->u.External.pfnCallback(pCur->pvUser);
2109 break;
2110 default:
2111 AssertMsgFailed(("Invalid at-reset type %d!\n", pCur->enmType));
2112 return VERR_INTERNAL_ERROR;
2113 }
2114
2115 if (RT_FAILURE(rc))
2116 {
2117 AssertMsgFailed(("At-reset handler %s failed with rc=%d\n", pCur->pszDesc, rc));
2118 return rc;
2119 }
2120 }
2121
2122 return VINF_SUCCESS;
2123}
2124
2125
2126/**
2127 * Internal registration function
2128 */
2129static int vmr3AtResetRegisterU(PUVM pUVM, void *pvUser, const char *pszDesc, PVMATRESET *ppNew)
2130{
2131 /*
2132 * Allocate restration structure.
2133 */
2134 PVMATRESET pNew = (PVMATRESET)MMR3HeapAllocU(pUVM, MM_TAG_VM, sizeof(*pNew));
2135 if (pNew)
2136 {
2137 /* fill data. */
2138 pNew->pszDesc = pszDesc;
2139 pNew->pvUser = pvUser;
2140
2141 /* insert */
2142 pNew->pNext = *pUVM->vm.s.ppAtResetNext;
2143 *pUVM->vm.s.ppAtResetNext = pNew;
2144 pUVM->vm.s.ppAtResetNext = &pNew->pNext;
2145
2146 *ppNew = pNew;
2147 return VINF_SUCCESS;
2148 }
2149 return VERR_NO_MEMORY;
2150}
2151
2152
2153/**
2154 * Registers an at VM reset callback.
2155 *
2156 * @returns VBox status code.
2157 * @param pVM The VM.
2158 * @param pDevInst Device instance.
2159 * @param pfnCallback Callback function.
2160 * @param pvUser User argument.
2161 * @param pszDesc Description (optional).
2162 */
2163VMMR3DECL(int) VMR3AtResetRegister(PVM pVM, PPDMDEVINS pDevInst, PFNVMATRESET pfnCallback, void *pvUser, const char *pszDesc)
2164{
2165 /*
2166 * Validate.
2167 */
2168 if (!pDevInst)
2169 {
2170 AssertMsgFailed(("pDevIns is NULL!\n"));
2171 return VERR_INVALID_PARAMETER;
2172 }
2173
2174 /*
2175 * Create the new entry.
2176 */
2177 PVMATRESET pNew;
2178 int rc = vmr3AtResetRegisterU(pVM->pUVM, pvUser, pszDesc, &pNew);
2179 if (RT_SUCCESS(rc))
2180 {
2181 /*
2182 * Fill in type data.
2183 */
2184 pNew->enmType = VMATRESETTYPE_DEV;
2185 pNew->u.Dev.pfnCallback = pfnCallback;
2186 pNew->u.Dev.pDevIns = pDevInst;
2187 }
2188
2189 return rc;
2190}
2191
2192
2193/**
2194 * Registers an at VM reset internal callback.
2195 *
2196 * @returns VBox status code.
2197 * @param pVM The VM.
2198 * @param pfnCallback Callback function.
2199 * @param pvUser User argument.
2200 * @param pszDesc Description (optional).
2201 */
2202VMMR3DECL(int) VMR3AtResetRegisterInternal(PVM pVM, PFNVMATRESETINT pfnCallback, void *pvUser, const char *pszDesc)
2203{
2204 /*
2205 * Validate.
2206 */
2207 if (!pfnCallback)
2208 {
2209 AssertMsgFailed(("pfnCallback is NULL!\n"));
2210 return VERR_INVALID_PARAMETER;
2211 }
2212
2213 /*
2214 * Create the new entry.
2215 */
2216 PVMATRESET pNew;
2217 int rc = vmr3AtResetRegisterU(pVM->pUVM, pvUser, pszDesc, &pNew);
2218 if (RT_SUCCESS(rc))
2219 {
2220 /*
2221 * Fill in type data.
2222 */
2223 pNew->enmType = VMATRESETTYPE_INTERNAL;
2224 pNew->u.Internal.pfnCallback = pfnCallback;
2225 }
2226
2227 return rc;
2228}
2229
2230
2231/**
2232 * Registers an at VM reset external callback.
2233 *
2234 * @returns VBox status code.
2235 * @param pVM The VM.
2236 * @param pfnCallback Callback function.
2237 * @param pvUser User argument.
2238 * @param pszDesc Description (optional).
2239 */
2240VMMR3DECL(int) VMR3AtResetRegisterExternal(PVM pVM, PFNVMATRESETEXT pfnCallback, void *pvUser, const char *pszDesc)
2241{
2242 /*
2243 * Validate.
2244 */
2245 if (!pfnCallback)
2246 {
2247 AssertMsgFailed(("pfnCallback is NULL!\n"));
2248 return VERR_INVALID_PARAMETER;
2249 }
2250
2251 /*
2252 * Create the new entry.
2253 */
2254 PVMATRESET pNew;
2255 int rc = vmr3AtResetRegisterU(pVM->pUVM, pvUser, pszDesc, &pNew);
2256 if (RT_SUCCESS(rc))
2257 {
2258 /*
2259 * Fill in type data.
2260 */
2261 pNew->enmType = VMATRESETTYPE_EXTERNAL;
2262 pNew->u.External.pfnCallback = pfnCallback;
2263 }
2264
2265 return rc;
2266}
2267
2268
2269/**
2270 * Unlinks and frees a callback.
2271 *
2272 * @returns Pointer to the next callback structure.
2273 * @param pUVM Pointer to the user mode VM structure.
2274 * @param pCur The one to free.
2275 * @param pPrev The one before pCur.
2276 */
2277static PVMATRESET vmr3AtResetFreeU(PUVM pUVM, PVMATRESET pCur, PVMATRESET pPrev)
2278{
2279 /*
2280 * Unlink it.
2281 */
2282 PVMATRESET pNext = pCur->pNext;
2283 if (pPrev)
2284 {
2285 pPrev->pNext = pNext;
2286 if (!pNext)
2287 pUVM->vm.s.ppAtResetNext = &pPrev->pNext;
2288 }
2289 else
2290 {
2291 pUVM->vm.s.pAtReset = pNext;
2292 if (!pNext)
2293 pUVM->vm.s.ppAtResetNext = &pUVM->vm.s.pAtReset;
2294 }
2295
2296 /*
2297 * Free it.
2298 */
2299 MMR3HeapFree(pCur);
2300
2301 return pNext;
2302}
2303
2304
2305/**
2306 * Deregisters an at VM reset callback.
2307 *
2308 * @returns VBox status code.
2309 * @param pVM The VM.
2310 * @param pDevIns Device instance.
2311 * @param pfnCallback Callback function.
2312 */
2313VMMR3DECL(int) VMR3AtResetDeregister(PVM pVM, PPDMDEVINS pDevIns, PFNVMATRESET pfnCallback)
2314{
2315 int rc = VERR_VM_ATRESET_NOT_FOUND;
2316 PVMATRESET pPrev = NULL;
2317 PVMATRESET pCur = pVM->pUVM->vm.s.pAtReset;
2318 while (pCur)
2319 {
2320 if ( pCur->enmType == VMATRESETTYPE_DEV
2321 && pCur->u.Dev.pDevIns == pDevIns
2322 && ( !pfnCallback
2323 || pCur->u.Dev.pfnCallback == pfnCallback))
2324 {
2325 pCur = vmr3AtResetFreeU(pVM->pUVM, pCur, pPrev);
2326 rc = VINF_SUCCESS;
2327 }
2328 else
2329 {
2330 pPrev = pCur;
2331 pCur = pCur->pNext;
2332 }
2333 }
2334
2335 AssertRC(rc);
2336 return rc;
2337}
2338
2339
2340/**
2341 * Deregisters an at VM reset internal callback.
2342 *
2343 * @returns VBox status code.
2344 * @param pVM The VM.
2345 * @param pfnCallback Callback function.
2346 */
2347VMMR3DECL(int) VMR3AtResetDeregisterInternal(PVM pVM, PFNVMATRESETINT pfnCallback)
2348{
2349 int rc = VERR_VM_ATRESET_NOT_FOUND;
2350 PVMATRESET pPrev = NULL;
2351 PVMATRESET pCur = pVM->pUVM->vm.s.pAtReset;
2352 while (pCur)
2353 {
2354 if ( pCur->enmType == VMATRESETTYPE_INTERNAL
2355 && pCur->u.Internal.pfnCallback == pfnCallback)
2356 {
2357 pCur = vmr3AtResetFreeU(pVM->pUVM, pCur, pPrev);
2358 rc = VINF_SUCCESS;
2359 }
2360 else
2361 {
2362 pPrev = pCur;
2363 pCur = pCur->pNext;
2364 }
2365 }
2366
2367 AssertRC(rc);
2368 return rc;
2369}
2370
2371
2372/**
2373 * Deregisters an at VM reset external callback.
2374 *
2375 * @returns VBox status code.
2376 * @param pVM The VM.
2377 * @param pfnCallback Callback function.
2378 */
2379VMMR3DECL(int) VMR3AtResetDeregisterExternal(PVM pVM, PFNVMATRESETEXT pfnCallback)
2380{
2381 int rc = VERR_VM_ATRESET_NOT_FOUND;
2382 PVMATRESET pPrev = NULL;
2383 PVMATRESET pCur = pVM->pUVM->vm.s.pAtReset;
2384 while (pCur)
2385 {
2386 if ( pCur->enmType == VMATRESETTYPE_INTERNAL
2387 && pCur->u.External.pfnCallback == pfnCallback)
2388 {
2389 pCur = vmr3AtResetFreeU(pVM->pUVM, pCur, pPrev);
2390 rc = VINF_SUCCESS;
2391 }
2392 else
2393 {
2394 pPrev = pCur;
2395 pCur = pCur->pNext;
2396 }
2397 }
2398
2399 AssertRC(rc);
2400 return rc;
2401}
2402
2403
2404/**
2405 * Gets the current VM state.
2406 *
2407 * @returns The current VM state.
2408 * @param pVM VM handle.
2409 * @thread Any
2410 */
2411VMMR3DECL(VMSTATE) VMR3GetState(PVM pVM)
2412{
2413 return pVM->enmVMState;
2414}
2415
2416
2417/**
2418 * Gets the state name string for a VM state.
2419 *
2420 * @returns Pointer to the state name. (readonly)
2421 * @param enmState The state.
2422 */
2423VMMR3DECL(const char *) VMR3GetStateName(VMSTATE enmState)
2424{
2425 switch (enmState)
2426 {
2427 case VMSTATE_CREATING: return "CREATING";
2428 case VMSTATE_CREATED: return "CREATED";
2429 case VMSTATE_RUNNING: return "RUNNING";
2430 case VMSTATE_LOADING: return "LOADING";
2431 case VMSTATE_LOAD_FAILURE: return "LOAD_FAILURE";
2432 case VMSTATE_SAVING: return "SAVING";
2433 case VMSTATE_SUSPENDED: return "SUSPENDED";
2434 case VMSTATE_RESETTING: return "RESETTING";
2435 case VMSTATE_GURU_MEDITATION: return "GURU_MEDITATION";
2436 case VMSTATE_OFF: return "OFF";
2437 case VMSTATE_DESTROYING: return "DESTROYING";
2438 case VMSTATE_TERMINATED: return "TERMINATED";
2439 default:
2440 AssertMsgFailed(("Unknown state %d\n", enmState));
2441 return "Unknown!\n";
2442 }
2443}
2444
2445
2446/**
2447 * Sets the current VM state.
2448 *
2449 * @returns The current VM state.
2450 * @param pVM VM handle.
2451 * @param enmStateNew The new state.
2452 */
2453void vmR3SetState(PVM pVM, VMSTATE enmStateNew)
2454{
2455 /*
2456 * Validate state machine transitions before doing the actual change.
2457 */
2458 VMSTATE enmStateOld = pVM->enmVMState;
2459 switch (enmStateOld)
2460 {
2461 case VMSTATE_OFF:
2462 Assert(enmStateNew != VMSTATE_GURU_MEDITATION);
2463 break;
2464
2465 default:
2466 /** @todo full validation. */
2467 break;
2468 }
2469
2470 pVM->enmVMState = enmStateNew;
2471 LogRel(("Changing the VM state from '%s' to '%s'.\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)));
2472
2473 /*
2474 * Call the at state change callbacks.
2475 */
2476 for (PVMATSTATE pCur = pVM->pUVM->vm.s.pAtState; pCur; pCur = pCur->pNext)
2477 {
2478 pCur->pfnAtState(pVM, enmStateNew, enmStateOld, pCur->pvUser);
2479 if ( pVM->enmVMState != enmStateNew
2480 && pVM->enmVMState == VMSTATE_DESTROYING)
2481 break;
2482 AssertMsg(pVM->enmVMState == enmStateNew,
2483 ("You are not allowed to change the state while in the change callback, except "
2484 "from destroying the VM. There are restrictions in the way the state changes "
2485 "are propagated up to the EM execution loop and it makes the program flow very "
2486 "difficult to follow.\n"));
2487 }
2488}
2489
2490
2491/**
2492 * Registers a VM state change callback.
2493 *
2494 * You are not allowed to call any function which changes the VM state from a
2495 * state callback, except VMR3Destroy().
2496 *
2497 * @returns VBox status code.
2498 * @param pVM VM handle.
2499 * @param pfnAtState Pointer to callback.
2500 * @param pvUser User argument.
2501 * @thread Any.
2502 */
2503VMMR3DECL(int) VMR3AtStateRegister(PVM pVM, PFNVMATSTATE pfnAtState, void *pvUser)
2504{
2505 LogFlow(("VMR3AtStateRegister: pfnAtState=%p pvUser=%p\n", pfnAtState, pvUser));
2506
2507 /*
2508 * Validate input.
2509 */
2510 if (!pfnAtState)
2511 {
2512 AssertMsgFailed(("callback is required\n"));
2513 return VERR_INVALID_PARAMETER;
2514 }
2515
2516 /*
2517 * Make sure we're in EMT (to avoid the logging).
2518 */
2519 PVMREQ pReq;
2520 int rc = VMR3ReqCall(pVM, VMREQDEST_ANY, &pReq, RT_INDEFINITE_WAIT, (PFNRT)vmR3AtStateRegisterU, 3, pVM->pUVM, pfnAtState, pvUser);
2521 if (RT_FAILURE(rc))
2522 return rc;
2523 rc = pReq->iStatus;
2524 VMR3ReqFree(pReq);
2525
2526 LogFlow(("VMR3AtStateRegister: returns %Rrc\n", rc));
2527 return rc;
2528}
2529
2530
2531/**
2532 * Registers a VM state change callback.
2533 *
2534 * @returns VBox status code.
2535 * @param pUVM Pointer to the user mode VM structure.
2536 * @param pfnAtState Pointer to callback.
2537 * @param pvUser User argument.
2538 * @thread EMT
2539 */
2540static DECLCALLBACK(int) vmR3AtStateRegisterU(PUVM pUVM, PFNVMATSTATE pfnAtState, void *pvUser)
2541{
2542 /*
2543 * Allocate a new record.
2544 */
2545
2546 PVMATSTATE pNew = (PVMATSTATE)MMR3HeapAllocU(pUVM, MM_TAG_VM, sizeof(*pNew));
2547 if (!pNew)
2548 return VERR_NO_MEMORY;
2549
2550 /* fill */
2551 pNew->pfnAtState = pfnAtState;
2552 pNew->pvUser = pvUser;
2553
2554 /* insert */
2555 pNew->pNext = *pUVM->vm.s.ppAtStateNext;
2556 *pUVM->vm.s.ppAtStateNext = pNew;
2557 pUVM->vm.s.ppAtStateNext = &pNew->pNext;
2558
2559 return VINF_SUCCESS;
2560}
2561
2562
2563/**
2564 * Deregisters a VM state change callback.
2565 *
2566 * @returns VBox status code.
2567 * @param pVM VM handle.
2568 * @param pfnAtState Pointer to callback.
2569 * @param pvUser User argument.
2570 * @thread Any.
2571 */
2572VMMR3DECL(int) VMR3AtStateDeregister(PVM pVM, PFNVMATSTATE pfnAtState, void *pvUser)
2573{
2574 LogFlow(("VMR3AtStateDeregister: pfnAtState=%p pvUser=%p\n", pfnAtState, pvUser));
2575
2576 /*
2577 * Validate input.
2578 */
2579 if (!pfnAtState)
2580 {
2581 AssertMsgFailed(("callback is required\n"));
2582 return VERR_INVALID_PARAMETER;
2583 }
2584
2585 /*
2586 * Make sure we're in EMT (to avoid the logging).
2587 */
2588 PVMREQ pReq;
2589 int rc = VMR3ReqCall(pVM, VMREQDEST_ANY, &pReq, RT_INDEFINITE_WAIT, (PFNRT)vmR3AtStateDeregisterU, 3, pVM->pUVM, pfnAtState, pvUser);
2590 if (RT_FAILURE(rc))
2591 return rc;
2592 rc = pReq->iStatus;
2593 VMR3ReqFree(pReq);
2594
2595 LogFlow(("VMR3AtStateDeregister: returns %Rrc\n", rc));
2596 return rc;
2597}
2598
2599
2600/**
2601 * Deregisters a VM state change callback.
2602 *
2603 * @returns VBox status code.
2604 * @param pUVM Pointer to the user mode VM structure.
2605 * @param pfnAtState Pointer to callback.
2606 * @param pvUser User argument.
2607 * @thread EMT
2608 */
2609static DECLCALLBACK(int) vmR3AtStateDeregisterU(PUVM pUVM, PFNVMATSTATE pfnAtState, void *pvUser)
2610{
2611 LogFlow(("vmR3AtStateDeregisterU: pfnAtState=%p pvUser=%p\n", pfnAtState, pvUser));
2612
2613 /*
2614 * Search the list for the entry.
2615 */
2616 PVMATSTATE pPrev = NULL;
2617 PVMATSTATE pCur = pUVM->vm.s.pAtState;
2618 while ( pCur
2619 && ( pCur->pfnAtState != pfnAtState
2620 || pCur->pvUser != pvUser))
2621 {
2622 pPrev = pCur;
2623 pCur = pCur->pNext;
2624 }
2625 if (!pCur)
2626 {
2627 AssertMsgFailed(("pfnAtState=%p was not found\n", pfnAtState));
2628 return VERR_FILE_NOT_FOUND;
2629 }
2630
2631 /*
2632 * Unlink it.
2633 */
2634 if (pPrev)
2635 {
2636 pPrev->pNext = pCur->pNext;
2637 if (!pCur->pNext)
2638 pUVM->vm.s.ppAtStateNext = &pPrev->pNext;
2639 }
2640 else
2641 {
2642 pUVM->vm.s.pAtState = pCur->pNext;
2643 if (!pCur->pNext)
2644 pUVM->vm.s.ppAtStateNext = &pUVM->vm.s.pAtState;
2645 }
2646
2647 /*
2648 * Free it.
2649 */
2650 pCur->pfnAtState = NULL;
2651 pCur->pNext = NULL;
2652 MMR3HeapFree(pCur);
2653
2654 return VINF_SUCCESS;
2655}
2656
2657
2658/**
2659 * Registers a VM error callback.
2660 *
2661 * @returns VBox status code.
2662 * @param pVM The VM handle.
2663 * @param pfnAtError Pointer to callback.
2664 * @param pvUser User argument.
2665 * @thread Any.
2666 */
2667VMMR3DECL(int) VMR3AtErrorRegister(PVM pVM, PFNVMATERROR pfnAtError, void *pvUser)
2668{
2669 return VMR3AtErrorRegisterU(pVM->pUVM, pfnAtError, pvUser);
2670}
2671
2672
2673/**
2674 * Registers a VM error callback.
2675 *
2676 * @returns VBox status code.
2677 * @param pUVM The VM handle.
2678 * @param pfnAtError Pointer to callback.
2679 * @param pvUser User argument.
2680 * @thread Any.
2681 */
2682VMMR3DECL(int) VMR3AtErrorRegisterU(PUVM pUVM, PFNVMATERROR pfnAtError, void *pvUser)
2683{
2684 LogFlow(("VMR3AtErrorRegister: pfnAtError=%p pvUser=%p\n", pfnAtError, pvUser));
2685 AssertPtrReturn(pfnAtError, VERR_INVALID_PARAMETER);
2686
2687 /*
2688 * Make sure we're in EMT (to avoid the logging).
2689 */
2690 PVMREQ pReq;
2691 int rc = VMR3ReqCallU(pUVM, VMREQDEST_ANY, &pReq, RT_INDEFINITE_WAIT, 0, (PFNRT)vmR3AtErrorRegisterU, 3, pUVM, pfnAtError, pvUser);
2692 if (RT_FAILURE(rc))
2693 return rc;
2694 rc = pReq->iStatus;
2695 VMR3ReqFree(pReq);
2696
2697 LogFlow(("VMR3AtErrorRegister: returns %Rrc\n", rc));
2698 return rc;
2699}
2700
2701
2702/**
2703 * Registers a VM error callback.
2704 *
2705 * @returns VBox status code.
2706 * @param pUVM Pointer to the user mode VM structure.
2707 * @param pfnAtError Pointer to callback.
2708 * @param pvUser User argument.
2709 * @thread EMT
2710 */
2711static DECLCALLBACK(int) vmR3AtErrorRegisterU(PUVM pUVM, PFNVMATERROR pfnAtError, void *pvUser)
2712{
2713 /*
2714 * Allocate a new record.
2715 */
2716
2717 PVMATERROR pNew = (PVMATERROR)MMR3HeapAllocU(pUVM, MM_TAG_VM, sizeof(*pNew));
2718 if (!pNew)
2719 return VERR_NO_MEMORY;
2720
2721 /* fill */
2722 pNew->pfnAtError = pfnAtError;
2723 pNew->pvUser = pvUser;
2724
2725 /* insert */
2726 pNew->pNext = *pUVM->vm.s.ppAtErrorNext;
2727 *pUVM->vm.s.ppAtErrorNext = pNew;
2728 pUVM->vm.s.ppAtErrorNext = &pNew->pNext;
2729
2730 return VINF_SUCCESS;
2731}
2732
2733
2734/**
2735 * Deregisters a VM error callback.
2736 *
2737 * @returns VBox status code.
2738 * @param pVM The VM handle.
2739 * @param pfnAtError Pointer to callback.
2740 * @param pvUser User argument.
2741 * @thread Any.
2742 */
2743VMMR3DECL(int) VMR3AtErrorDeregister(PVM pVM, PFNVMATERROR pfnAtError, void *pvUser)
2744{
2745 LogFlow(("VMR3AtErrorDeregister: pfnAtError=%p pvUser=%p\n", pfnAtError, pvUser));
2746
2747 /*
2748 * Validate input.
2749 */
2750 if (!pfnAtError)
2751 {
2752 AssertMsgFailed(("callback is required\n"));
2753 return VERR_INVALID_PARAMETER;
2754 }
2755
2756 /*
2757 * Make sure we're in EMT (to avoid the logging).
2758 */
2759 PVMREQ pReq;
2760 int rc = VMR3ReqCall(pVM, VMREQDEST_ANY, &pReq, RT_INDEFINITE_WAIT, (PFNRT)vmR3AtErrorDeregisterU, 3, pVM->pUVM, pfnAtError, pvUser);
2761 if (RT_FAILURE(rc))
2762 return rc;
2763 rc = pReq->iStatus;
2764 VMR3ReqFree(pReq);
2765
2766 LogFlow(("VMR3AtErrorDeregister: returns %Rrc\n", rc));
2767 return rc;
2768}
2769
2770
2771/**
2772 * Deregisters a VM error callback.
2773 *
2774 * @returns VBox status code.
2775 * @param pUVM Pointer to the user mode VM structure.
2776 * @param pfnAtError Pointer to callback.
2777 * @param pvUser User argument.
2778 * @thread EMT
2779 */
2780static DECLCALLBACK(int) vmR3AtErrorDeregisterU(PUVM pUVM, PFNVMATERROR pfnAtError, void *pvUser)
2781{
2782 LogFlow(("vmR3AtErrorDeregisterU: pfnAtError=%p pvUser=%p\n", pfnAtError, pvUser));
2783
2784 /*
2785 * Search the list for the entry.
2786 */
2787 PVMATERROR pPrev = NULL;
2788 PVMATERROR pCur = pUVM->vm.s.pAtError;
2789 while ( pCur
2790 && ( pCur->pfnAtError != pfnAtError
2791 || pCur->pvUser != pvUser))
2792 {
2793 pPrev = pCur;
2794 pCur = pCur->pNext;
2795 }
2796 if (!pCur)
2797 {
2798 AssertMsgFailed(("pfnAtError=%p was not found\n", pfnAtError));
2799 return VERR_FILE_NOT_FOUND;
2800 }
2801
2802 /*
2803 * Unlink it.
2804 */
2805 if (pPrev)
2806 {
2807 pPrev->pNext = pCur->pNext;
2808 if (!pCur->pNext)
2809 pUVM->vm.s.ppAtErrorNext = &pPrev->pNext;
2810 }
2811 else
2812 {
2813 pUVM->vm.s.pAtError = pCur->pNext;
2814 if (!pCur->pNext)
2815 pUVM->vm.s.ppAtErrorNext = &pUVM->vm.s.pAtError;
2816 }
2817
2818 /*
2819 * Free it.
2820 */
2821 pCur->pfnAtError = NULL;
2822 pCur->pNext = NULL;
2823 MMR3HeapFree(pCur);
2824
2825 return VINF_SUCCESS;
2826}
2827
2828
2829/**
2830 * Ellipsis to va_list wrapper for calling pfnAtError.
2831 */
2832static void vmR3SetErrorWorkerDoCall(PVM pVM, PVMATERROR pCur, int rc, RT_SRC_POS_DECL, const char *pszFormat, ...)
2833{
2834 va_list va;
2835 va_start(va, pszFormat);
2836 pCur->pfnAtError(pVM, pCur->pvUser, rc, RT_SRC_POS_ARGS, pszFormat, va);
2837 va_end(va);
2838}
2839
2840
2841/**
2842 * This is a worker function for GC and Ring-0 calls to VMSetError and VMSetErrorV.
2843 * The message is found in VMINT.
2844 *
2845 * @param pVM The VM handle.
2846 * @thread EMT.
2847 */
2848VMMR3DECL(void) VMR3SetErrorWorker(PVM pVM)
2849{
2850 VM_ASSERT_EMT(pVM);
2851 AssertReleaseMsgFailed(("And we have a winner! You get to implement Ring-0 and GC VMSetErrorV! Contrats!\n"));
2852
2853 /*
2854 * Unpack the error (if we managed to format one).
2855 */
2856 PVMERROR pErr = pVM->vm.s.pErrorR3;
2857 const char *pszFile = NULL;
2858 const char *pszFunction = NULL;
2859 uint32_t iLine = 0;
2860 const char *pszMessage;
2861 int32_t rc = VERR_MM_HYPER_NO_MEMORY;
2862 if (pErr)
2863 {
2864 AssertCompile(sizeof(const char) == sizeof(uint8_t));
2865 if (pErr->offFile)
2866 pszFile = (const char *)pErr + pErr->offFile;
2867 iLine = pErr->iLine;
2868 if (pErr->offFunction)
2869 pszFunction = (const char *)pErr + pErr->offFunction;
2870 if (pErr->offMessage)
2871 pszMessage = (const char *)pErr + pErr->offMessage;
2872 else
2873 pszMessage = "No message!";
2874 }
2875 else
2876 pszMessage = "No message! (Failed to allocate memory to put the error message in!)";
2877
2878 /*
2879 * Call the at error callbacks.
2880 */
2881 for (PVMATERROR pCur = pVM->pUVM->vm.s.pAtError; pCur; pCur = pCur->pNext)
2882 vmR3SetErrorWorkerDoCall(pVM, pCur, rc, RT_SRC_POS_ARGS, "%s", pszMessage);
2883}
2884
2885
2886/**
2887 * Creation time wrapper for vmR3SetErrorUV.
2888 *
2889 * @returns rc.
2890 * @param pUVM Pointer to the user mode VM structure.
2891 * @param rc The VBox status code.
2892 * @param RT_SRC_POS_DECL The source position of this error.
2893 * @param pszFormat Format string.
2894 * @param ... The arguments.
2895 * @thread Any thread.
2896 */
2897static int vmR3SetErrorU(PUVM pUVM, int rc, RT_SRC_POS_DECL, const char *pszFormat, ...)
2898{
2899 va_list va;
2900 va_start(va, pszFormat);
2901 vmR3SetErrorUV(pUVM, rc, pszFile, iLine, pszFunction, pszFormat, &va);
2902 va_end(va);
2903 return rc;
2904}
2905
2906
2907/**
2908 * Worker which calls everyone listening to the VM error messages.
2909 *
2910 * @param pUVM Pointer to the user mode VM structure.
2911 * @param rc The VBox status code.
2912 * @param RT_SRC_POS_DECL The source position of this error.
2913 * @param pszFormat Format string.
2914 * @param pArgs Pointer to the format arguments.
2915 * @thread EMT
2916 */
2917DECLCALLBACK(void) vmR3SetErrorUV(PUVM pUVM, int rc, RT_SRC_POS_DECL, const char *pszFormat, va_list *pArgs)
2918{
2919#ifdef LOG_ENABLED
2920 /*
2921 * Log the error.
2922 */
2923 RTLogPrintf("VMSetError: %s(%d) %s\n", pszFile, iLine, pszFunction);
2924 va_list va3;
2925 va_copy(va3, *pArgs);
2926 RTLogPrintfV(pszFormat, va3);
2927 va_end(va3);
2928 RTLogPrintf("\n");
2929#endif
2930
2931 /*
2932 * Make a copy of the message.
2933 */
2934 if (pUVM->pVM)
2935 vmSetErrorCopy(pUVM->pVM, rc, RT_SRC_POS_ARGS, pszFormat, *pArgs);
2936
2937 /*
2938 * Call the at error callbacks.
2939 */
2940 for (PVMATERROR pCur = pUVM->vm.s.pAtError; pCur; pCur = pCur->pNext)
2941 {
2942 va_list va2;
2943 va_copy(va2, *pArgs);
2944 pCur->pfnAtError(pUVM->pVM, pCur->pvUser, rc, RT_SRC_POS_ARGS, pszFormat, va2);
2945 va_end(va2);
2946 }
2947}
2948
2949
2950/**
2951 * Registers a VM runtime error callback.
2952 *
2953 * @returns VBox status code.
2954 * @param pVM The VM handle.
2955 * @param pfnAtRuntimeError Pointer to callback.
2956 * @param pvUser User argument.
2957 * @thread Any.
2958 */
2959VMMR3DECL(int) VMR3AtRuntimeErrorRegister(PVM pVM, PFNVMATRUNTIMEERROR pfnAtRuntimeError, void *pvUser)
2960{
2961 LogFlow(("VMR3AtRuntimeErrorRegister: pfnAtRuntimeError=%p pvUser=%p\n", pfnAtRuntimeError, pvUser));
2962
2963 /*
2964 * Validate input.
2965 */
2966 if (!pfnAtRuntimeError)
2967 {
2968 AssertMsgFailed(("callback is required\n"));
2969 return VERR_INVALID_PARAMETER;
2970 }
2971
2972 /*
2973 * Make sure we're in EMT (to avoid the logging).
2974 */
2975 PVMREQ pReq;
2976 int rc = VMR3ReqCall(pVM, VMREQDEST_ANY, &pReq, RT_INDEFINITE_WAIT, (PFNRT)vmR3AtRuntimeErrorRegisterU, 3, pVM->pUVM, pfnAtRuntimeError, pvUser);
2977 if (RT_FAILURE(rc))
2978 return rc;
2979 rc = pReq->iStatus;
2980 VMR3ReqFree(pReq);
2981
2982 LogFlow(("VMR3AtRuntimeErrorRegister: returns %Rrc\n", rc));
2983 return rc;
2984}
2985
2986
2987/**
2988 * Registers a VM runtime error callback.
2989 *
2990 * @returns VBox status code.
2991 * @param pUVM Pointer to the user mode VM structure.
2992 * @param pfnAtRuntimeError Pointer to callback.
2993 * @param pvUser User argument.
2994 * @thread EMT
2995 */
2996static DECLCALLBACK(int) vmR3AtRuntimeErrorRegisterU(PUVM pUVM, PFNVMATRUNTIMEERROR pfnAtRuntimeError, void *pvUser)
2997{
2998 /*
2999 * Allocate a new record.
3000 */
3001
3002 PVMATRUNTIMEERROR pNew = (PVMATRUNTIMEERROR)MMR3HeapAllocU(pUVM, MM_TAG_VM, sizeof(*pNew));
3003 if (!pNew)
3004 return VERR_NO_MEMORY;
3005
3006 /* fill */
3007 pNew->pfnAtRuntimeError = pfnAtRuntimeError;
3008 pNew->pvUser = pvUser;
3009
3010 /* insert */
3011 pNew->pNext = *pUVM->vm.s.ppAtRuntimeErrorNext;
3012 *pUVM->vm.s.ppAtRuntimeErrorNext = pNew;
3013 pUVM->vm.s.ppAtRuntimeErrorNext = &pNew->pNext;
3014
3015 return VINF_SUCCESS;
3016}
3017
3018
3019/**
3020 * Deregisters a VM runtime error callback.
3021 *
3022 * @returns VBox status code.
3023 * @param pVM The VM handle.
3024 * @param pfnAtRuntimeError Pointer to callback.
3025 * @param pvUser User argument.
3026 * @thread Any.
3027 */
3028VMMR3DECL(int) VMR3AtRuntimeErrorDeregister(PVM pVM, PFNVMATRUNTIMEERROR pfnAtRuntimeError, void *pvUser)
3029{
3030 LogFlow(("VMR3AtRuntimeErrorDeregister: pfnAtRuntimeError=%p pvUser=%p\n", pfnAtRuntimeError, pvUser));
3031
3032 /*
3033 * Validate input.
3034 */
3035 if (!pfnAtRuntimeError)
3036 {
3037 AssertMsgFailed(("callback is required\n"));
3038 return VERR_INVALID_PARAMETER;
3039 }
3040
3041 /*
3042 * Make sure we're in EMT (to avoid the logging).
3043 */
3044 PVMREQ pReq;
3045 int rc = VMR3ReqCall(pVM, VMREQDEST_ANY, &pReq, RT_INDEFINITE_WAIT, (PFNRT)vmR3AtRuntimeErrorDeregisterU, 3, pVM->pUVM, pfnAtRuntimeError, pvUser);
3046 if (RT_FAILURE(rc))
3047 return rc;
3048 rc = pReq->iStatus;
3049 VMR3ReqFree(pReq);
3050
3051 LogFlow(("VMR3AtRuntimeErrorDeregister: returns %Rrc\n", rc));
3052 return rc;
3053}
3054
3055
3056/**
3057 * Deregisters a VM runtime error callback.
3058 *
3059 * @returns VBox status code.
3060 * @param pUVM Pointer to the user mode VM structure.
3061 * @param pfnAtRuntimeError Pointer to callback.
3062 * @param pvUser User argument.
3063 * @thread EMT
3064 */
3065static DECLCALLBACK(int) vmR3AtRuntimeErrorDeregisterU(PUVM pUVM, PFNVMATRUNTIMEERROR pfnAtRuntimeError, void *pvUser)
3066{
3067 LogFlow(("vmR3AtRuntimeErrorDeregisterU: pfnAtRuntimeError=%p pvUser=%p\n", pfnAtRuntimeError, pvUser));
3068
3069 /*
3070 * Search the list for the entry.
3071 */
3072 PVMATRUNTIMEERROR pPrev = NULL;
3073 PVMATRUNTIMEERROR pCur = pUVM->vm.s.pAtRuntimeError;
3074 while ( pCur
3075 && ( pCur->pfnAtRuntimeError != pfnAtRuntimeError
3076 || pCur->pvUser != pvUser))
3077 {
3078 pPrev = pCur;
3079 pCur = pCur->pNext;
3080 }
3081 if (!pCur)
3082 {
3083 AssertMsgFailed(("pfnAtRuntimeError=%p was not found\n", pfnAtRuntimeError));
3084 return VERR_FILE_NOT_FOUND;
3085 }
3086
3087 /*
3088 * Unlink it.
3089 */
3090 if (pPrev)
3091 {
3092 pPrev->pNext = pCur->pNext;
3093 if (!pCur->pNext)
3094 pUVM->vm.s.ppAtRuntimeErrorNext = &pPrev->pNext;
3095 }
3096 else
3097 {
3098 pUVM->vm.s.pAtRuntimeError = pCur->pNext;
3099 if (!pCur->pNext)
3100 pUVM->vm.s.ppAtRuntimeErrorNext = &pUVM->vm.s.pAtRuntimeError;
3101 }
3102
3103 /*
3104 * Free it.
3105 */
3106 pCur->pfnAtRuntimeError = NULL;
3107 pCur->pNext = NULL;
3108 MMR3HeapFree(pCur);
3109
3110 return VINF_SUCCESS;
3111}
3112
3113
3114/**
3115 * Worker for VMR3SetRuntimeErrorWorker and vmR3SetRuntimeErrorV.
3116 *
3117 * This does the common parts after the error has been saved / retrieved.
3118 *
3119 * @returns VBox status code with modifications, see VMSetRuntimeErrorV.
3120 *
3121 * @param pVM The VM handle.
3122 * @param fFlags The error flags.
3123 * @param pszErrorId Error ID string.
3124 * @param pszFormat Format string.
3125 * @param pVa Pointer to the format arguments.
3126 */
3127static int vmR3SetRuntimeErrorCommon(PVM pVM, uint32_t fFlags, const char *pszErrorId, const char *pszFormat, va_list *pVa)
3128{
3129 LogRel(("VM: Raising runtime error '%s' (fFlags=%#x)\n", pszErrorId, fFlags));
3130
3131 /*
3132 * Take actions before the call.
3133 */
3134 int rc = VINF_SUCCESS;
3135 if (fFlags & VMSETRTERR_FLAGS_FATAL)
3136 /** @todo Add some special VM state for the FATAL variant that isn't resumable.
3137 * It's too risky for 2.2.0, do after branching. */
3138 rc = VMR3SuspendNoSave(pVM);
3139 else if (fFlags & VMSETRTERR_FLAGS_SUSPEND)
3140 rc = VMR3Suspend(pVM);
3141
3142 /*
3143 * Do the callback round.
3144 */
3145 for (PVMATRUNTIMEERROR pCur = pVM->pUVM->vm.s.pAtRuntimeError; pCur; pCur = pCur->pNext)
3146 {
3147 va_list va;
3148 va_copy(va, *pVa);
3149 pCur->pfnAtRuntimeError(pVM, pCur->pvUser, fFlags, pszErrorId, pszFormat, va);
3150 va_end(va);
3151 }
3152
3153 return rc;
3154}
3155
3156
3157/**
3158 * Ellipsis to va_list wrapper for calling vmR3SetRuntimeErrorCommon.
3159 */
3160static int vmR3SetRuntimeErrorCommonF(PVM pVM, uint32_t fFlags, const char *pszErrorId, const char *pszFormat, ...)
3161{
3162 va_list va;
3163 va_start(va, pszFormat);
3164 int rc = vmR3SetRuntimeErrorCommon(pVM, fFlags, pszErrorId, pszFormat, &va);
3165 va_end(va);
3166 return rc;
3167}
3168
3169
3170/**
3171 * This is a worker function for RC and Ring-0 calls to VMSetError and
3172 * VMSetErrorV.
3173 *
3174 * The message is found in VMINT.
3175 *
3176 * @returns VBox status code, see VMSetRuntimeError.
3177 * @param pVM The VM handle.
3178 * @thread EMT.
3179 */
3180VMMR3DECL(int) VMR3SetRuntimeErrorWorker(PVM pVM)
3181{
3182 VM_ASSERT_EMT(pVM);
3183 AssertReleaseMsgFailed(("And we have a winner! You get to implement Ring-0 and GC VMSetRuntimeErrorV! Congrats!\n"));
3184
3185 /*
3186 * Unpack the error (if we managed to format one).
3187 */
3188 const char *pszErrorId = "SetRuntimeError";
3189 const char *pszMessage = "No message!";
3190 uint32_t fFlags = VMSETRTERR_FLAGS_FATAL;
3191 PVMRUNTIMEERROR pErr = pVM->vm.s.pRuntimeErrorR3;
3192 if (pErr)
3193 {
3194 AssertCompile(sizeof(const char) == sizeof(uint8_t));
3195 if (pErr->offErrorId)
3196 pszErrorId = (const char *)pErr + pErr->offErrorId;
3197 if (pErr->offMessage)
3198 pszMessage = (const char *)pErr + pErr->offMessage;
3199 fFlags = pErr->fFlags;
3200 }
3201
3202 /*
3203 * Join cause with vmR3SetRuntimeErrorV.
3204 */
3205 return vmR3SetRuntimeErrorCommonF(pVM, fFlags, pszErrorId, "%s", pszMessage);
3206}
3207
3208
3209/**
3210 * Worker for VMSetRuntimeErrorV for doing the job on EMT in ring-3.
3211 *
3212 * @returns VBox status code with modifications, see VMSetRuntimeErrorV.
3213 *
3214 * @param pVM The VM handle.
3215 * @param fFlags The error flags.
3216 * @param pszErrorId Error ID string.
3217 * @param pszFormat Format string.
3218 * @param pVa Pointer to the format arguments.
3219 *
3220 * @thread EMT
3221 */
3222DECLCALLBACK(int) vmR3SetRuntimeErrorV(PVM pVM, uint32_t fFlags, const char *pszErrorId, const char *pszFormat, va_list *pVa)
3223{
3224 /*
3225 * Make a copy of the message.
3226 */
3227 va_list va2;
3228 va_copy(va2, *pVa);
3229 vmSetRuntimeErrorCopy(pVM, fFlags, pszErrorId, pszFormat, va2);
3230 va_end(va2);
3231
3232 /*
3233 * Join paths with VMR3SetRuntimeErrorWorker.
3234 */
3235 return vmR3SetRuntimeErrorCommon(pVM, fFlags, pszErrorId, pszFormat, pVa);
3236}
3237
3238
3239/**
3240 * Returns the VMCPU id of the current EMT thread.
3241 *
3242 * @param pVM The VM handle.
3243 * @thread EMT
3244 */
3245VMMR3DECL(RTCPUID) VMR3GetVMCPUId(PVM pVM)
3246{
3247 PUVMCPU pUVMCPU = (PUVMCPU)RTTlsGet(pVM->pUVM->vm.s.idxTLS);
3248
3249 AssertMsg(pUVMCPU, ("RTTlsGet %d failed!\n", pVM->pUVM->vm.s.idxTLS));
3250 return pUVMCPU->idCpu;
3251}
3252
3253
3254/**
3255 * Returns the native handle of the current EMT VMCPU thread.
3256 *
3257 * @returns Handle if this is an EMT thread; NIL_RTNATIVETHREAD otherwise
3258 * @param pVM The VM handle.
3259 * @thread EMT
3260 */
3261VMMR3DECL(RTNATIVETHREAD) VMR3GetVMCPUNativeThread(PVM pVM)
3262{
3263 PUVMCPU pUVMCPU = (PUVMCPU)RTTlsGet(pVM->pUVM->vm.s.idxTLS);
3264
3265 if (!pUVMCPU)
3266 return NIL_RTNATIVETHREAD;
3267
3268 return pUVMCPU->vm.s.NativeThreadEMT;
3269}
3270
3271
3272/**
3273 * Returns the native handle of the current EMT VMCPU thread.
3274 *
3275 * @returns Handle if this is an EMT thread; NIL_RTNATIVETHREAD otherwise
3276 * @param pVM The VM handle.
3277 * @thread EMT
3278 */
3279VMMR3DECL(RTNATIVETHREAD) VMR3GetVMCPUNativeThreadU(PUVM pUVM)
3280{
3281 PUVMCPU pUVMCPU = (PUVMCPU)RTTlsGet(pUVM->vm.s.idxTLS);
3282
3283 if (!pUVMCPU)
3284 return NIL_RTNATIVETHREAD;
3285
3286 return pUVMCPU->vm.s.NativeThreadEMT;
3287}
3288
3289
3290/**
3291 * Returns the handle of the current EMT VMCPU thread.
3292 *
3293 * @returns Handle if this is an EMT thread; NIL_RTNATIVETHREAD otherwise
3294 * @param pVM The VM handle.
3295 * @thread EMT
3296 */
3297VMMR3DECL(RTTHREAD) VMR3GetVMCPUThread(PVM pVM)
3298{
3299 PUVMCPU pUVMCPU = (PUVMCPU)RTTlsGet(pVM->pUVM->vm.s.idxTLS);
3300
3301 if (!pUVMCPU)
3302 return NIL_RTTHREAD;
3303
3304 return pUVMCPU->vm.s.ThreadEMT;
3305}
3306
3307
3308/**
3309 * Returns the handle of the current EMT VMCPU thread.
3310 *
3311 * @returns Handle if this is an EMT thread; NIL_RTNATIVETHREAD otherwise
3312 * @param pVM The VM handle.
3313 * @thread EMT
3314 */
3315VMMR3DECL(RTTHREAD) VMR3GetVMCPUThreadU(PUVM pUVM)
3316{
3317 PUVMCPU pUVMCPU = (PUVMCPU)RTTlsGet(pUVM->vm.s.idxTLS);
3318
3319 if (!pUVMCPU)
3320 return NIL_RTTHREAD;
3321
3322 return pUVMCPU->vm.s.ThreadEMT;
3323}
3324
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