VirtualBox

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

最後變更 在這個檔案從80334是 80334,由 vboxsync 提交於 6 年 前

VMM: Eliminating the VBOX_BUGREF_9217 preprocessor macro. bugref:9217

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

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