VirtualBox

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

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

VM.cpp: Always write VMSetError messages to the release log. Main may delay logging them and confuse things.

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