VirtualBox

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

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

VMM: State reworking.

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