VirtualBox

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

Last change on this file since 98103 was 98103, checked in by vboxsync, 17 months ago

Copyright year updates by scm.

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

© 2023 Oracle
ContactPrivacy policyTerms of Use