VirtualBox

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

Last change on this file since 34904 was 34683, checked in by vboxsync, 14 years ago

VM: better error message about a missing device implementation

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