VirtualBox

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

最後變更 在這個檔案從50575是 50575,由 vboxsync 提交於 11 年 前

VMM: Added SSMR3RegisterStub and used it to provide saved state load-exec stubs for ignoring CSAM and PATM state when VBOX_WITH_RAW_MODE isn't defined or when HM is active.

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

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