VirtualBox

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

Last change on this file since 33000 was 32885, checked in by vboxsync, 14 years ago

Renaming cpu priority to cpu execution cap

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 150.6 KB
Line 
1/* $Id: VM.cpp 32885 2010-10-04 12:56:35Z 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->uCpuExecutionCap == 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, "CpuExecutionCap", &pVM->uCpuExecutionCap, 100);
656 AssertLogRelMsgRC(rc, ("Configuration error: Querying \"CpuExecutionCap\" 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 bool fOldBuffered = RTLogRelSetBuffering(true /*fBuffered*/);
2182 RTLogRelPrintf("****************** Guest state at power off ******************\n");
2183 DBGFR3Info(pVM, "cpumguest", "verbose", DBGFR3InfoLogRelHlp());
2184 RTLogRelPrintf("***\n");
2185 DBGFR3Info(pVM, "mode", NULL, DBGFR3InfoLogRelHlp());
2186 RTLogRelPrintf("***\n");
2187 DBGFR3Info(pVM, "activetimers", NULL, DBGFR3InfoLogRelHlp());
2188 RTLogRelPrintf("***\n");
2189 DBGFR3Info(pVM, "gdt", NULL, DBGFR3InfoLogRelHlp());
2190 /** @todo dump guest call stack. */
2191#if 1 // "temporary" while debugging #1589
2192 RTLogRelPrintf("***\n");
2193 uint32_t esp = CPUMGetGuestESP(pVCpu);
2194 if ( CPUMGetGuestSS(pVCpu) == 0
2195 && esp < _64K)
2196 {
2197 uint8_t abBuf[PAGE_SIZE];
2198 RTLogRelPrintf("***\n"
2199 "ss:sp=0000:%04x ", esp);
2200 uint32_t Start = esp & ~(uint32_t)63;
2201 int rc = PGMPhysSimpleReadGCPhys(pVM, abBuf, Start, 0x100);
2202 if (RT_SUCCESS(rc))
2203 RTLogRelPrintf("0000:%04x TO 0000:%04x:\n"
2204 "%.*Rhxd\n",
2205 Start, Start + 0x100 - 1,
2206 0x100, abBuf);
2207 else
2208 RTLogRelPrintf("rc=%Rrc\n", rc);
2209
2210 /* grub ... */
2211 if (esp < 0x2000 && esp > 0x1fc0)
2212 {
2213 rc = PGMPhysSimpleReadGCPhys(pVM, abBuf, 0x8000, 0x800);
2214 if (RT_SUCCESS(rc))
2215 RTLogRelPrintf("0000:8000 TO 0000:87ff:\n"
2216 "%.*Rhxd\n",
2217 0x800, abBuf);
2218 }
2219 /* microsoft cdrom hang ... */
2220 if (true)
2221 {
2222 rc = PGMPhysSimpleReadGCPhys(pVM, abBuf, 0x8000, 0x200);
2223 if (RT_SUCCESS(rc))
2224 RTLogRelPrintf("2000:0000 TO 2000:01ff:\n"
2225 "%.*Rhxd\n",
2226 0x200, abBuf);
2227 }
2228 }
2229#endif
2230 RTLogRelSetBuffering(fOldBuffered);
2231 RTLogRelPrintf("************** End of Guest state at power off ***************\n");
2232 }
2233
2234 /*
2235 * Perform the power off notifications and advance the state to
2236 * Off or OffLS.
2237 */
2238 PDMR3PowerOff(pVM);
2239
2240 PUVM pUVM = pVM->pUVM;
2241 RTCritSectEnter(&pUVM->vm.s.AtStateCritSect);
2242 enmVMState = pVM->enmVMState;
2243 if (enmVMState == VMSTATE_POWERING_OFF_LS)
2244 vmR3SetStateLocked(pVM, pUVM, VMSTATE_OFF_LS, VMSTATE_POWERING_OFF_LS);
2245 else
2246 vmR3SetStateLocked(pVM, pUVM, VMSTATE_OFF, VMSTATE_POWERING_OFF);
2247 RTCritSectLeave(&pUVM->vm.s.AtStateCritSect);
2248 }
2249 return VINF_EM_OFF;
2250}
2251
2252
2253/**
2254 * Power off the VM.
2255 *
2256 * @returns VBox status code. When called on EMT, this will be a strict status
2257 * code that has to be propagated up the call stack.
2258 *
2259 * @param pVM The handle of the VM to be powered off.
2260 *
2261 * @thread Any thread.
2262 * @vmstate Suspended, Running, Guru Meditation, Load Failure
2263 * @vmstateto Off or OffLS
2264 */
2265VMMR3DECL(int) VMR3PowerOff(PVM pVM)
2266{
2267 LogFlow(("VMR3PowerOff: pVM=%p\n", pVM));
2268 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
2269
2270 /*
2271 * Gather all the EMTs to make sure there are no races before
2272 * changing the VM state.
2273 */
2274 int rc = VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_DESCENDING | VMMEMTRENDEZVOUS_FLAGS_STOP_ON_ERROR,
2275 vmR3PowerOff, NULL);
2276 LogFlow(("VMR3PowerOff: returns %Rrc\n", rc));
2277 return rc;
2278}
2279
2280
2281/**
2282 * Destroys the VM.
2283 *
2284 * The VM must be powered off (or never really powered on) to call this
2285 * function. The VM handle is destroyed and can no longer be used up successful
2286 * return.
2287 *
2288 * @returns VBox status code.
2289 *
2290 * @param pVM The handle of the VM which should be destroyed.
2291 *
2292 * @thread Any none emulation thread.
2293 * @vmstate Off, Created
2294 * @vmstateto N/A
2295 */
2296VMMR3DECL(int) VMR3Destroy(PVM pVM)
2297{
2298 LogFlow(("VMR3Destroy: pVM=%p\n", pVM));
2299
2300 /*
2301 * Validate input.
2302 */
2303 if (!pVM)
2304 return VERR_INVALID_PARAMETER;
2305 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
2306 AssertLogRelReturn(!VM_IS_EMT(pVM), VERR_VM_THREAD_IS_EMT);
2307
2308 /*
2309 * Change VM state to destroying and unlink the VM.
2310 */
2311 int rc = vmR3TrySetState(pVM, "VMR3Destroy", 1, VMSTATE_DESTROYING, VMSTATE_OFF);
2312 if (RT_FAILURE(rc))
2313 return rc;
2314
2315 /** @todo lock this when we start having multiple machines in a process... */
2316 PUVM pUVM = pVM->pUVM; AssertPtr(pUVM);
2317 if (g_pUVMsHead == pUVM)
2318 g_pUVMsHead = pUVM->pNext;
2319 else
2320 {
2321 PUVM pPrev = g_pUVMsHead;
2322 while (pPrev && pPrev->pNext != pUVM)
2323 pPrev = pPrev->pNext;
2324 AssertMsgReturn(pPrev, ("pUVM=%p / pVM=%p is INVALID!\n", pUVM, pVM), VERR_INVALID_PARAMETER);
2325
2326 pPrev->pNext = pUVM->pNext;
2327 }
2328 pUVM->pNext = NULL;
2329
2330 /*
2331 * Notify registered at destruction listeners.
2332 */
2333 vmR3AtDtor(pVM);
2334
2335 /*
2336 * Call vmR3Destroy on each of the EMTs ending with EMT(0) doing the bulk
2337 * of the cleanup.
2338 */
2339 /* vmR3Destroy on all EMTs, ending with EMT(0). */
2340 rc = VMR3ReqCallWaitU(pUVM, VMCPUID_ALL_REVERSE, (PFNRT)vmR3Destroy, 1, pVM);
2341 AssertLogRelRC(rc);
2342
2343 /* Wait for EMTs and destroy the UVM. */
2344 vmR3DestroyUVM(pUVM, 30000);
2345
2346 LogFlow(("VMR3Destroy: returns VINF_SUCCESS\n"));
2347 return VINF_SUCCESS;
2348}
2349
2350
2351/**
2352 * Internal destruction worker.
2353 *
2354 * This is either called from VMR3Destroy via VMR3ReqCallU or from
2355 * vmR3EmulationThreadWithId when EMT(0) terminates after having called
2356 * VMR3Destroy().
2357 *
2358 * When called on EMT(0), it will performed the great bulk of the destruction.
2359 * When called on the other EMTs, they will do nothing and the whole purpose is
2360 * to return VINF_EM_TERMINATE so they break out of their run loops.
2361 *
2362 * @returns VINF_EM_TERMINATE.
2363 * @param pVM The VM handle.
2364 */
2365DECLCALLBACK(int) vmR3Destroy(PVM pVM)
2366{
2367 PUVM pUVM = pVM->pUVM;
2368 PVMCPU pVCpu = VMMGetCpu(pVM);
2369 Assert(pVCpu);
2370 LogFlow(("vmR3Destroy: pVM=%p pUVM=%p pVCpu=%p idCpu=%u\n", pVM, pUVM, pVCpu, pVCpu->idCpu));
2371
2372 /*
2373 * Only VCPU 0 does the full cleanup (last).
2374 */
2375 if (pVCpu->idCpu == 0)
2376 {
2377 /*
2378 * Dump statistics to the log.
2379 */
2380#if defined(VBOX_WITH_STATISTICS) || defined(LOG_ENABLED)
2381 RTLogFlags(NULL, "nodisabled nobuffered");
2382#endif
2383#ifdef VBOX_WITH_STATISTICS
2384 STAMR3Dump(pVM, "*");
2385#else
2386 LogRel(("************************* Statistics *************************\n"));
2387 STAMR3DumpToReleaseLog(pVM, "*");
2388 LogRel(("********************* End of statistics **********************\n"));
2389#endif
2390
2391 /*
2392 * Destroy the VM components.
2393 */
2394 int rc = TMR3Term(pVM);
2395 AssertRC(rc);
2396#ifdef VBOX_WITH_DEBUGGER
2397 rc = DBGCTcpTerminate(pVM, pUVM->vm.s.pvDBGC);
2398 pUVM->vm.s.pvDBGC = NULL;
2399#endif
2400 AssertRC(rc);
2401 rc = FTMR3Term(pVM);
2402 AssertRC(rc);
2403 rc = DBGFR3Term(pVM);
2404 AssertRC(rc);
2405 rc = PDMR3Term(pVM);
2406 AssertRC(rc);
2407 rc = EMR3Term(pVM);
2408 AssertRC(rc);
2409 rc = IOMR3Term(pVM);
2410 AssertRC(rc);
2411 rc = CSAMR3Term(pVM);
2412 AssertRC(rc);
2413 rc = PATMR3Term(pVM);
2414 AssertRC(rc);
2415 rc = TRPMR3Term(pVM);
2416 AssertRC(rc);
2417 rc = SELMR3Term(pVM);
2418 AssertRC(rc);
2419 rc = REMR3Term(pVM);
2420 AssertRC(rc);
2421 rc = HWACCMR3Term(pVM);
2422 AssertRC(rc);
2423 rc = PGMR3Term(pVM);
2424 AssertRC(rc);
2425 rc = VMMR3Term(pVM); /* Terminates the ring-0 code! */
2426 AssertRC(rc);
2427 rc = CPUMR3Term(pVM);
2428 AssertRC(rc);
2429 SSMR3Term(pVM);
2430 rc = PDMR3CritSectTerm(pVM);
2431 AssertRC(rc);
2432 rc = MMR3Term(pVM);
2433 AssertRC(rc);
2434
2435 /*
2436 * We're done, tell the other EMTs to quit.
2437 */
2438 ASMAtomicUoWriteBool(&pUVM->vm.s.fTerminateEMT, true);
2439 ASMAtomicWriteU32(&pVM->fGlobalForcedActions, VM_FF_CHECK_VM_STATE); /* Can't hurt... */
2440 LogFlow(("vmR3Destroy: returning %Rrc\n", VINF_EM_TERMINATE));
2441 }
2442 return VINF_EM_TERMINATE;
2443}
2444
2445
2446/**
2447 * Destroys the UVM portion.
2448 *
2449 * This is called as the final step in the VM destruction or as the cleanup
2450 * in case of a creation failure.
2451 *
2452 * @param pVM VM Handle.
2453 * @param cMilliesEMTWait The number of milliseconds to wait for the emulation
2454 * threads.
2455 */
2456static void vmR3DestroyUVM(PUVM pUVM, uint32_t cMilliesEMTWait)
2457{
2458 /*
2459 * Signal termination of each the emulation threads and
2460 * wait for them to complete.
2461 */
2462 /* Signal them. */
2463 ASMAtomicUoWriteBool(&pUVM->vm.s.fTerminateEMT, true);
2464 if (pUVM->pVM)
2465 VM_FF_SET(pUVM->pVM, VM_FF_CHECK_VM_STATE); /* Can't hurt... */
2466 for (VMCPUID i = 0; i < pUVM->cCpus; i++)
2467 {
2468 VMR3NotifyGlobalFFU(pUVM, VMNOTIFYFF_FLAGS_DONE_REM);
2469 RTSemEventSignal(pUVM->aCpus[i].vm.s.EventSemWait);
2470 }
2471
2472 /* Wait for them. */
2473 uint64_t NanoTS = RTTimeNanoTS();
2474 RTTHREAD hSelf = RTThreadSelf();
2475 ASMAtomicUoWriteBool(&pUVM->vm.s.fTerminateEMT, true);
2476 for (VMCPUID i = 0; i < pUVM->cCpus; i++)
2477 {
2478 RTTHREAD hThread = pUVM->aCpus[i].vm.s.ThreadEMT;
2479 if ( hThread != NIL_RTTHREAD
2480 && hThread != hSelf)
2481 {
2482 uint64_t cMilliesElapsed = (RTTimeNanoTS() - NanoTS) / 1000000;
2483 int rc2 = RTThreadWait(hThread,
2484 cMilliesElapsed < cMilliesEMTWait
2485 ? RT_MAX(cMilliesEMTWait - cMilliesElapsed, 2000)
2486 : 2000,
2487 NULL);
2488 if (rc2 == VERR_TIMEOUT) /* avoid the assertion when debugging. */
2489 rc2 = RTThreadWait(hThread, 1000, NULL);
2490 AssertLogRelMsgRC(rc2, ("i=%u rc=%Rrc\n", i, rc2));
2491 if (RT_SUCCESS(rc2))
2492 pUVM->aCpus[0].vm.s.ThreadEMT = NIL_RTTHREAD;
2493 }
2494 }
2495
2496 /* Cleanup the semaphores. */
2497 for (VMCPUID i = 0; i < pUVM->cCpus; i++)
2498 {
2499 RTSemEventDestroy(pUVM->aCpus[i].vm.s.EventSemWait);
2500 pUVM->aCpus[i].vm.s.EventSemWait = NIL_RTSEMEVENT;
2501 }
2502
2503 /*
2504 * Free the event semaphores associated with the request packets.
2505 */
2506 unsigned cReqs = 0;
2507 for (unsigned i = 0; i < RT_ELEMENTS(pUVM->vm.s.apReqFree); i++)
2508 {
2509 PVMREQ pReq = pUVM->vm.s.apReqFree[i];
2510 pUVM->vm.s.apReqFree[i] = NULL;
2511 for (; pReq; pReq = pReq->pNext, cReqs++)
2512 {
2513 pReq->enmState = VMREQSTATE_INVALID;
2514 RTSemEventDestroy(pReq->EventSem);
2515 }
2516 }
2517 Assert(cReqs == pUVM->vm.s.cReqFree); NOREF(cReqs);
2518
2519 /*
2520 * Kill all queued requests. (There really shouldn't be any!)
2521 */
2522 for (unsigned i = 0; i < 10; i++)
2523 {
2524 PVMREQ pReqHead = ASMAtomicXchgPtrT(&pUVM->vm.s.pReqs, NULL, PVMREQ);
2525 AssertMsg(!pReqHead, ("This isn't supposed to happen! VMR3Destroy caller has to serialize this.\n"));
2526 if (!pReqHead)
2527 break;
2528 for (PVMREQ pReq = pReqHead; pReq; pReq = pReq->pNext)
2529 {
2530 ASMAtomicUoWriteSize(&pReq->iStatus, VERR_INTERNAL_ERROR);
2531 ASMAtomicWriteSize(&pReq->enmState, VMREQSTATE_INVALID);
2532 RTSemEventSignal(pReq->EventSem);
2533 RTThreadSleep(2);
2534 RTSemEventDestroy(pReq->EventSem);
2535 }
2536 /* give them a chance to respond before we free the request memory. */
2537 RTThreadSleep(32);
2538 }
2539
2540 /*
2541 * Now all queued VCPU requests (again, there shouldn't be any).
2542 */
2543 for (VMCPUID idCpu = 0; idCpu < pUVM->cCpus; idCpu++)
2544 {
2545 PUVMCPU pUVCpu = &pUVM->aCpus[idCpu];
2546
2547 for (unsigned i = 0; i < 10; i++)
2548 {
2549 PVMREQ pReqHead = ASMAtomicXchgPtrT(&pUVCpu->vm.s.pReqs, NULL, PVMREQ);
2550 AssertMsg(!pReqHead, ("This isn't supposed to happen! VMR3Destroy caller has to serialize this.\n"));
2551 if (!pReqHead)
2552 break;
2553 for (PVMREQ pReq = pReqHead; pReq; pReq = pReq->pNext)
2554 {
2555 ASMAtomicUoWriteSize(&pReq->iStatus, VERR_INTERNAL_ERROR);
2556 ASMAtomicWriteSize(&pReq->enmState, VMREQSTATE_INVALID);
2557 RTSemEventSignal(pReq->EventSem);
2558 RTThreadSleep(2);
2559 RTSemEventDestroy(pReq->EventSem);
2560 }
2561 /* give them a chance to respond before we free the request memory. */
2562 RTThreadSleep(32);
2563 }
2564 }
2565
2566 /*
2567 * Make sure the VMMR0.r0 module and whatever else is unloaded.
2568 */
2569 PDMR3TermUVM(pUVM);
2570
2571 /*
2572 * Terminate the support library if initialized.
2573 */
2574 if (pUVM->vm.s.pSession)
2575 {
2576 int rc = SUPR3Term(false /*fForced*/);
2577 AssertRC(rc);
2578 pUVM->vm.s.pSession = NIL_RTR0PTR;
2579 }
2580
2581 /*
2582 * Destroy the MM heap and free the UVM structure.
2583 */
2584 MMR3TermUVM(pUVM);
2585 STAMR3TermUVM(pUVM);
2586
2587#ifdef LOG_ENABLED
2588 RTLogSetCustomPrefixCallback(NULL, NULL, NULL);
2589#endif
2590 RTTlsFree(pUVM->vm.s.idxTLS);
2591
2592 ASMAtomicUoWriteU32(&pUVM->u32Magic, UINT32_MAX);
2593 RTMemPageFree(pUVM, sizeof(*pUVM));
2594
2595 RTLogFlush(NULL);
2596}
2597
2598
2599/**
2600 * Enumerates the VMs in this process.
2601 *
2602 * @returns Pointer to the next VM.
2603 * @returns NULL when no more VMs.
2604 * @param pVMPrev The previous VM
2605 * Use NULL to start the enumeration.
2606 */
2607VMMR3DECL(PVM) VMR3EnumVMs(PVM pVMPrev)
2608{
2609 /*
2610 * This is quick and dirty. It has issues with VM being
2611 * destroyed during the enumeration.
2612 */
2613 PUVM pNext;
2614 if (pVMPrev)
2615 pNext = pVMPrev->pUVM->pNext;
2616 else
2617 pNext = g_pUVMsHead;
2618 return pNext ? pNext->pVM : NULL;
2619}
2620
2621
2622/**
2623 * Registers an at VM destruction callback.
2624 *
2625 * @returns VBox status code.
2626 * @param pfnAtDtor Pointer to callback.
2627 * @param pvUser User argument.
2628 */
2629VMMR3DECL(int) VMR3AtDtorRegister(PFNVMATDTOR pfnAtDtor, void *pvUser)
2630{
2631 /*
2632 * Check if already registered.
2633 */
2634 VM_ATDTOR_LOCK();
2635 PVMATDTOR pCur = g_pVMAtDtorHead;
2636 while (pCur)
2637 {
2638 if (pfnAtDtor == pCur->pfnAtDtor)
2639 {
2640 VM_ATDTOR_UNLOCK();
2641 AssertMsgFailed(("Already registered at destruction callback %p!\n", pfnAtDtor));
2642 return VERR_INVALID_PARAMETER;
2643 }
2644
2645 /* next */
2646 pCur = pCur->pNext;
2647 }
2648 VM_ATDTOR_UNLOCK();
2649
2650 /*
2651 * Allocate new entry.
2652 */
2653 PVMATDTOR pVMAtDtor = (PVMATDTOR)RTMemAlloc(sizeof(*pVMAtDtor));
2654 if (!pVMAtDtor)
2655 return VERR_NO_MEMORY;
2656
2657 VM_ATDTOR_LOCK();
2658 pVMAtDtor->pfnAtDtor = pfnAtDtor;
2659 pVMAtDtor->pvUser = pvUser;
2660 pVMAtDtor->pNext = g_pVMAtDtorHead;
2661 g_pVMAtDtorHead = pVMAtDtor;
2662 VM_ATDTOR_UNLOCK();
2663
2664 return VINF_SUCCESS;
2665}
2666
2667
2668/**
2669 * Deregisters an at VM destruction callback.
2670 *
2671 * @returns VBox status code.
2672 * @param pfnAtDtor Pointer to callback.
2673 */
2674VMMR3DECL(int) VMR3AtDtorDeregister(PFNVMATDTOR pfnAtDtor)
2675{
2676 /*
2677 * Find it, unlink it and free it.
2678 */
2679 VM_ATDTOR_LOCK();
2680 PVMATDTOR pPrev = NULL;
2681 PVMATDTOR pCur = g_pVMAtDtorHead;
2682 while (pCur)
2683 {
2684 if (pfnAtDtor == pCur->pfnAtDtor)
2685 {
2686 if (pPrev)
2687 pPrev->pNext = pCur->pNext;
2688 else
2689 g_pVMAtDtorHead = pCur->pNext;
2690 pCur->pNext = NULL;
2691 VM_ATDTOR_UNLOCK();
2692
2693 RTMemFree(pCur);
2694 return VINF_SUCCESS;
2695 }
2696
2697 /* next */
2698 pPrev = pCur;
2699 pCur = pCur->pNext;
2700 }
2701 VM_ATDTOR_UNLOCK();
2702
2703 return VERR_INVALID_PARAMETER;
2704}
2705
2706
2707/**
2708 * Walks the list of at VM destructor callbacks.
2709 * @param pVM The VM which is about to be destroyed.
2710 */
2711static void vmR3AtDtor(PVM pVM)
2712{
2713 /*
2714 * Find it, unlink it and free it.
2715 */
2716 VM_ATDTOR_LOCK();
2717 for (PVMATDTOR pCur = g_pVMAtDtorHead; pCur; pCur = pCur->pNext)
2718 pCur->pfnAtDtor(pVM, pCur->pvUser);
2719 VM_ATDTOR_UNLOCK();
2720}
2721
2722
2723/**
2724 * Worker which checks integrity of some internal structures.
2725 * This is yet another attempt to track down that AVL tree crash.
2726 */
2727static void vmR3CheckIntegrity(PVM pVM)
2728{
2729#ifdef VBOX_STRICT
2730 int rc = PGMR3CheckIntegrity(pVM);
2731 AssertReleaseRC(rc);
2732#endif
2733}
2734
2735
2736/**
2737 * EMT rendezvous worker for VMR3Reset.
2738 *
2739 * This is called by the emulation threads as a response to the reset request
2740 * issued by VMR3Reset().
2741 *
2742 * @returns VERR_VM_INVALID_VM_STATE, VINF_EM_RESET or VINF_EM_SUSPEND. (This
2743 * is a strict return code, see FNVMMEMTRENDEZVOUS.)
2744 *
2745 * @param pVM The VM handle.
2746 * @param pVCpu The VMCPU handle of the EMT.
2747 * @param pvUser Ignored.
2748 */
2749static DECLCALLBACK(VBOXSTRICTRC) vmR3Reset(PVM pVM, PVMCPU pVCpu, void *pvUser)
2750{
2751 Assert(!pvUser); NOREF(pvUser);
2752
2753 /*
2754 * The first EMT will try change the state to resetting. If this fails,
2755 * we won't get called for the other EMTs.
2756 */
2757 if (pVCpu->idCpu == pVM->cCpus - 1)
2758 {
2759 int rc = vmR3TrySetState(pVM, "VMR3Reset", 3,
2760 VMSTATE_RESETTING, VMSTATE_RUNNING,
2761 VMSTATE_RESETTING, VMSTATE_SUSPENDED,
2762 VMSTATE_RESETTING_LS, VMSTATE_RUNNING_LS);
2763 if (RT_FAILURE(rc))
2764 return rc;
2765 }
2766
2767 /*
2768 * Check the state.
2769 */
2770 VMSTATE enmVMState = VMR3GetState(pVM);
2771 AssertLogRelMsgReturn( enmVMState == VMSTATE_RESETTING
2772 || enmVMState == VMSTATE_RESETTING_LS,
2773 ("%s\n", VMR3GetStateName(enmVMState)),
2774 VERR_INTERNAL_ERROR_4);
2775
2776 /*
2777 * EMT(0) does the full cleanup *after* all the other EMTs has been
2778 * thru here and been told to enter the EMSTATE_WAIT_SIPI state.
2779 *
2780 * Because there are per-cpu reset routines and order may/is important,
2781 * the following sequence looks a bit ugly...
2782 */
2783 if (pVCpu->idCpu == 0)
2784 vmR3CheckIntegrity(pVM);
2785
2786 /* Reset the VCpu state. */
2787 VMCPU_ASSERT_STATE(pVCpu, VMCPUSTATE_STARTED);
2788
2789 /* Clear all pending forced actions. */
2790 VMCPU_FF_CLEAR(pVCpu, VMCPU_FF_ALL_MASK & ~VMCPU_FF_REQUEST);
2791
2792 /*
2793 * Reset the VM components.
2794 */
2795 if (pVCpu->idCpu == 0)
2796 {
2797 PATMR3Reset(pVM);
2798 CSAMR3Reset(pVM);
2799 PGMR3Reset(pVM); /* We clear VM RAM in PGMR3Reset. It's vital PDMR3Reset is executed
2800 * _afterwards_. E.g. ACPI sets up RAM tables during init/reset. */
2801/** @todo PGMR3Reset should be called after PDMR3Reset really, because we'll trash OS <-> hardware
2802 * communication structures residing in RAM when done in the other order. I.e. the device must be
2803 * quiesced first, then we clear the memory and plan tables. Probably have to make these things
2804 * explicit in some way, some memory setup pass or something.
2805 * (Example: DevAHCI may assert if memory is zeroed before it've read the FIS.)
2806 *
2807 * @bugref{4467}
2808 */
2809 MMR3Reset(pVM);
2810 PDMR3Reset(pVM);
2811 SELMR3Reset(pVM);
2812 TRPMR3Reset(pVM);
2813 REMR3Reset(pVM);
2814 IOMR3Reset(pVM);
2815 CPUMR3Reset(pVM);
2816 }
2817 CPUMR3ResetCpu(pVCpu);
2818 if (pVCpu->idCpu == 0)
2819 {
2820 TMR3Reset(pVM);
2821 EMR3Reset(pVM);
2822 HWACCMR3Reset(pVM); /* This must come *after* PATM, CSAM, CPUM, SELM and TRPM. */
2823
2824#ifdef LOG_ENABLED
2825 /*
2826 * Debug logging.
2827 */
2828 RTLogPrintf("\n\nThe VM was reset:\n");
2829 DBGFR3Info(pVM, "cpum", "verbose", NULL);
2830#endif
2831
2832 /*
2833 * Since EMT(0) is the last to go thru here, it will advance the state.
2834 * When a live save is active, we will move on to SuspendingLS but
2835 * leave it for VMR3Reset to do the actual suspending due to deadlock risks.
2836 */
2837 PUVM pUVM = pVM->pUVM;
2838 RTCritSectEnter(&pUVM->vm.s.AtStateCritSect);
2839 enmVMState = pVM->enmVMState;
2840 if (enmVMState == VMSTATE_RESETTING)
2841 {
2842 if (pUVM->vm.s.enmPrevVMState == VMSTATE_SUSPENDED)
2843 vmR3SetStateLocked(pVM, pUVM, VMSTATE_SUSPENDED, VMSTATE_RESETTING);
2844 else
2845 vmR3SetStateLocked(pVM, pUVM, VMSTATE_RUNNING, VMSTATE_RESETTING);
2846 }
2847 else
2848 vmR3SetStateLocked(pVM, pUVM, VMSTATE_SUSPENDING_LS, VMSTATE_RESETTING_LS);
2849 RTCritSectLeave(&pUVM->vm.s.AtStateCritSect);
2850
2851 vmR3CheckIntegrity(pVM);
2852
2853 /*
2854 * Do the suspend bit as well.
2855 * It only requires some EMT(0) work at present.
2856 */
2857 if (enmVMState != VMSTATE_RESETTING)
2858 {
2859 vmR3SuspendDoWork(pVM);
2860 vmR3SetState(pVM, VMSTATE_SUSPENDED_LS, VMSTATE_SUSPENDING_LS);
2861 }
2862 }
2863
2864 return enmVMState == VMSTATE_RESETTING
2865 ? VINF_EM_RESET
2866 : 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. */
2867}
2868
2869
2870/**
2871 * Reset the current VM.
2872 *
2873 * @returns VBox status code.
2874 * @param pVM VM to reset.
2875 */
2876VMMR3DECL(int) VMR3Reset(PVM pVM)
2877{
2878 LogFlow(("VMR3Reset:\n"));
2879 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
2880
2881 /*
2882 * Gather all the EMTs to make sure there are no races before
2883 * changing the VM state.
2884 */
2885 int rc = VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_DESCENDING | VMMEMTRENDEZVOUS_FLAGS_STOP_ON_ERROR,
2886 vmR3Reset, NULL);
2887 LogFlow(("VMR3Reset: returns %Rrc\n", rc));
2888 return rc;
2889}
2890
2891
2892/**
2893 * Gets the current VM state.
2894 *
2895 * @returns The current VM state.
2896 * @param pVM VM handle.
2897 * @thread Any
2898 */
2899VMMR3DECL(VMSTATE) VMR3GetState(PVM pVM)
2900{
2901 return pVM->enmVMState;
2902}
2903
2904
2905/**
2906 * Gets the state name string for a VM state.
2907 *
2908 * @returns Pointer to the state name. (readonly)
2909 * @param enmState The state.
2910 */
2911VMMR3DECL(const char *) VMR3GetStateName(VMSTATE enmState)
2912{
2913 switch (enmState)
2914 {
2915 case VMSTATE_CREATING: return "CREATING";
2916 case VMSTATE_CREATED: return "CREATED";
2917 case VMSTATE_LOADING: return "LOADING";
2918 case VMSTATE_POWERING_ON: return "POWERING_ON";
2919 case VMSTATE_RESUMING: return "RESUMING";
2920 case VMSTATE_RUNNING: return "RUNNING";
2921 case VMSTATE_RUNNING_LS: return "RUNNING_LS";
2922 case VMSTATE_RUNNING_FT: return "RUNNING_FT";
2923 case VMSTATE_RESETTING: return "RESETTING";
2924 case VMSTATE_RESETTING_LS: return "RESETTING_LS";
2925 case VMSTATE_SUSPENDED: return "SUSPENDED";
2926 case VMSTATE_SUSPENDED_LS: return "SUSPENDED_LS";
2927 case VMSTATE_SUSPENDED_EXT_LS: return "SUSPENDED_EXT_LS";
2928 case VMSTATE_SUSPENDING: return "SUSPENDING";
2929 case VMSTATE_SUSPENDING_LS: return "SUSPENDING_LS";
2930 case VMSTATE_SUSPENDING_EXT_LS: return "SUSPENDING_EXT_LS";
2931 case VMSTATE_SAVING: return "SAVING";
2932 case VMSTATE_DEBUGGING: return "DEBUGGING";
2933 case VMSTATE_DEBUGGING_LS: return "DEBUGGING_LS";
2934 case VMSTATE_POWERING_OFF: return "POWERING_OFF";
2935 case VMSTATE_POWERING_OFF_LS: return "POWERING_OFF_LS";
2936 case VMSTATE_FATAL_ERROR: return "FATAL_ERROR";
2937 case VMSTATE_FATAL_ERROR_LS: return "FATAL_ERROR_LS";
2938 case VMSTATE_GURU_MEDITATION: return "GURU_MEDITATION";
2939 case VMSTATE_GURU_MEDITATION_LS:return "GURU_MEDITATION_LS";
2940 case VMSTATE_LOAD_FAILURE: return "LOAD_FAILURE";
2941 case VMSTATE_OFF: return "OFF";
2942 case VMSTATE_OFF_LS: return "OFF_LS";
2943 case VMSTATE_DESTROYING: return "DESTROYING";
2944 case VMSTATE_TERMINATED: return "TERMINATED";
2945
2946 default:
2947 AssertMsgFailed(("Unknown state %d\n", enmState));
2948 return "Unknown!\n";
2949 }
2950}
2951
2952
2953/**
2954 * Validates the state transition in strict builds.
2955 *
2956 * @returns true if valid, false if not.
2957 *
2958 * @param enmStateOld The old (current) state.
2959 * @param enmStateNew The proposed new state.
2960 *
2961 * @remarks The reference for this is found in doc/vp/VMM.vpp, the VMSTATE
2962 * diagram (under State Machine Diagram).
2963 */
2964static bool vmR3ValidateStateTransition(VMSTATE enmStateOld, VMSTATE enmStateNew)
2965{
2966#ifdef VBOX_STRICT
2967 switch (enmStateOld)
2968 {
2969 case VMSTATE_CREATING:
2970 AssertMsgReturn(enmStateNew == VMSTATE_CREATED, ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2971 break;
2972
2973 case VMSTATE_CREATED:
2974 AssertMsgReturn( enmStateNew == VMSTATE_LOADING
2975 || enmStateNew == VMSTATE_POWERING_ON
2976 || enmStateNew == VMSTATE_POWERING_OFF
2977 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2978 break;
2979
2980 case VMSTATE_LOADING:
2981 AssertMsgReturn( enmStateNew == VMSTATE_SUSPENDED
2982 || enmStateNew == VMSTATE_LOAD_FAILURE
2983 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2984 break;
2985
2986 case VMSTATE_POWERING_ON:
2987 AssertMsgReturn( enmStateNew == VMSTATE_RUNNING
2988 /*|| enmStateNew == VMSTATE_FATAL_ERROR ?*/
2989 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2990 break;
2991
2992 case VMSTATE_RESUMING:
2993 AssertMsgReturn( enmStateNew == VMSTATE_RUNNING
2994 /*|| enmStateNew == VMSTATE_FATAL_ERROR ?*/
2995 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
2996 break;
2997
2998 case VMSTATE_RUNNING:
2999 AssertMsgReturn( enmStateNew == VMSTATE_POWERING_OFF
3000 || enmStateNew == VMSTATE_SUSPENDING
3001 || enmStateNew == VMSTATE_RESETTING
3002 || enmStateNew == VMSTATE_RUNNING_LS
3003 || enmStateNew == VMSTATE_RUNNING_FT
3004 || enmStateNew == VMSTATE_DEBUGGING
3005 || enmStateNew == VMSTATE_FATAL_ERROR
3006 || enmStateNew == VMSTATE_GURU_MEDITATION
3007 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
3008 break;
3009
3010 case VMSTATE_RUNNING_LS:
3011 AssertMsgReturn( enmStateNew == VMSTATE_POWERING_OFF_LS
3012 || enmStateNew == VMSTATE_SUSPENDING_LS
3013 || enmStateNew == VMSTATE_SUSPENDING_EXT_LS
3014 || enmStateNew == VMSTATE_RESETTING_LS
3015 || enmStateNew == VMSTATE_RUNNING
3016 || enmStateNew == VMSTATE_DEBUGGING_LS
3017 || enmStateNew == VMSTATE_FATAL_ERROR_LS
3018 || enmStateNew == VMSTATE_GURU_MEDITATION_LS
3019 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
3020 break;
3021
3022 case VMSTATE_RUNNING_FT:
3023 AssertMsgReturn( enmStateNew == VMSTATE_POWERING_OFF
3024 || enmStateNew == VMSTATE_FATAL_ERROR
3025 || enmStateNew == VMSTATE_GURU_MEDITATION
3026 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
3027 break;
3028
3029 case VMSTATE_RESETTING:
3030 AssertMsgReturn(enmStateNew == VMSTATE_RUNNING, ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
3031 break;
3032
3033 case VMSTATE_RESETTING_LS:
3034 AssertMsgReturn( enmStateNew == VMSTATE_SUSPENDING_LS
3035 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
3036 break;
3037
3038 case VMSTATE_SUSPENDING:
3039 AssertMsgReturn(enmStateNew == VMSTATE_SUSPENDED, ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
3040 break;
3041
3042 case VMSTATE_SUSPENDING_LS:
3043 AssertMsgReturn( enmStateNew == VMSTATE_SUSPENDING
3044 || enmStateNew == VMSTATE_SUSPENDED_LS
3045 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
3046 break;
3047
3048 case VMSTATE_SUSPENDING_EXT_LS:
3049 AssertMsgReturn( enmStateNew == VMSTATE_SUSPENDING
3050 || enmStateNew == VMSTATE_SUSPENDED_EXT_LS
3051 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
3052 break;
3053
3054 case VMSTATE_SUSPENDED:
3055 AssertMsgReturn( enmStateNew == VMSTATE_POWERING_OFF
3056 || enmStateNew == VMSTATE_SAVING
3057 || enmStateNew == VMSTATE_RESETTING
3058 || enmStateNew == VMSTATE_RESUMING
3059 || enmStateNew == VMSTATE_LOADING
3060 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
3061 break;
3062
3063 case VMSTATE_SUSPENDED_LS:
3064 AssertMsgReturn( enmStateNew == VMSTATE_SUSPENDED
3065 || enmStateNew == VMSTATE_SAVING
3066 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
3067 break;
3068
3069 case VMSTATE_SUSPENDED_EXT_LS:
3070 AssertMsgReturn( enmStateNew == VMSTATE_SUSPENDED
3071 || enmStateNew == VMSTATE_SAVING
3072 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
3073 break;
3074
3075 case VMSTATE_SAVING:
3076 AssertMsgReturn(enmStateNew == VMSTATE_SUSPENDED, ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
3077 break;
3078
3079 case VMSTATE_DEBUGGING:
3080 AssertMsgReturn( enmStateNew == VMSTATE_RUNNING
3081 || enmStateNew == VMSTATE_POWERING_OFF
3082 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
3083 break;
3084
3085 case VMSTATE_DEBUGGING_LS:
3086 AssertMsgReturn( enmStateNew == VMSTATE_DEBUGGING
3087 || enmStateNew == VMSTATE_RUNNING_LS
3088 || enmStateNew == VMSTATE_POWERING_OFF_LS
3089 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
3090 break;
3091
3092 case VMSTATE_POWERING_OFF:
3093 AssertMsgReturn(enmStateNew == VMSTATE_OFF, ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
3094 break;
3095
3096 case VMSTATE_POWERING_OFF_LS:
3097 AssertMsgReturn( enmStateNew == VMSTATE_POWERING_OFF
3098 || enmStateNew == VMSTATE_OFF_LS
3099 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
3100 break;
3101
3102 case VMSTATE_OFF:
3103 AssertMsgReturn(enmStateNew == VMSTATE_DESTROYING, ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
3104 break;
3105
3106 case VMSTATE_OFF_LS:
3107 AssertMsgReturn(enmStateNew == VMSTATE_OFF, ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
3108 break;
3109
3110 case VMSTATE_FATAL_ERROR:
3111 AssertMsgReturn(enmStateNew == VMSTATE_POWERING_OFF, ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
3112 break;
3113
3114 case VMSTATE_FATAL_ERROR_LS:
3115 AssertMsgReturn( enmStateNew == VMSTATE_FATAL_ERROR
3116 || enmStateNew == VMSTATE_POWERING_OFF_LS
3117 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
3118 break;
3119
3120 case VMSTATE_GURU_MEDITATION:
3121 AssertMsgReturn( enmStateNew == VMSTATE_DEBUGGING
3122 || enmStateNew == VMSTATE_POWERING_OFF
3123 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
3124 break;
3125
3126 case VMSTATE_GURU_MEDITATION_LS:
3127 AssertMsgReturn( enmStateNew == VMSTATE_GURU_MEDITATION
3128 || enmStateNew == VMSTATE_DEBUGGING_LS
3129 || enmStateNew == VMSTATE_POWERING_OFF_LS
3130 , ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
3131 break;
3132
3133 case VMSTATE_LOAD_FAILURE:
3134 AssertMsgReturn(enmStateNew == VMSTATE_POWERING_OFF, ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
3135 break;
3136
3137 case VMSTATE_DESTROYING:
3138 AssertMsgReturn(enmStateNew == VMSTATE_TERMINATED, ("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
3139 break;
3140
3141 case VMSTATE_TERMINATED:
3142 default:
3143 AssertMsgFailedReturn(("%s -> %s\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)), false);
3144 break;
3145 }
3146#endif /* VBOX_STRICT */
3147 return true;
3148}
3149
3150
3151/**
3152 * Does the state change callouts.
3153 *
3154 * The caller owns the AtStateCritSect.
3155 *
3156 * @param pVM The VM handle.
3157 * @param pUVM The UVM handle.
3158 * @param enmStateNew The New state.
3159 * @param enmStateOld The old state.
3160 */
3161static void vmR3DoAtState(PVM pVM, PUVM pUVM, VMSTATE enmStateNew, VMSTATE enmStateOld)
3162{
3163 LogRel(("Changing the VM state from '%s' to '%s'.\n", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)));
3164
3165 for (PVMATSTATE pCur = pUVM->vm.s.pAtState; pCur; pCur = pCur->pNext)
3166 {
3167 pCur->pfnAtState(pVM, enmStateNew, enmStateOld, pCur->pvUser);
3168 if ( enmStateNew != VMSTATE_DESTROYING
3169 && pVM->enmVMState == VMSTATE_DESTROYING)
3170 break;
3171 AssertMsg(pVM->enmVMState == enmStateNew,
3172 ("You are not allowed to change the state while in the change callback, except "
3173 "from destroying the VM. There are restrictions in the way the state changes "
3174 "are propagated up to the EM execution loop and it makes the program flow very "
3175 "difficult to follow. (%s, expected %s, old %s)\n",
3176 VMR3GetStateName(pVM->enmVMState), VMR3GetStateName(enmStateNew),
3177 VMR3GetStateName(enmStateOld)));
3178 }
3179}
3180
3181
3182/**
3183 * Sets the current VM state, with the AtStatCritSect already entered.
3184 *
3185 * @param pVM The VM handle.
3186 * @param pUVM The UVM handle.
3187 * @param enmStateNew The new state.
3188 * @param enmStateOld The old state.
3189 */
3190static void vmR3SetStateLocked(PVM pVM, PUVM pUVM, VMSTATE enmStateNew, VMSTATE enmStateOld)
3191{
3192 vmR3ValidateStateTransition(enmStateOld, enmStateNew);
3193
3194 AssertMsg(pVM->enmVMState == enmStateOld,
3195 ("%s != %s\n", VMR3GetStateName(pVM->enmVMState), VMR3GetStateName(enmStateOld)));
3196 pUVM->vm.s.enmPrevVMState = enmStateOld;
3197 pVM->enmVMState = enmStateNew;
3198 VM_FF_CLEAR(pVM, VM_FF_CHECK_VM_STATE);
3199
3200 vmR3DoAtState(pVM, pUVM, enmStateNew, enmStateOld);
3201}
3202
3203
3204/**
3205 * Sets the current VM state.
3206 *
3207 * @param pVM VM handle.
3208 * @param enmStateNew The new state.
3209 * @param enmStateOld The old state (for asserting only).
3210 */
3211static void vmR3SetState(PVM pVM, VMSTATE enmStateNew, VMSTATE enmStateOld)
3212{
3213 PUVM pUVM = pVM->pUVM;
3214 RTCritSectEnter(&pUVM->vm.s.AtStateCritSect);
3215
3216 AssertMsg(pVM->enmVMState == enmStateOld,
3217 ("%s != %s\n", VMR3GetStateName(pVM->enmVMState), VMR3GetStateName(enmStateOld)));
3218 vmR3SetStateLocked(pVM, pUVM, enmStateNew, pVM->enmVMState);
3219
3220 RTCritSectLeave(&pUVM->vm.s.AtStateCritSect);
3221}
3222
3223
3224/**
3225 * Tries to perform a state transition.
3226 *
3227 * @returns The 1-based ordinal of the succeeding transition.
3228 * VERR_VM_INVALID_VM_STATE and Assert+LogRel on failure.
3229 *
3230 * @param pVM The VM handle.
3231 * @param pszWho Who is trying to change it.
3232 * @param cTransitions The number of transitions in the ellipsis.
3233 * @param ... Transition pairs; new, old.
3234 */
3235static int vmR3TrySetState(PVM pVM, const char *pszWho, unsigned cTransitions, ...)
3236{
3237 va_list va;
3238 VMSTATE enmStateNew = VMSTATE_CREATED;
3239 VMSTATE enmStateOld = VMSTATE_CREATED;
3240
3241#ifdef VBOX_STRICT
3242 /*
3243 * Validate the input first.
3244 */
3245 va_start(va, cTransitions);
3246 for (unsigned i = 0; i < cTransitions; i++)
3247 {
3248 enmStateNew = (VMSTATE)va_arg(va, /*VMSTATE*/int);
3249 enmStateOld = (VMSTATE)va_arg(va, /*VMSTATE*/int);
3250 vmR3ValidateStateTransition(enmStateOld, enmStateNew);
3251 }
3252 va_end(va);
3253#endif
3254
3255 /*
3256 * Grab the lock and see if any of the proposed transisions works out.
3257 */
3258 va_start(va, cTransitions);
3259 int rc = VERR_VM_INVALID_VM_STATE;
3260 PUVM pUVM = pVM->pUVM;
3261 RTCritSectEnter(&pUVM->vm.s.AtStateCritSect);
3262
3263 VMSTATE enmStateCur = pVM->enmVMState;
3264
3265 for (unsigned i = 0; i < cTransitions; i++)
3266 {
3267 enmStateNew = (VMSTATE)va_arg(va, /*VMSTATE*/int);
3268 enmStateOld = (VMSTATE)va_arg(va, /*VMSTATE*/int);
3269 if (enmStateCur == enmStateOld)
3270 {
3271 vmR3SetStateLocked(pVM, pUVM, enmStateNew, enmStateOld);
3272 rc = i + 1;
3273 break;
3274 }
3275 }
3276
3277 if (RT_FAILURE(rc))
3278 {
3279 /*
3280 * Complain about it.
3281 */
3282 if (cTransitions == 1)
3283 {
3284 LogRel(("%s: %s -> %s failed, because the VM state is actually %s\n",
3285 pszWho, VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew), VMR3GetStateName(enmStateCur)));
3286 VMSetError(pVM, VERR_VM_INVALID_VM_STATE, RT_SRC_POS,
3287 N_("%s failed because the VM state is %s instead of %s"),
3288 pszWho, VMR3GetStateName(enmStateCur), VMR3GetStateName(enmStateOld));
3289 AssertMsgFailed(("%s: %s -> %s failed, because the VM state is actually %s\n",
3290 pszWho, VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew), VMR3GetStateName(enmStateCur)));
3291 }
3292 else
3293 {
3294 va_end(va);
3295 va_start(va, cTransitions);
3296 LogRel(("%s:\n", pszWho));
3297 for (unsigned i = 0; i < cTransitions; i++)
3298 {
3299 enmStateNew = (VMSTATE)va_arg(va, /*VMSTATE*/int);
3300 enmStateOld = (VMSTATE)va_arg(va, /*VMSTATE*/int);
3301 LogRel(("%s%s -> %s",
3302 i ? ", " : " ", VMR3GetStateName(enmStateOld), VMR3GetStateName(enmStateNew)));
3303 }
3304 LogRel((" failed, because the VM state is actually %s\n", VMR3GetStateName(enmStateCur)));
3305 VMSetError(pVM, VERR_VM_INVALID_VM_STATE, RT_SRC_POS,
3306 N_("%s failed because the current VM state, %s, was not found in the state transition table"),
3307 pszWho, VMR3GetStateName(enmStateCur), VMR3GetStateName(enmStateOld));
3308 AssertMsgFailed(("%s - state=%s, see release log for full details. Check the cTransitions passed us.\n",
3309 pszWho, VMR3GetStateName(enmStateCur)));
3310 }
3311 }
3312
3313 RTCritSectLeave(&pUVM->vm.s.AtStateCritSect);
3314 va_end(va);
3315 Assert(rc > 0 || rc < 0);
3316 return rc;
3317}
3318
3319
3320/**
3321 * Flag a guru meditation ... a hack.
3322 *
3323 * @param pVM The VM handle
3324 *
3325 * @todo Rewrite this part. The guru meditation should be flagged
3326 * immediately by the VMM and not by VMEmt.cpp when it's all over.
3327 */
3328void vmR3SetGuruMeditation(PVM pVM)
3329{
3330 PUVM pUVM = pVM->pUVM;
3331 RTCritSectEnter(&pUVM->vm.s.AtStateCritSect);
3332
3333 VMSTATE enmStateCur = pVM->enmVMState;
3334 if (enmStateCur == VMSTATE_RUNNING)
3335 vmR3SetStateLocked(pVM, pUVM, VMSTATE_GURU_MEDITATION, VMSTATE_RUNNING);
3336 else if (enmStateCur == VMSTATE_RUNNING_LS)
3337 {
3338 vmR3SetStateLocked(pVM, pUVM, VMSTATE_GURU_MEDITATION_LS, VMSTATE_RUNNING_LS);
3339 SSMR3Cancel(pVM);
3340 }
3341
3342 RTCritSectLeave(&pUVM->vm.s.AtStateCritSect);
3343}
3344
3345
3346/**
3347 * Called by vmR3EmulationThreadWithId just before the VM structure is freed.
3348 *
3349 * @param pVM The VM handle.
3350 */
3351void vmR3SetTerminated(PVM pVM)
3352{
3353 vmR3SetState(pVM, VMSTATE_TERMINATED, VMSTATE_DESTROYING);
3354}
3355
3356
3357/**
3358 * Checks if the VM was teleported and hasn't been fully resumed yet.
3359 *
3360 * This applies to both sides of the teleportation since we may leave a working
3361 * clone behind and the user is allowed to resume this...
3362 *
3363 * @returns true / false.
3364 * @param pVM The VM handle.
3365 * @thread Any thread.
3366 */
3367VMMR3DECL(bool) VMR3TeleportedAndNotFullyResumedYet(PVM pVM)
3368{
3369 VM_ASSERT_VALID_EXT_RETURN(pVM, false);
3370 return pVM->vm.s.fTeleportedAndNotFullyResumedYet;
3371}
3372
3373
3374/**
3375 * Registers a VM state change callback.
3376 *
3377 * You are not allowed to call any function which changes the VM state from a
3378 * state callback.
3379 *
3380 * @returns VBox status code.
3381 * @param pVM VM handle.
3382 * @param pfnAtState Pointer to callback.
3383 * @param pvUser User argument.
3384 * @thread Any.
3385 */
3386VMMR3DECL(int) VMR3AtStateRegister(PVM pVM, PFNVMATSTATE pfnAtState, void *pvUser)
3387{
3388 LogFlow(("VMR3AtStateRegister: pfnAtState=%p pvUser=%p\n", pfnAtState, pvUser));
3389
3390 /*
3391 * Validate input.
3392 */
3393 AssertPtrReturn(pfnAtState, VERR_INVALID_PARAMETER);
3394 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
3395
3396 /*
3397 * Allocate a new record.
3398 */
3399 PUVM pUVM = pVM->pUVM;
3400 PVMATSTATE pNew = (PVMATSTATE)MMR3HeapAllocU(pUVM, MM_TAG_VM, sizeof(*pNew));
3401 if (!pNew)
3402 return VERR_NO_MEMORY;
3403
3404 /* fill */
3405 pNew->pfnAtState = pfnAtState;
3406 pNew->pvUser = pvUser;
3407
3408 /* insert */
3409 RTCritSectEnter(&pUVM->vm.s.AtStateCritSect);
3410 pNew->pNext = *pUVM->vm.s.ppAtStateNext;
3411 *pUVM->vm.s.ppAtStateNext = pNew;
3412 pUVM->vm.s.ppAtStateNext = &pNew->pNext;
3413 RTCritSectLeave(&pUVM->vm.s.AtStateCritSect);
3414
3415 return VINF_SUCCESS;
3416}
3417
3418
3419/**
3420 * Deregisters a VM state change callback.
3421 *
3422 * @returns VBox status code.
3423 * @param pVM VM handle.
3424 * @param pfnAtState Pointer to callback.
3425 * @param pvUser User argument.
3426 * @thread Any.
3427 */
3428VMMR3DECL(int) VMR3AtStateDeregister(PVM pVM, PFNVMATSTATE pfnAtState, void *pvUser)
3429{
3430 LogFlow(("VMR3AtStateDeregister: pfnAtState=%p pvUser=%p\n", pfnAtState, pvUser));
3431
3432 /*
3433 * Validate input.
3434 */
3435 AssertPtrReturn(pfnAtState, VERR_INVALID_PARAMETER);
3436 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
3437
3438 PUVM pUVM = pVM->pUVM;
3439 RTCritSectEnter(&pUVM->vm.s.AtStateCritSect);
3440
3441 /*
3442 * Search the list for the entry.
3443 */
3444 PVMATSTATE pPrev = NULL;
3445 PVMATSTATE pCur = pUVM->vm.s.pAtState;
3446 while ( pCur
3447 && ( pCur->pfnAtState != pfnAtState
3448 || pCur->pvUser != pvUser))
3449 {
3450 pPrev = pCur;
3451 pCur = pCur->pNext;
3452 }
3453 if (!pCur)
3454 {
3455 AssertMsgFailed(("pfnAtState=%p was not found\n", pfnAtState));
3456 RTCritSectLeave(&pUVM->vm.s.AtStateCritSect);
3457 return VERR_FILE_NOT_FOUND;
3458 }
3459
3460 /*
3461 * Unlink it.
3462 */
3463 if (pPrev)
3464 {
3465 pPrev->pNext = pCur->pNext;
3466 if (!pCur->pNext)
3467 pUVM->vm.s.ppAtStateNext = &pPrev->pNext;
3468 }
3469 else
3470 {
3471 pUVM->vm.s.pAtState = pCur->pNext;
3472 if (!pCur->pNext)
3473 pUVM->vm.s.ppAtStateNext = &pUVM->vm.s.pAtState;
3474 }
3475
3476 RTCritSectLeave(&pUVM->vm.s.AtStateCritSect);
3477
3478 /*
3479 * Free it.
3480 */
3481 pCur->pfnAtState = NULL;
3482 pCur->pNext = NULL;
3483 MMR3HeapFree(pCur);
3484
3485 return VINF_SUCCESS;
3486}
3487
3488
3489/**
3490 * Registers a VM error callback.
3491 *
3492 * @returns VBox status code.
3493 * @param pVM The VM handle.
3494 * @param pfnAtError Pointer to callback.
3495 * @param pvUser User argument.
3496 * @thread Any.
3497 */
3498VMMR3DECL(int) VMR3AtErrorRegister(PVM pVM, PFNVMATERROR pfnAtError, void *pvUser)
3499{
3500 return VMR3AtErrorRegisterU(pVM->pUVM, pfnAtError, pvUser);
3501}
3502
3503
3504/**
3505 * Registers a VM error callback.
3506 *
3507 * @returns VBox status code.
3508 * @param pUVM The VM handle.
3509 * @param pfnAtError Pointer to callback.
3510 * @param pvUser User argument.
3511 * @thread Any.
3512 */
3513VMMR3DECL(int) VMR3AtErrorRegisterU(PUVM pUVM, PFNVMATERROR pfnAtError, void *pvUser)
3514{
3515 LogFlow(("VMR3AtErrorRegister: pfnAtError=%p pvUser=%p\n", pfnAtError, pvUser));
3516
3517 /*
3518 * Validate input.
3519 */
3520 AssertPtrReturn(pfnAtError, VERR_INVALID_PARAMETER);
3521 UVM_ASSERT_VALID_EXT_RETURN(pUVM, VERR_INVALID_VM_HANDLE);
3522
3523 /*
3524 * Allocate a new record.
3525 */
3526 PVMATERROR pNew = (PVMATERROR)MMR3HeapAllocU(pUVM, MM_TAG_VM, sizeof(*pNew));
3527 if (!pNew)
3528 return VERR_NO_MEMORY;
3529
3530 /* fill */
3531 pNew->pfnAtError = pfnAtError;
3532 pNew->pvUser = pvUser;
3533
3534 /* insert */
3535 RTCritSectEnter(&pUVM->vm.s.AtErrorCritSect);
3536 pNew->pNext = *pUVM->vm.s.ppAtErrorNext;
3537 *pUVM->vm.s.ppAtErrorNext = pNew;
3538 pUVM->vm.s.ppAtErrorNext = &pNew->pNext;
3539 RTCritSectLeave(&pUVM->vm.s.AtErrorCritSect);
3540
3541 return VINF_SUCCESS;
3542}
3543
3544
3545/**
3546 * Deregisters a VM error callback.
3547 *
3548 * @returns VBox status code.
3549 * @param pVM The VM handle.
3550 * @param pfnAtError Pointer to callback.
3551 * @param pvUser User argument.
3552 * @thread Any.
3553 */
3554VMMR3DECL(int) VMR3AtErrorDeregister(PVM pVM, PFNVMATERROR pfnAtError, void *pvUser)
3555{
3556 LogFlow(("VMR3AtErrorDeregister: pfnAtError=%p pvUser=%p\n", pfnAtError, pvUser));
3557
3558 /*
3559 * Validate input.
3560 */
3561 AssertPtrReturn(pfnAtError, VERR_INVALID_PARAMETER);
3562 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
3563
3564 PUVM pUVM = pVM->pUVM;
3565 RTCritSectEnter(&pUVM->vm.s.AtErrorCritSect);
3566
3567 /*
3568 * Search the list for the entry.
3569 */
3570 PVMATERROR pPrev = NULL;
3571 PVMATERROR pCur = pUVM->vm.s.pAtError;
3572 while ( pCur
3573 && ( pCur->pfnAtError != pfnAtError
3574 || pCur->pvUser != pvUser))
3575 {
3576 pPrev = pCur;
3577 pCur = pCur->pNext;
3578 }
3579 if (!pCur)
3580 {
3581 AssertMsgFailed(("pfnAtError=%p was not found\n", pfnAtError));
3582 RTCritSectLeave(&pUVM->vm.s.AtErrorCritSect);
3583 return VERR_FILE_NOT_FOUND;
3584 }
3585
3586 /*
3587 * Unlink it.
3588 */
3589 if (pPrev)
3590 {
3591 pPrev->pNext = pCur->pNext;
3592 if (!pCur->pNext)
3593 pUVM->vm.s.ppAtErrorNext = &pPrev->pNext;
3594 }
3595 else
3596 {
3597 pUVM->vm.s.pAtError = pCur->pNext;
3598 if (!pCur->pNext)
3599 pUVM->vm.s.ppAtErrorNext = &pUVM->vm.s.pAtError;
3600 }
3601
3602 RTCritSectLeave(&pUVM->vm.s.AtErrorCritSect);
3603
3604 /*
3605 * Free it.
3606 */
3607 pCur->pfnAtError = NULL;
3608 pCur->pNext = NULL;
3609 MMR3HeapFree(pCur);
3610
3611 return VINF_SUCCESS;
3612}
3613
3614
3615/**
3616 * Ellipsis to va_list wrapper for calling pfnAtError.
3617 */
3618static void vmR3SetErrorWorkerDoCall(PVM pVM, PVMATERROR pCur, int rc, RT_SRC_POS_DECL, const char *pszFormat, ...)
3619{
3620 va_list va;
3621 va_start(va, pszFormat);
3622 pCur->pfnAtError(pVM, pCur->pvUser, rc, RT_SRC_POS_ARGS, pszFormat, va);
3623 va_end(va);
3624}
3625
3626
3627/**
3628 * This is a worker function for GC and Ring-0 calls to VMSetError and VMSetErrorV.
3629 * The message is found in VMINT.
3630 *
3631 * @param pVM The VM handle.
3632 * @thread EMT.
3633 */
3634VMMR3DECL(void) VMR3SetErrorWorker(PVM pVM)
3635{
3636 VM_ASSERT_EMT(pVM);
3637 AssertReleaseMsgFailed(("And we have a winner! You get to implement Ring-0 and GC VMSetErrorV! Contrats!\n"));
3638
3639 /*
3640 * Unpack the error (if we managed to format one).
3641 */
3642 PVMERROR pErr = pVM->vm.s.pErrorR3;
3643 const char *pszFile = NULL;
3644 const char *pszFunction = NULL;
3645 uint32_t iLine = 0;
3646 const char *pszMessage;
3647 int32_t rc = VERR_MM_HYPER_NO_MEMORY;
3648 if (pErr)
3649 {
3650 AssertCompile(sizeof(const char) == sizeof(uint8_t));
3651 if (pErr->offFile)
3652 pszFile = (const char *)pErr + pErr->offFile;
3653 iLine = pErr->iLine;
3654 if (pErr->offFunction)
3655 pszFunction = (const char *)pErr + pErr->offFunction;
3656 if (pErr->offMessage)
3657 pszMessage = (const char *)pErr + pErr->offMessage;
3658 else
3659 pszMessage = "No message!";
3660 }
3661 else
3662 pszMessage = "No message! (Failed to allocate memory to put the error message in!)";
3663
3664 /*
3665 * Call the at error callbacks.
3666 */
3667 PUVM pUVM = pVM->pUVM;
3668 RTCritSectEnter(&pUVM->vm.s.AtErrorCritSect);
3669 ASMAtomicIncU32(&pUVM->vm.s.cRuntimeErrors);
3670 for (PVMATERROR pCur = pUVM->vm.s.pAtError; pCur; pCur = pCur->pNext)
3671 vmR3SetErrorWorkerDoCall(pVM, pCur, rc, RT_SRC_POS_ARGS, "%s", pszMessage);
3672 RTCritSectLeave(&pUVM->vm.s.AtErrorCritSect);
3673}
3674
3675
3676/**
3677 * Gets the number of errors raised via VMSetError.
3678 *
3679 * This can be used avoid double error messages.
3680 *
3681 * @returns The error count.
3682 * @param pVM The VM handle.
3683 */
3684VMMR3DECL(uint32_t) VMR3GetErrorCount(PVM pVM)
3685{
3686 return pVM->pUVM->vm.s.cErrors;
3687}
3688
3689
3690/**
3691 * Creation time wrapper for vmR3SetErrorUV.
3692 *
3693 * @returns rc.
3694 * @param pUVM Pointer to the user mode VM structure.
3695 * @param rc The VBox status code.
3696 * @param RT_SRC_POS_DECL The source position of this error.
3697 * @param pszFormat Format string.
3698 * @param ... The arguments.
3699 * @thread Any thread.
3700 */
3701static int vmR3SetErrorU(PUVM pUVM, int rc, RT_SRC_POS_DECL, const char *pszFormat, ...)
3702{
3703 va_list va;
3704 va_start(va, pszFormat);
3705 vmR3SetErrorUV(pUVM, rc, pszFile, iLine, pszFunction, pszFormat, &va);
3706 va_end(va);
3707 return rc;
3708}
3709
3710
3711/**
3712 * Worker which calls everyone listening to the VM error messages.
3713 *
3714 * @param pUVM Pointer to the user mode VM structure.
3715 * @param rc The VBox status code.
3716 * @param RT_SRC_POS_DECL The source position of this error.
3717 * @param pszFormat Format string.
3718 * @param pArgs Pointer to the format arguments.
3719 * @thread EMT
3720 */
3721DECLCALLBACK(void) vmR3SetErrorUV(PUVM pUVM, int rc, RT_SRC_POS_DECL, const char *pszFormat, va_list *pArgs)
3722{
3723 /*
3724 * Log the error.
3725 */
3726 va_list va3;
3727 va_copy(va3, *pArgs);
3728 RTLogRelPrintf("VMSetError: %s(%d) %s; rc=%Rrc\n"
3729 "VMSetError: %N\n",
3730 pszFile, iLine, pszFunction, rc,
3731 pszFormat, &va3);
3732 va_end(va3);
3733
3734#ifdef LOG_ENABLED
3735 va_copy(va3, *pArgs);
3736 RTLogPrintf("VMSetError: %s(%d) %s; rc=%Rrc\n"
3737 "%N\n",
3738 pszFile, iLine, pszFunction, rc,
3739 pszFormat, &va3);
3740 va_end(va3);
3741#endif
3742
3743 /*
3744 * Make a copy of the message.
3745 */
3746 if (pUVM->pVM)
3747 vmSetErrorCopy(pUVM->pVM, rc, RT_SRC_POS_ARGS, pszFormat, *pArgs);
3748
3749 /*
3750 * Call the at error callbacks.
3751 */
3752 bool fCalledSomeone = false;
3753 RTCritSectEnter(&pUVM->vm.s.AtErrorCritSect);
3754 ASMAtomicIncU32(&pUVM->vm.s.cErrors);
3755 for (PVMATERROR pCur = pUVM->vm.s.pAtError; pCur; pCur = pCur->pNext)
3756 {
3757 va_list va2;
3758 va_copy(va2, *pArgs);
3759 pCur->pfnAtError(pUVM->pVM, pCur->pvUser, rc, RT_SRC_POS_ARGS, pszFormat, va2);
3760 va_end(va2);
3761 fCalledSomeone = true;
3762 }
3763 RTCritSectLeave(&pUVM->vm.s.AtErrorCritSect);
3764}
3765
3766
3767/**
3768 * Registers a VM runtime error callback.
3769 *
3770 * @returns VBox status code.
3771 * @param pVM The VM handle.
3772 * @param pfnAtRuntimeError Pointer to callback.
3773 * @param pvUser User argument.
3774 * @thread Any.
3775 */
3776VMMR3DECL(int) VMR3AtRuntimeErrorRegister(PVM pVM, PFNVMATRUNTIMEERROR pfnAtRuntimeError, void *pvUser)
3777{
3778 LogFlow(("VMR3AtRuntimeErrorRegister: pfnAtRuntimeError=%p pvUser=%p\n", pfnAtRuntimeError, pvUser));
3779
3780 /*
3781 * Validate input.
3782 */
3783 AssertPtrReturn(pfnAtRuntimeError, VERR_INVALID_PARAMETER);
3784 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
3785
3786 /*
3787 * Allocate a new record.
3788 */
3789 PUVM pUVM = pVM->pUVM;
3790 PVMATRUNTIMEERROR pNew = (PVMATRUNTIMEERROR)MMR3HeapAllocU(pUVM, MM_TAG_VM, sizeof(*pNew));
3791 if (!pNew)
3792 return VERR_NO_MEMORY;
3793
3794 /* fill */
3795 pNew->pfnAtRuntimeError = pfnAtRuntimeError;
3796 pNew->pvUser = pvUser;
3797
3798 /* insert */
3799 RTCritSectEnter(&pUVM->vm.s.AtErrorCritSect);
3800 pNew->pNext = *pUVM->vm.s.ppAtRuntimeErrorNext;
3801 *pUVM->vm.s.ppAtRuntimeErrorNext = pNew;
3802 pUVM->vm.s.ppAtRuntimeErrorNext = &pNew->pNext;
3803 RTCritSectLeave(&pUVM->vm.s.AtErrorCritSect);
3804
3805 return VINF_SUCCESS;
3806}
3807
3808
3809/**
3810 * Deregisters a VM runtime error callback.
3811 *
3812 * @returns VBox status code.
3813 * @param pVM The VM handle.
3814 * @param pfnAtRuntimeError Pointer to callback.
3815 * @param pvUser User argument.
3816 * @thread Any.
3817 */
3818VMMR3DECL(int) VMR3AtRuntimeErrorDeregister(PVM pVM, PFNVMATRUNTIMEERROR pfnAtRuntimeError, void *pvUser)
3819{
3820 LogFlow(("VMR3AtRuntimeErrorDeregister: pfnAtRuntimeError=%p pvUser=%p\n", pfnAtRuntimeError, pvUser));
3821
3822 /*
3823 * Validate input.
3824 */
3825 AssertPtrReturn(pfnAtRuntimeError, VERR_INVALID_PARAMETER);
3826 VM_ASSERT_VALID_EXT_RETURN(pVM, VERR_INVALID_VM_HANDLE);
3827
3828 PUVM pUVM = pVM->pUVM;
3829 RTCritSectEnter(&pUVM->vm.s.AtErrorCritSect);
3830
3831 /*
3832 * Search the list for the entry.
3833 */
3834 PVMATRUNTIMEERROR pPrev = NULL;
3835 PVMATRUNTIMEERROR pCur = pUVM->vm.s.pAtRuntimeError;
3836 while ( pCur
3837 && ( pCur->pfnAtRuntimeError != pfnAtRuntimeError
3838 || pCur->pvUser != pvUser))
3839 {
3840 pPrev = pCur;
3841 pCur = pCur->pNext;
3842 }
3843 if (!pCur)
3844 {
3845 AssertMsgFailed(("pfnAtRuntimeError=%p was not found\n", pfnAtRuntimeError));
3846 RTCritSectLeave(&pUVM->vm.s.AtErrorCritSect);
3847 return VERR_FILE_NOT_FOUND;
3848 }
3849
3850 /*
3851 * Unlink it.
3852 */
3853 if (pPrev)
3854 {
3855 pPrev->pNext = pCur->pNext;
3856 if (!pCur->pNext)
3857 pUVM->vm.s.ppAtRuntimeErrorNext = &pPrev->pNext;
3858 }
3859 else
3860 {
3861 pUVM->vm.s.pAtRuntimeError = pCur->pNext;
3862 if (!pCur->pNext)
3863 pUVM->vm.s.ppAtRuntimeErrorNext = &pUVM->vm.s.pAtRuntimeError;
3864 }
3865
3866 RTCritSectLeave(&pUVM->vm.s.AtErrorCritSect);
3867
3868 /*
3869 * Free it.
3870 */
3871 pCur->pfnAtRuntimeError = NULL;
3872 pCur->pNext = NULL;
3873 MMR3HeapFree(pCur);
3874
3875 return VINF_SUCCESS;
3876}
3877
3878
3879/**
3880 * EMT rendezvous worker that vmR3SetRuntimeErrorCommon uses to safely change
3881 * the state to FatalError(LS).
3882 *
3883 * @returns VERR_VM_INVALID_VM_STATE or VINF_EM_SUSPENED. (This is a strict
3884 * return code, see FNVMMEMTRENDEZVOUS.)
3885 *
3886 * @param pVM The VM handle.
3887 * @param pVCpu The VMCPU handle of the EMT.
3888 * @param pvUser Ignored.
3889 */
3890static DECLCALLBACK(VBOXSTRICTRC) vmR3SetRuntimeErrorChangeState(PVM pVM, PVMCPU pVCpu, void *pvUser)
3891{
3892 NOREF(pVCpu);
3893 Assert(!pvUser); NOREF(pvUser);
3894
3895 /*
3896 * The first EMT thru here changes the state.
3897 */
3898 if (pVCpu->idCpu == pVM->cCpus - 1)
3899 {
3900 int rc = vmR3TrySetState(pVM, "VMSetRuntimeError", 2,
3901 VMSTATE_FATAL_ERROR, VMSTATE_RUNNING,
3902 VMSTATE_FATAL_ERROR_LS, VMSTATE_RUNNING_LS);
3903 if (RT_FAILURE(rc))
3904 return rc;
3905 if (rc == 2)
3906 SSMR3Cancel(pVM);
3907
3908 VM_FF_SET(pVM, VM_FF_CHECK_VM_STATE);
3909 }
3910
3911 /* This'll make sure we get out of whereever we are (e.g. REM). */
3912 return VINF_EM_SUSPEND;
3913}
3914
3915
3916/**
3917 * Worker for VMR3SetRuntimeErrorWorker and vmR3SetRuntimeErrorV.
3918 *
3919 * This does the common parts after the error has been saved / retrieved.
3920 *
3921 * @returns VBox status code with modifications, see VMSetRuntimeErrorV.
3922 *
3923 * @param pVM The VM handle.
3924 * @param fFlags The error flags.
3925 * @param pszErrorId Error ID string.
3926 * @param pszFormat Format string.
3927 * @param pVa Pointer to the format arguments.
3928 */
3929static int vmR3SetRuntimeErrorCommon(PVM pVM, uint32_t fFlags, const char *pszErrorId, const char *pszFormat, va_list *pVa)
3930{
3931 LogRel(("VM: Raising runtime error '%s' (fFlags=%#x)\n", pszErrorId, fFlags));
3932
3933 /*
3934 * Take actions before the call.
3935 */
3936 int rc;
3937 if (fFlags & VMSETRTERR_FLAGS_FATAL)
3938 rc = VMMR3EmtRendezvous(pVM, VMMEMTRENDEZVOUS_FLAGS_TYPE_DESCENDING | VMMEMTRENDEZVOUS_FLAGS_STOP_ON_ERROR,
3939 vmR3SetRuntimeErrorChangeState, NULL);
3940 else if (fFlags & VMSETRTERR_FLAGS_SUSPEND)
3941 rc = VMR3Suspend(pVM);
3942 else
3943 rc = VINF_SUCCESS;
3944
3945 /*
3946 * Do the callback round.
3947 */
3948 PUVM pUVM = pVM->pUVM;
3949 RTCritSectEnter(&pUVM->vm.s.AtErrorCritSect);
3950 ASMAtomicIncU32(&pUVM->vm.s.cRuntimeErrors);
3951 for (PVMATRUNTIMEERROR pCur = pUVM->vm.s.pAtRuntimeError; pCur; pCur = pCur->pNext)
3952 {
3953 va_list va;
3954 va_copy(va, *pVa);
3955 pCur->pfnAtRuntimeError(pVM, pCur->pvUser, fFlags, pszErrorId, pszFormat, va);
3956 va_end(va);
3957 }
3958 RTCritSectLeave(&pUVM->vm.s.AtErrorCritSect);
3959
3960 return rc;
3961}
3962
3963
3964/**
3965 * Ellipsis to va_list wrapper for calling vmR3SetRuntimeErrorCommon.
3966 */
3967static int vmR3SetRuntimeErrorCommonF(PVM pVM, uint32_t fFlags, const char *pszErrorId, const char *pszFormat, ...)
3968{
3969 va_list va;
3970 va_start(va, pszFormat);
3971 int rc = vmR3SetRuntimeErrorCommon(pVM, fFlags, pszErrorId, pszFormat, &va);
3972 va_end(va);
3973 return rc;
3974}
3975
3976
3977/**
3978 * This is a worker function for RC and Ring-0 calls to VMSetError and
3979 * VMSetErrorV.
3980 *
3981 * The message is found in VMINT.
3982 *
3983 * @returns VBox status code, see VMSetRuntimeError.
3984 * @param pVM The VM handle.
3985 * @thread EMT.
3986 */
3987VMMR3DECL(int) VMR3SetRuntimeErrorWorker(PVM pVM)
3988{
3989 VM_ASSERT_EMT(pVM);
3990 AssertReleaseMsgFailed(("And we have a winner! You get to implement Ring-0 and GC VMSetRuntimeErrorV! Congrats!\n"));
3991
3992 /*
3993 * Unpack the error (if we managed to format one).
3994 */
3995 const char *pszErrorId = "SetRuntimeError";
3996 const char *pszMessage = "No message!";
3997 uint32_t fFlags = VMSETRTERR_FLAGS_FATAL;
3998 PVMRUNTIMEERROR pErr = pVM->vm.s.pRuntimeErrorR3;
3999 if (pErr)
4000 {
4001 AssertCompile(sizeof(const char) == sizeof(uint8_t));
4002 if (pErr->offErrorId)
4003 pszErrorId = (const char *)pErr + pErr->offErrorId;
4004 if (pErr->offMessage)
4005 pszMessage = (const char *)pErr + pErr->offMessage;
4006 fFlags = pErr->fFlags;
4007 }
4008
4009 /*
4010 * Join cause with vmR3SetRuntimeErrorV.
4011 */
4012 return vmR3SetRuntimeErrorCommonF(pVM, fFlags, pszErrorId, "%s", pszMessage);
4013}
4014
4015
4016/**
4017 * Worker for VMSetRuntimeErrorV for doing the job on EMT in ring-3.
4018 *
4019 * @returns VBox status code with modifications, see VMSetRuntimeErrorV.
4020 *
4021 * @param pVM The VM handle.
4022 * @param fFlags The error flags.
4023 * @param pszErrorId Error ID string.
4024 * @param pszMessage The error message residing the MM heap.
4025 *
4026 * @thread EMT
4027 */
4028DECLCALLBACK(int) vmR3SetRuntimeError(PVM pVM, uint32_t fFlags, const char *pszErrorId, char *pszMessage)
4029{
4030#if 0 /** @todo make copy of the error msg. */
4031 /*
4032 * Make a copy of the message.
4033 */
4034 va_list va2;
4035 va_copy(va2, *pVa);
4036 vmSetRuntimeErrorCopy(pVM, fFlags, pszErrorId, pszFormat, va2);
4037 va_end(va2);
4038#endif
4039
4040 /*
4041 * Join paths with VMR3SetRuntimeErrorWorker.
4042 */
4043 int rc = vmR3SetRuntimeErrorCommonF(pVM, fFlags, pszErrorId, "%s", pszMessage);
4044 MMR3HeapFree(pszMessage);
4045 return rc;
4046}
4047
4048
4049/**
4050 * Worker for VMSetRuntimeErrorV for doing the job on EMT in ring-3.
4051 *
4052 * @returns VBox status code with modifications, see VMSetRuntimeErrorV.
4053 *
4054 * @param pVM The VM handle.
4055 * @param fFlags The error flags.
4056 * @param pszErrorId Error ID string.
4057 * @param pszFormat Format string.
4058 * @param pVa Pointer to the format arguments.
4059 *
4060 * @thread EMT
4061 */
4062DECLCALLBACK(int) vmR3SetRuntimeErrorV(PVM pVM, uint32_t fFlags, const char *pszErrorId, const char *pszFormat, va_list *pVa)
4063{
4064 /*
4065 * Make a copy of the message.
4066 */
4067 va_list va2;
4068 va_copy(va2, *pVa);
4069 vmSetRuntimeErrorCopy(pVM, fFlags, pszErrorId, pszFormat, va2);
4070 va_end(va2);
4071
4072 /*
4073 * Join paths with VMR3SetRuntimeErrorWorker.
4074 */
4075 return vmR3SetRuntimeErrorCommon(pVM, fFlags, pszErrorId, pszFormat, pVa);
4076}
4077
4078
4079/**
4080 * Gets the number of runtime errors raised via VMR3SetRuntimeError.
4081 *
4082 * This can be used avoid double error messages.
4083 *
4084 * @returns The runtime error count.
4085 * @param pVM The VM handle.
4086 */
4087VMMR3DECL(uint32_t) VMR3GetRuntimeErrorCount(PVM pVM)
4088{
4089 return pVM->pUVM->vm.s.cRuntimeErrors;
4090}
4091
4092
4093/**
4094 * Gets the ID virtual of the virtual CPU assoicated with the calling thread.
4095 *
4096 * @returns The CPU ID. NIL_VMCPUID if the thread isn't an EMT.
4097 *
4098 * @param pVM The VM handle.
4099 */
4100VMMR3DECL(RTCPUID) VMR3GetVMCPUId(PVM pVM)
4101{
4102 PUVMCPU pUVCpu = (PUVMCPU)RTTlsGet(pVM->pUVM->vm.s.idxTLS);
4103 return pUVCpu
4104 ? pUVCpu->idCpu
4105 : NIL_VMCPUID;
4106}
4107
4108
4109/**
4110 * Returns the native handle of the current EMT VMCPU thread.
4111 *
4112 * @returns Handle if this is an EMT thread; NIL_RTNATIVETHREAD otherwise
4113 * @param pVM The VM handle.
4114 * @thread EMT
4115 */
4116VMMR3DECL(RTNATIVETHREAD) VMR3GetVMCPUNativeThread(PVM pVM)
4117{
4118 PUVMCPU pUVCpu = (PUVMCPU)RTTlsGet(pVM->pUVM->vm.s.idxTLS);
4119
4120 if (!pUVCpu)
4121 return NIL_RTNATIVETHREAD;
4122
4123 return pUVCpu->vm.s.NativeThreadEMT;
4124}
4125
4126
4127/**
4128 * Returns the native handle of the current EMT VMCPU thread.
4129 *
4130 * @returns Handle if this is an EMT thread; NIL_RTNATIVETHREAD otherwise
4131 * @param pVM The VM handle.
4132 * @thread EMT
4133 */
4134VMMR3DECL(RTNATIVETHREAD) VMR3GetVMCPUNativeThreadU(PUVM pUVM)
4135{
4136 PUVMCPU pUVCpu = (PUVMCPU)RTTlsGet(pUVM->vm.s.idxTLS);
4137
4138 if (!pUVCpu)
4139 return NIL_RTNATIVETHREAD;
4140
4141 return pUVCpu->vm.s.NativeThreadEMT;
4142}
4143
4144
4145/**
4146 * Returns the handle of the current EMT VMCPU thread.
4147 *
4148 * @returns Handle if this is an EMT thread; NIL_RTNATIVETHREAD otherwise
4149 * @param pVM The VM handle.
4150 * @thread EMT
4151 */
4152VMMR3DECL(RTTHREAD) VMR3GetVMCPUThread(PVM pVM)
4153{
4154 PUVMCPU pUVCpu = (PUVMCPU)RTTlsGet(pVM->pUVM->vm.s.idxTLS);
4155
4156 if (!pUVCpu)
4157 return NIL_RTTHREAD;
4158
4159 return pUVCpu->vm.s.ThreadEMT;
4160}
4161
4162
4163/**
4164 * Returns the handle of the current EMT VMCPU thread.
4165 *
4166 * @returns Handle if this is an EMT thread; NIL_RTNATIVETHREAD otherwise
4167 * @param pVM The VM handle.
4168 * @thread EMT
4169 */
4170VMMR3DECL(RTTHREAD) VMR3GetVMCPUThreadU(PUVM pUVM)
4171{
4172 PUVMCPU pUVCpu = (PUVMCPU)RTTlsGet(pUVM->vm.s.idxTLS);
4173
4174 if (!pUVCpu)
4175 return NIL_RTTHREAD;
4176
4177 return pUVCpu->vm.s.ThreadEMT;
4178}
4179
4180
4181/**
4182 * Return the package and core id of a CPU.
4183 *
4184 * @returns VBOX status code.
4185 * @param pVM The VM to operate on.
4186 * @param idCpu Virtual CPU to get the ID from.
4187 * @param pidCpuCore Where to store the core ID of the virtual CPU.
4188 * @param pidCpuPackage Where to store the package ID of the virtual CPU.
4189 *
4190 */
4191VMMR3DECL(int) VMR3GetCpuCoreAndPackageIdFromCpuId(PVM pVM, VMCPUID idCpu, uint32_t *pidCpuCore, uint32_t *pidCpuPackage)
4192{
4193 if (idCpu >= pVM->cCpus)
4194 return VERR_INVALID_CPU_ID;
4195
4196#ifdef VBOX_WITH_MULTI_CORE
4197 *pidCpuCore = idCpu;
4198 *pidCpuPackage = 0;
4199#else
4200 *pidCpuCore = 0;
4201 *pidCpuPackage = idCpu;
4202#endif
4203
4204 return VINF_SUCCESS;
4205}
4206
4207
4208/**
4209 * Worker for VMR3HotUnplugCpu.
4210 *
4211 * @returns VINF_EM_WAIT_SPIP (strict status code).
4212 * @param pVM The VM handle.
4213 * @param idCpu The current CPU.
4214 */
4215static DECLCALLBACK(int) vmR3HotUnplugCpu(PVM pVM, VMCPUID idCpu)
4216{
4217 PVMCPU pVCpu = VMMGetCpuById(pVM, idCpu);
4218 VMCPU_ASSERT_EMT(pVCpu);
4219
4220 /*
4221 * Reset per CPU resources.
4222 *
4223 * Actually only needed for VT-x because the CPU seems to be still in some
4224 * paged mode and startup fails after a new hot plug event. SVM works fine
4225 * even without this.
4226 */
4227 Log(("vmR3HotUnplugCpu for VCPU %u\n", idCpu));
4228 PGMR3ResetUnpluggedCpu(pVM, pVCpu);
4229 PDMR3ResetCpu(pVCpu);
4230 TRPMR3ResetCpu(pVCpu);
4231 CPUMR3ResetCpu(pVCpu);
4232 EMR3ResetCpu(pVCpu);
4233 HWACCMR3ResetCpu(pVCpu);
4234 return VINF_EM_WAIT_SIPI;
4235}
4236
4237
4238/**
4239 * Hot-unplugs a CPU from the guest.
4240 *
4241 * @returns VBox status code.
4242 * @param pVM The VM to operate on.
4243 * @param idCpu Virtual CPU to perform the hot unplugging operation on.
4244 */
4245VMMR3DECL(int) VMR3HotUnplugCpu(PVM pVM, VMCPUID idCpu)
4246{
4247 AssertReturn(idCpu < pVM->cCpus, VERR_INVALID_CPU_ID);
4248
4249 /** @todo r=bird: Don't destroy the EMT, it'll break VMMR3EmtRendezvous and
4250 * broadcast requests. Just note down somewhere that the CPU is
4251 * offline and send it to SPIP wait. Maybe modify VMCPUSTATE and push
4252 * it out of the EM loops when offline. */
4253 return VMR3ReqCallNoWaitU(pVM->pUVM, idCpu, (PFNRT)vmR3HotUnplugCpu, 2, pVM, idCpu);
4254}
4255
4256
4257/**
4258 * Hot-plugs a CPU on the guest.
4259 *
4260 * @returns VBox status code.
4261 * @param pVM The VM to operate on.
4262 * @param idCpu Virtual CPU to perform the hot plugging operation on.
4263 */
4264VMMR3DECL(int) VMR3HotPlugCpu(PVM pVM, VMCPUID idCpu)
4265{
4266 AssertReturn(idCpu < pVM->cCpus, VERR_INVALID_CPU_ID);
4267
4268 /** @todo r-bird: Just mark it online and make sure it waits on SPIP. */
4269 return VINF_SUCCESS;
4270}
4271
4272
4273/**
4274 * Changes the VMM execution cap.
4275 *
4276 * @returns VBox status code.
4277 * @param pVM The VM to operate on.
4278 * @param ulCpuExecutionCap New CPU execution cap
4279 */
4280VMMR3DECL(int) VMR3SetCpuExecutionCap(PVM pVM, unsigned ulCpuExecutionCap)
4281{
4282 AssertReturn(ulCpuExecutionCap > 0 && ulCpuExecutionCap <= 100, VERR_INVALID_PARAMETER);
4283
4284 Log(("VMR3SetCpuExecutionCap: new priority = %d\n", ulCpuExecutionCap));
4285 /* Note: not called from EMT. */
4286 pVM->uCpuExecutionCap = ulCpuExecutionCap;
4287 return VINF_SUCCESS;
4288}
Note: See TracBrowser for help on using the repository browser.

© 2023 Oracle
ContactPrivacy policyTerms of Use