VirtualBox

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

Last change on this file since 32217 was 32206, checked in by vboxsync, 14 years ago

FT: no state changes for loading either

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