VirtualBox

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

Last change on this file since 93457 was 93444, checked in by vboxsync, 3 years ago

VMM,Main,HostServices: Use a function table for accessing the VBoxVMM.dll/so/dylib functionality, and load it dynamically when the Console object is initialized. Also converted a few drivers in Main to use device helpers to get config values and such. bugref:10074

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

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