VirtualBox

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

Last change on this file since 45189 was 45189, checked in by vboxsync, 12 years ago

STAM,VM: ring-3 only testing of pdmcritsectrw.h (disabled).

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

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