VirtualBox

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

Last change on this file since 109008 was 108968, checked in by vboxsync, 7 days ago

VMM,Main,Devices: Respect VBOX_VMM_TARGET_ARMV8 correctly on amd64 hosts (for IEM debugging purposes). jiraref:VBP-1598

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

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