VirtualBox

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

Last change on this file since 107663 was 107661, checked in by vboxsync, 5 weeks ago

VMM/VMMR3/VM.cpp: Remove unused fCalledSomeone flag, bugref:3409

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

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