VirtualBox

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

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

Broken assertion

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

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette