VirtualBox

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

Last change on this file since 99740 was 99051, checked in by vboxsync, 20 months ago

VMM: More ARMv8 x86/amd64 separation work, VBoxVMMArm compiles and links now, bugref:10385

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