VirtualBox

source: vbox/trunk/src/VBox/Main/MediumImpl.cpp@ 31389

Last change on this file since 31389 was 31370, checked in by vboxsync, 14 years ago

Main: cleanup machine renames, remove dead code

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 210.9 KB
Line 
1/* $Id: MediumImpl.cpp 31370 2010-08-04 18:49:09Z vboxsync $ */
2/** @file
3 * VirtualBox COM class implementation
4 */
5
6/*
7 * Copyright (C) 2008-2010 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#include "MediumImpl.h"
19#include "ProgressImpl.h"
20#include "SystemPropertiesImpl.h"
21#include "VirtualBoxImpl.h"
22
23#include "AutoCaller.h"
24#include "Logging.h"
25
26#include <VBox/com/array.h>
27#include "VBox/com/MultiResult.h"
28#include "VBox/com/ErrorInfo.h"
29
30#include <VBox/err.h>
31#include <VBox/settings.h>
32
33#include <iprt/param.h>
34#include <iprt/path.h>
35#include <iprt/file.h>
36#include <iprt/tcp.h>
37#include <iprt/cpp/utils.h>
38
39#include <VBox/VBoxHDD.h>
40
41#include <algorithm>
42
43////////////////////////////////////////////////////////////////////////////////
44//
45// Medium data definition
46//
47////////////////////////////////////////////////////////////////////////////////
48
49/** Describes how a machine refers to this medium. */
50struct BackRef
51{
52 /** Equality predicate for stdc++. */
53 struct EqualsTo : public std::unary_function <BackRef, bool>
54 {
55 explicit EqualsTo(const Guid &aMachineId) : machineId(aMachineId) {}
56
57 bool operator()(const argument_type &aThat) const
58 {
59 return aThat.machineId == machineId;
60 }
61
62 const Guid machineId;
63 };
64
65 typedef std::list<Guid> GuidList;
66
67 BackRef(const Guid &aMachineId,
68 const Guid &aSnapshotId = Guid::Empty)
69 : machineId(aMachineId),
70 fInCurState(aSnapshotId.isEmpty())
71 {
72 if (!aSnapshotId.isEmpty())
73 llSnapshotIds.push_back(aSnapshotId);
74 }
75
76 Guid machineId;
77 bool fInCurState : 1;
78 GuidList llSnapshotIds;
79};
80
81typedef std::list<BackRef> BackRefList;
82
83struct Medium::Data
84{
85 Data()
86 : pVirtualBox(NULL),
87 state(MediumState_NotCreated),
88 variant(MediumVariant_Standard),
89 size(0),
90 readers(0),
91 preLockState(MediumState_NotCreated),
92 queryInfoSem(NIL_RTSEMEVENTMULTI),
93 queryInfoRunning(false),
94 type(MediumType_Normal),
95 devType(DeviceType_HardDisk),
96 logicalSize(0),
97 hddOpenMode(OpenReadWrite),
98 autoReset(false),
99 setImageId(false),
100 setParentId(false),
101 hostDrive(false),
102 implicit(false),
103 numCreateDiffTasks(0),
104 vdDiskIfaces(NULL)
105 {}
106
107 /** weak VirtualBox parent */
108 VirtualBox * const pVirtualBox;
109
110 const Guid id;
111 Utf8Str strDescription;
112 MediumState_T state;
113 MediumVariant_T variant;
114 Utf8Str strLocation;
115 Utf8Str strLocationFull;
116 uint64_t size;
117 Utf8Str strLastAccessError;
118
119 // pParent and llChildren are protected by VirtualBox::getMediaTreeLockHandle()
120 ComObjPtr<Medium> pParent;
121 MediaList llChildren; // to add a child, just call push_back; to remove a child, call child->deparent() which does a lookup
122
123 BackRefList backRefs;
124
125 size_t readers;
126 MediumState_T preLockState;
127
128 RTSEMEVENTMULTI queryInfoSem;
129 bool queryInfoRunning : 1;
130
131 const Utf8Str strFormat;
132 ComObjPtr<MediumFormat> formatObj;
133
134 MediumType_T type;
135 DeviceType_T devType;
136 uint64_t logicalSize; /*< In MBytes. */
137
138 HDDOpenMode hddOpenMode;
139
140 bool autoReset : 1;
141
142 /** the following members are invalid after changing UUID on open */
143 bool setImageId : 1;
144 bool setParentId : 1;
145 const Guid imageId;
146 const Guid parentId;
147
148 bool hostDrive : 1;
149
150 typedef std::map <Bstr, Bstr> PropertyMap;
151 PropertyMap properties;
152
153 bool implicit : 1;
154
155 uint32_t numCreateDiffTasks;
156
157 Utf8Str vdError; /*< Error remembered by the VD error callback. */
158
159 VDINTERFACE vdIfError;
160 VDINTERFACEERROR vdIfCallsError;
161
162 VDINTERFACE vdIfConfig;
163 VDINTERFACECONFIG vdIfCallsConfig;
164
165 VDINTERFACE vdIfTcpNet;
166 VDINTERFACETCPNET vdIfCallsTcpNet;
167
168 PVDINTERFACE vdDiskIfaces;
169};
170
171typedef struct VDSOCKETINT
172{
173 /** Socket handle. */
174 RTSOCKET hSocket;
175} VDSOCKETINT, *PVDSOCKETINT;
176
177////////////////////////////////////////////////////////////////////////////////
178//
179// Globals
180//
181////////////////////////////////////////////////////////////////////////////////
182
183/**
184 * Medium::Task class for asynchronous operations.
185 *
186 * @note Instances of this class must be created using new() because the
187 * task thread function will delete them when the task is complete.
188 *
189 * @note The constructor of this class adds a caller on the managed Medium
190 * object which is automatically released upon destruction.
191 */
192class Medium::Task
193{
194public:
195 Task(Medium *aMedium, Progress *aProgress)
196 : mVDOperationIfaces(NULL),
197 m_pfNeedsSaveSettings(NULL),
198 mMedium(aMedium),
199 mMediumCaller(aMedium),
200 mThread(NIL_RTTHREAD),
201 mProgress(aProgress)
202 {
203 AssertReturnVoidStmt(aMedium, mRC = E_FAIL);
204 mRC = mMediumCaller.rc();
205 if (FAILED(mRC))
206 return;
207
208 /* Set up a per-operation progress interface, can be used freely (for
209 * binary operations you can use it either on the source or target). */
210 mVDIfCallsProgress.cbSize = sizeof(VDINTERFACEPROGRESS);
211 mVDIfCallsProgress.enmInterface = VDINTERFACETYPE_PROGRESS;
212 mVDIfCallsProgress.pfnProgress = vdProgressCall;
213 int vrc = VDInterfaceAdd(&mVDIfProgress,
214 "Medium::Task::vdInterfaceProgress",
215 VDINTERFACETYPE_PROGRESS,
216 &mVDIfCallsProgress,
217 mProgress,
218 &mVDOperationIfaces);
219 AssertRC(vrc);
220 if (RT_FAILURE(vrc))
221 mRC = E_FAIL;
222 }
223
224 // Make all destructors virtual. Just in case.
225 virtual ~Task()
226 {}
227
228 HRESULT rc() const { return mRC; }
229 bool isOk() const { return SUCCEEDED(rc()); }
230
231 static int fntMediumTask(RTTHREAD aThread, void *pvUser);
232
233 bool isAsync() { return mThread != NIL_RTTHREAD; }
234
235 PVDINTERFACE mVDOperationIfaces;
236
237 // Whether the caller needs to call VirtualBox::saveSettings() after
238 // the task function returns. Only used in synchronous (wait) mode;
239 // otherwise the task will save the settings itself.
240 bool *m_pfNeedsSaveSettings;
241
242 const ComObjPtr<Medium> mMedium;
243 AutoCaller mMediumCaller;
244
245 friend HRESULT Medium::runNow(Medium::Task*, bool*);
246
247protected:
248 HRESULT mRC;
249 RTTHREAD mThread;
250
251private:
252 virtual HRESULT handler() = 0;
253
254 const ComObjPtr<Progress> mProgress;
255
256 static DECLCALLBACK(int) vdProgressCall(void *pvUser, unsigned uPercent);
257
258 VDINTERFACE mVDIfProgress;
259 VDINTERFACEPROGRESS mVDIfCallsProgress;
260};
261
262class Medium::CreateBaseTask : public Medium::Task
263{
264public:
265 CreateBaseTask(Medium *aMedium,
266 Progress *aProgress,
267 uint64_t aSize,
268 MediumVariant_T aVariant)
269 : Medium::Task(aMedium, aProgress),
270 mSize(aSize),
271 mVariant(aVariant)
272 {}
273
274 uint64_t mSize;
275 MediumVariant_T mVariant;
276
277private:
278 virtual HRESULT handler();
279};
280
281class Medium::CreateDiffTask : public Medium::Task
282{
283public:
284 CreateDiffTask(Medium *aMedium,
285 Progress *aProgress,
286 Medium *aTarget,
287 MediumVariant_T aVariant,
288 MediumLockList *aMediumLockList,
289 bool fKeepMediumLockList = false)
290 : Medium::Task(aMedium, aProgress),
291 mpMediumLockList(aMediumLockList),
292 mTarget(aTarget),
293 mVariant(aVariant),
294 mTargetCaller(aTarget),
295 mfKeepMediumLockList(fKeepMediumLockList)
296 {
297 AssertReturnVoidStmt(aTarget != NULL, mRC = E_FAIL);
298 mRC = mTargetCaller.rc();
299 if (FAILED(mRC))
300 return;
301 }
302
303 ~CreateDiffTask()
304 {
305 if (!mfKeepMediumLockList && mpMediumLockList)
306 delete mpMediumLockList;
307 }
308
309 MediumLockList *mpMediumLockList;
310
311 const ComObjPtr<Medium> mTarget;
312 MediumVariant_T mVariant;
313
314private:
315 virtual HRESULT handler();
316
317 AutoCaller mTargetCaller;
318 bool mfKeepMediumLockList;
319};
320
321class Medium::CloneTask : public Medium::Task
322{
323public:
324 CloneTask(Medium *aMedium,
325 Progress *aProgress,
326 Medium *aTarget,
327 MediumVariant_T aVariant,
328 Medium *aParent,
329 MediumLockList *aSourceMediumLockList,
330 MediumLockList *aTargetMediumLockList,
331 bool fKeepSourceMediumLockList = false,
332 bool fKeepTargetMediumLockList = false)
333 : Medium::Task(aMedium, aProgress),
334 mTarget(aTarget),
335 mParent(aParent),
336 mpSourceMediumLockList(aSourceMediumLockList),
337 mpTargetMediumLockList(aTargetMediumLockList),
338 mVariant(aVariant),
339 mTargetCaller(aTarget),
340 mParentCaller(aParent),
341 mfKeepSourceMediumLockList(fKeepSourceMediumLockList),
342 mfKeepTargetMediumLockList(fKeepTargetMediumLockList)
343 {
344 AssertReturnVoidStmt(aTarget != NULL, mRC = E_FAIL);
345 mRC = mTargetCaller.rc();
346 if (FAILED(mRC))
347 return;
348 /* aParent may be NULL */
349 mRC = mParentCaller.rc();
350 if (FAILED(mRC))
351 return;
352 AssertReturnVoidStmt(aSourceMediumLockList != NULL, mRC = E_FAIL);
353 AssertReturnVoidStmt(aTargetMediumLockList != NULL, mRC = E_FAIL);
354 }
355
356 ~CloneTask()
357 {
358 if (!mfKeepSourceMediumLockList && mpSourceMediumLockList)
359 delete mpSourceMediumLockList;
360 if (!mfKeepTargetMediumLockList && mpTargetMediumLockList)
361 delete mpTargetMediumLockList;
362 }
363
364 const ComObjPtr<Medium> mTarget;
365 const ComObjPtr<Medium> mParent;
366 MediumLockList *mpSourceMediumLockList;
367 MediumLockList *mpTargetMediumLockList;
368 MediumVariant_T mVariant;
369
370private:
371 virtual HRESULT handler();
372
373 AutoCaller mTargetCaller;
374 AutoCaller mParentCaller;
375 bool mfKeepSourceMediumLockList;
376 bool mfKeepTargetMediumLockList;
377};
378
379class Medium::CompactTask : public Medium::Task
380{
381public:
382 CompactTask(Medium *aMedium,
383 Progress *aProgress,
384 MediumLockList *aMediumLockList,
385 bool fKeepMediumLockList = false)
386 : Medium::Task(aMedium, aProgress),
387 mpMediumLockList(aMediumLockList),
388 mfKeepMediumLockList(fKeepMediumLockList)
389 {
390 AssertReturnVoidStmt(aMediumLockList != NULL, mRC = E_FAIL);
391 }
392
393 ~CompactTask()
394 {
395 if (!mfKeepMediumLockList && mpMediumLockList)
396 delete mpMediumLockList;
397 }
398
399 MediumLockList *mpMediumLockList;
400
401private:
402 virtual HRESULT handler();
403
404 bool mfKeepMediumLockList;
405};
406
407class Medium::ResetTask : public Medium::Task
408{
409public:
410 ResetTask(Medium *aMedium,
411 Progress *aProgress,
412 MediumLockList *aMediumLockList,
413 bool fKeepMediumLockList = false)
414 : Medium::Task(aMedium, aProgress),
415 mpMediumLockList(aMediumLockList),
416 mfKeepMediumLockList(fKeepMediumLockList)
417 {}
418
419 ~ResetTask()
420 {
421 if (!mfKeepMediumLockList && mpMediumLockList)
422 delete mpMediumLockList;
423 }
424
425 MediumLockList *mpMediumLockList;
426
427private:
428 virtual HRESULT handler();
429
430 bool mfKeepMediumLockList;
431};
432
433class Medium::DeleteTask : public Medium::Task
434{
435public:
436 DeleteTask(Medium *aMedium,
437 Progress *aProgress,
438 MediumLockList *aMediumLockList,
439 bool fKeepMediumLockList = false)
440 : Medium::Task(aMedium, aProgress),
441 mpMediumLockList(aMediumLockList),
442 mfKeepMediumLockList(fKeepMediumLockList)
443 {}
444
445 ~DeleteTask()
446 {
447 if (!mfKeepMediumLockList && mpMediumLockList)
448 delete mpMediumLockList;
449 }
450
451 MediumLockList *mpMediumLockList;
452
453private:
454 virtual HRESULT handler();
455
456 bool mfKeepMediumLockList;
457};
458
459class Medium::MergeTask : public Medium::Task
460{
461public:
462 MergeTask(Medium *aMedium,
463 Medium *aTarget,
464 bool fMergeForward,
465 Medium *aParentForTarget,
466 const MediaList &aChildrenToReparent,
467 Progress *aProgress,
468 MediumLockList *aMediumLockList,
469 bool fKeepMediumLockList = false)
470 : Medium::Task(aMedium, aProgress),
471 mTarget(aTarget),
472 mfMergeForward(fMergeForward),
473 mParentForTarget(aParentForTarget),
474 mChildrenToReparent(aChildrenToReparent),
475 mpMediumLockList(aMediumLockList),
476 mTargetCaller(aTarget),
477 mParentForTargetCaller(aParentForTarget),
478 mfChildrenCaller(false),
479 mfKeepMediumLockList(fKeepMediumLockList)
480 {
481 AssertReturnVoidStmt(aMediumLockList != NULL, mRC = E_FAIL);
482 for (MediaList::const_iterator it = mChildrenToReparent.begin();
483 it != mChildrenToReparent.end();
484 ++it)
485 {
486 HRESULT rc2 = (*it)->addCaller();
487 if (FAILED(rc2))
488 {
489 mRC = E_FAIL;
490 for (MediaList::const_iterator it2 = mChildrenToReparent.begin();
491 it2 != it;
492 --it2)
493 {
494 (*it2)->releaseCaller();
495 }
496 return;
497 }
498 }
499 mfChildrenCaller = true;
500 }
501
502 ~MergeTask()
503 {
504 if (!mfKeepMediumLockList && mpMediumLockList)
505 delete mpMediumLockList;
506 if (mfChildrenCaller)
507 {
508 for (MediaList::const_iterator it = mChildrenToReparent.begin();
509 it != mChildrenToReparent.end();
510 ++it)
511 {
512 (*it)->releaseCaller();
513 }
514 }
515 }
516
517 const ComObjPtr<Medium> mTarget;
518 bool mfMergeForward;
519 /* When mChildrenToReparent is empty then mParentForTarget is non-null.
520 * In other words: they are used in different cases. */
521 const ComObjPtr<Medium> mParentForTarget;
522 MediaList mChildrenToReparent;
523 MediumLockList *mpMediumLockList;
524
525private:
526 virtual HRESULT handler();
527
528 AutoCaller mTargetCaller;
529 AutoCaller mParentForTargetCaller;
530 bool mfChildrenCaller;
531 bool mfKeepMediumLockList;
532};
533
534/**
535 * Thread function for time-consuming medium tasks.
536 *
537 * @param pvUser Pointer to the Medium::Task instance.
538 */
539/* static */
540DECLCALLBACK(int) Medium::Task::fntMediumTask(RTTHREAD aThread, void *pvUser)
541{
542 LogFlowFuncEnter();
543 AssertReturn(pvUser, (int)E_INVALIDARG);
544 Medium::Task *pTask = static_cast<Medium::Task *>(pvUser);
545
546 pTask->mThread = aThread;
547
548 HRESULT rc = pTask->handler();
549
550 /* complete the progress if run asynchronously */
551 if (pTask->isAsync())
552 {
553 if (!pTask->mProgress.isNull())
554 pTask->mProgress->notifyComplete(rc);
555 }
556
557 /* pTask is no longer needed, delete it. */
558 delete pTask;
559
560 LogFlowFunc(("rc=%Rhrc\n", rc));
561 LogFlowFuncLeave();
562
563 return (int)rc;
564}
565
566/**
567 * PFNVDPROGRESS callback handler for Task operations.
568 *
569 * @param pvUser Pointer to the Progress instance.
570 * @param uPercent Completetion precentage (0-100).
571 */
572/*static*/
573DECLCALLBACK(int) Medium::Task::vdProgressCall(void *pvUser, unsigned uPercent)
574{
575 Progress *that = static_cast<Progress *>(pvUser);
576
577 if (that != NULL)
578 {
579 /* update the progress object, capping it at 99% as the final percent
580 * is used for additional operations like setting the UUIDs and similar. */
581 HRESULT rc = that->SetCurrentOperationProgress(uPercent * 99 / 100);
582 if (FAILED(rc))
583 {
584 if (rc == E_FAIL)
585 return VERR_CANCELLED;
586 else
587 return VERR_INVALID_STATE;
588 }
589 }
590
591 return VINF_SUCCESS;
592}
593
594/**
595 * Implementation code for the "create base" task.
596 */
597HRESULT Medium::CreateBaseTask::handler()
598{
599 return mMedium->taskCreateBaseHandler(*this);
600}
601
602/**
603 * Implementation code for the "create diff" task.
604 */
605HRESULT Medium::CreateDiffTask::handler()
606{
607 return mMedium->taskCreateDiffHandler(*this);
608}
609
610/**
611 * Implementation code for the "clone" task.
612 */
613HRESULT Medium::CloneTask::handler()
614{
615 return mMedium->taskCloneHandler(*this);
616}
617
618/**
619 * Implementation code for the "compact" task.
620 */
621HRESULT Medium::CompactTask::handler()
622{
623 return mMedium->taskCompactHandler(*this);
624}
625
626/**
627 * Implementation code for the "reset" task.
628 */
629HRESULT Medium::ResetTask::handler()
630{
631 return mMedium->taskResetHandler(*this);
632}
633
634/**
635 * Implementation code for the "delete" task.
636 */
637HRESULT Medium::DeleteTask::handler()
638{
639 return mMedium->taskDeleteHandler(*this);
640}
641
642/**
643 * Implementation code for the "merge" task.
644 */
645HRESULT Medium::MergeTask::handler()
646{
647 return mMedium->taskMergeHandler(*this);
648}
649
650
651////////////////////////////////////////////////////////////////////////////////
652//
653// Medium constructor / destructor
654//
655////////////////////////////////////////////////////////////////////////////////
656
657DEFINE_EMPTY_CTOR_DTOR(Medium)
658
659HRESULT Medium::FinalConstruct()
660{
661 m = new Data;
662
663 /* Initialize the callbacks of the VD error interface */
664 m->vdIfCallsError.cbSize = sizeof(VDINTERFACEERROR);
665 m->vdIfCallsError.enmInterface = VDINTERFACETYPE_ERROR;
666 m->vdIfCallsError.pfnError = vdErrorCall;
667 m->vdIfCallsError.pfnMessage = NULL;
668
669 /* Initialize the callbacks of the VD config interface */
670 m->vdIfCallsConfig.cbSize = sizeof(VDINTERFACECONFIG);
671 m->vdIfCallsConfig.enmInterface = VDINTERFACETYPE_CONFIG;
672 m->vdIfCallsConfig.pfnAreKeysValid = vdConfigAreKeysValid;
673 m->vdIfCallsConfig.pfnQuerySize = vdConfigQuerySize;
674 m->vdIfCallsConfig.pfnQuery = vdConfigQuery;
675
676 /* Initialize the callbacks of the VD TCP interface (we always use the host
677 * IP stack for now) */
678 m->vdIfCallsTcpNet.cbSize = sizeof(VDINTERFACETCPNET);
679 m->vdIfCallsTcpNet.enmInterface = VDINTERFACETYPE_TCPNET;
680 m->vdIfCallsTcpNet.pfnSocketCreate = vdTcpSocketCreate;
681 m->vdIfCallsTcpNet.pfnSocketDestroy = vdTcpSocketDestroy;
682 m->vdIfCallsTcpNet.pfnClientConnect = vdTcpClientConnect;
683 m->vdIfCallsTcpNet.pfnClientClose = vdTcpClientClose;
684 m->vdIfCallsTcpNet.pfnIsClientConnected = vdTcpIsClientConnected;
685 m->vdIfCallsTcpNet.pfnSelectOne = vdTcpSelectOne;
686 m->vdIfCallsTcpNet.pfnRead = vdTcpRead;
687 m->vdIfCallsTcpNet.pfnWrite = vdTcpWrite;
688 m->vdIfCallsTcpNet.pfnSgWrite = vdTcpSgWrite;
689 m->vdIfCallsTcpNet.pfnFlush = vdTcpFlush;
690 m->vdIfCallsTcpNet.pfnSetSendCoalescing = vdTcpSetSendCoalescing;
691 m->vdIfCallsTcpNet.pfnGetLocalAddress = vdTcpGetLocalAddress;
692 m->vdIfCallsTcpNet.pfnGetPeerAddress = vdTcpGetPeerAddress;
693 m->vdIfCallsTcpNet.pfnSelectOneEx = NULL;
694 m->vdIfCallsTcpNet.pfnPoke = NULL;
695
696 /* Initialize the per-disk interface chain */
697 int vrc;
698 vrc = VDInterfaceAdd(&m->vdIfError,
699 "Medium::vdInterfaceError",
700 VDINTERFACETYPE_ERROR,
701 &m->vdIfCallsError, this, &m->vdDiskIfaces);
702 AssertRCReturn(vrc, E_FAIL);
703
704 vrc = VDInterfaceAdd(&m->vdIfConfig,
705 "Medium::vdInterfaceConfig",
706 VDINTERFACETYPE_CONFIG,
707 &m->vdIfCallsConfig, this, &m->vdDiskIfaces);
708 AssertRCReturn(vrc, E_FAIL);
709
710 vrc = VDInterfaceAdd(&m->vdIfTcpNet,
711 "Medium::vdInterfaceTcpNet",
712 VDINTERFACETYPE_TCPNET,
713 &m->vdIfCallsTcpNet, this, &m->vdDiskIfaces);
714 AssertRCReturn(vrc, E_FAIL);
715
716 vrc = RTSemEventMultiCreate(&m->queryInfoSem);
717 AssertRCReturn(vrc, E_FAIL);
718 vrc = RTSemEventMultiSignal(m->queryInfoSem);
719 AssertRCReturn(vrc, E_FAIL);
720
721 return S_OK;
722}
723
724void Medium::FinalRelease()
725{
726 uninit();
727
728 delete m;
729}
730
731/**
732 * Initializes an empty hard disk object without creating or opening an associated
733 * storage unit.
734 *
735 * This gets called by VirtualBox::CreateHardDisk().
736 *
737 * For hard disks that don't have the VD_CAP_CREATE_FIXED or
738 * VD_CAP_CREATE_DYNAMIC capability (and therefore cannot be created or deleted
739 * with the means of VirtualBox) the associated storage unit is assumed to be
740 * ready for use so the state of the hard disk object will be set to Created.
741 *
742 * @param aVirtualBox VirtualBox object.
743 * @param aLocation Storage unit location.
744 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
745 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
746 */
747HRESULT Medium::init(VirtualBox *aVirtualBox,
748 const Utf8Str &aFormat,
749 const Utf8Str &aLocation,
750 bool *pfNeedsSaveSettings)
751{
752 AssertReturn(aVirtualBox != NULL, E_FAIL);
753 AssertReturn(!aFormat.isEmpty(), E_FAIL);
754
755 /* Enclose the state transition NotReady->InInit->Ready */
756 AutoInitSpan autoInitSpan(this);
757 AssertReturn(autoInitSpan.isOk(), E_FAIL);
758
759 HRESULT rc = S_OK;
760
761 /* share VirtualBox weakly (parent remains NULL so far) */
762 unconst(m->pVirtualBox) = aVirtualBox;
763
764 /* no storage yet */
765 m->state = MediumState_NotCreated;
766
767 /* cannot be a host drive */
768 m->hostDrive = false;
769
770 /* No storage unit is created yet, no need to queryInfo() */
771
772 rc = setFormat(aFormat);
773 if (FAILED(rc)) return rc;
774
775 if (m->formatObj->getCapabilities() & MediumFormatCapabilities_File)
776 {
777 rc = setLocation(aLocation);
778 if (FAILED(rc)) return rc;
779 }
780 else
781 {
782 rc = setLocation(aLocation);
783 if (FAILED(rc)) return rc;
784 }
785
786 if (!(m->formatObj->getCapabilities() & ( MediumFormatCapabilities_CreateFixed
787 | MediumFormatCapabilities_CreateDynamic))
788 )
789 {
790 /* storage for hard disks of this format can neither be explicitly
791 * created by VirtualBox nor deleted, so we place the hard disk to
792 * Created state here and also add it to the registry */
793 m->state = MediumState_Created;
794 unconst(m->id).create();
795
796 AutoWriteLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
797 rc = m->pVirtualBox->registerHardDisk(this, pfNeedsSaveSettings);
798 }
799
800 /* Confirm a successful initialization when it's the case */
801 if (SUCCEEDED(rc))
802 autoInitSpan.setSucceeded();
803
804 return rc;
805}
806
807/**
808 * Initializes the medium object by opening the storage unit at the specified
809 * location. The enOpenMode parameter defines whether the medium will be opened
810 * read/write or read-only.
811 *
812 * This gets called by VirtualBox::OpenHardDisk(), OpenDVDImage and OpenFloppyImage();
813 * this also gets called by Machine::AttachDevice() and createImplicitDiffs()
814 * when new diff images are created.
815 *
816 * Note that the UUID, format and the parent of this medium will be
817 * determined when reading the medium storage unit, unless new values are
818 * specified by the parameters. If the detected or set parent is
819 * not known to VirtualBox, then this method will fail.
820 *
821 * @param aVirtualBox VirtualBox object.
822 * @param aLocation Storage unit location.
823 * @param enOpenMode Whether to open the medium read/write or read-only.
824 * @param aDeviceType Device type of medium.
825 * @param aSetImageId Whether to set the medium UUID or not.
826 * @param aImageId New medium UUID if @aSetId is true. Empty string means
827 * create a new UUID, and a zero UUID is invalid.
828 * @param aSetParentId Whether to set the parent UUID or not.
829 * @param aParentId New parent UUID if @aSetParentId is true. Empty string
830 * means create a new UUID, and a zero UUID is valid.
831 */
832HRESULT Medium::init(VirtualBox *aVirtualBox,
833 const Utf8Str &aLocation,
834 HDDOpenMode enOpenMode,
835 DeviceType_T aDeviceType,
836 BOOL aSetImageId,
837 const Guid &aImageId,
838 BOOL aSetParentId,
839 const Guid &aParentId)
840{
841 AssertReturn(aVirtualBox, E_INVALIDARG);
842 AssertReturn(!aLocation.isEmpty(), E_INVALIDARG);
843
844 /* Enclose the state transition NotReady->InInit->Ready */
845 AutoInitSpan autoInitSpan(this);
846 AssertReturn(autoInitSpan.isOk(), E_FAIL);
847
848 HRESULT rc = S_OK;
849
850 /* share VirtualBox weakly (parent remains NULL so far) */
851 unconst(m->pVirtualBox) = aVirtualBox;
852
853 /* there must be a storage unit */
854 m->state = MediumState_Created;
855
856 /* remember device type for correct unregistering later */
857 m->devType = aDeviceType;
858
859 /* cannot be a host drive */
860 m->hostDrive = false;
861
862 /* remember the open mode (defaults to ReadWrite) */
863 m->hddOpenMode = enOpenMode;
864
865 if (aDeviceType == DeviceType_HardDisk)
866 rc = setLocation(aLocation);
867 else
868 rc = setLocation(aLocation, "RAW");
869 if (FAILED(rc)) return rc;
870
871 /* save the new uuid values, will be used by queryInfo() */
872 m->setImageId = !!aSetImageId;
873 unconst(m->imageId) = aImageId;
874 m->setParentId = !!aSetParentId;
875 unconst(m->parentId) = aParentId;
876
877 /* get all the information about the medium from the storage unit */
878 rc = queryInfo();
879
880 if (SUCCEEDED(rc))
881 {
882 /* if the storage unit is not accessible, it's not acceptable for the
883 * newly opened media so convert this into an error */
884 if (m->state == MediumState_Inaccessible)
885 {
886 Assert(!m->strLastAccessError.isEmpty());
887 rc = setError(E_FAIL, "%s", m->strLastAccessError.c_str());
888 }
889 else
890 {
891 AssertReturn(!m->id.isEmpty(), E_FAIL);
892
893 /* storage format must be detected by queryInfo() if the medium is accessible */
894 AssertReturn(!m->strFormat.isEmpty(), E_FAIL);
895 }
896 }
897
898 /* Confirm a successful initialization when it's the case */
899 if (SUCCEEDED(rc))
900 autoInitSpan.setSucceeded();
901
902 return rc;
903}
904
905/**
906 * Initializes the medium object by loading its data from the given settings
907 * node. In this mode, the medium will always be opened read/write.
908 *
909 * @param aVirtualBox VirtualBox object.
910 * @param aParent Parent medium disk or NULL for a root (base) medium.
911 * @param aDeviceType Device type of the medium.
912 * @param aNode Configuration settings.
913 *
914 * @note Locks VirtualBox for writing, the medium tree for writing.
915 */
916HRESULT Medium::init(VirtualBox *aVirtualBox,
917 Medium *aParent,
918 DeviceType_T aDeviceType,
919 const settings::Medium &data)
920{
921 using namespace settings;
922
923 AssertReturn(aVirtualBox, E_INVALIDARG);
924
925 /* Enclose the state transition NotReady->InInit->Ready */
926 AutoInitSpan autoInitSpan(this);
927 AssertReturn(autoInitSpan.isOk(), E_FAIL);
928
929 HRESULT rc = S_OK;
930
931 /* share VirtualBox and parent weakly */
932 unconst(m->pVirtualBox) = aVirtualBox;
933
934 /* register with VirtualBox/parent early, since uninit() will
935 * unconditionally unregister on failure */
936 if (aParent)
937 {
938 // differencing medium: add to parent
939 AutoWriteLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
940 m->pParent = aParent;
941 aParent->m->llChildren.push_back(this);
942 }
943
944 /* see below why we don't call queryInfo() (and therefore treat the medium
945 * as inaccessible for now */
946 m->state = MediumState_Inaccessible;
947 m->strLastAccessError = tr("Accessibility check was not yet performed");
948
949 /* required */
950 unconst(m->id) = data.uuid;
951
952 /* assume not a host drive */
953 m->hostDrive = false;
954
955 /* optional */
956 m->strDescription = data.strDescription;
957
958 /* required */
959 if (aDeviceType == DeviceType_HardDisk)
960 {
961 AssertReturn(!data.strFormat.isEmpty(), E_FAIL);
962 rc = setFormat(data.strFormat);
963 if (FAILED(rc)) return rc;
964 }
965 else
966 {
967 /// @todo handle host drive settings here as well?
968 if (!data.strFormat.isEmpty())
969 rc = setFormat(data.strFormat);
970 else
971 rc = setFormat("RAW");
972 if (FAILED(rc)) return rc;
973 }
974
975 /* optional, only for diffs, default is false; we can only auto-reset
976 * diff media so they must have a parent */
977 if (aParent != NULL)
978 m->autoReset = data.fAutoReset;
979 else
980 m->autoReset = false;
981
982 /* properties (after setting the format as it populates the map). Note that
983 * if some properties are not supported but preseint in the settings file,
984 * they will still be read and accessible (for possible backward
985 * compatibility; we can also clean them up from the XML upon next
986 * XML format version change if we wish) */
987 for (settings::PropertiesMap::const_iterator it = data.properties.begin();
988 it != data.properties.end(); ++it)
989 {
990 const Utf8Str &name = it->first;
991 const Utf8Str &value = it->second;
992 m->properties[Bstr(name)] = Bstr(value);
993 }
994
995 /* required */
996 rc = setLocation(data.strLocation);
997 if (FAILED(rc)) return rc;
998
999 if (aDeviceType == DeviceType_HardDisk)
1000 {
1001 /* type is only for base hard disks */
1002 if (m->pParent.isNull())
1003 m->type = data.hdType;
1004 }
1005 else
1006 m->type = MediumType_Writethrough;
1007
1008 /* remember device type for correct unregistering later */
1009 m->devType = aDeviceType;
1010
1011 LogFlowThisFunc(("m->strLocationFull='%s', m->strFormat=%s, m->id={%RTuuid}\n",
1012 m->strLocationFull.raw(), m->strFormat.raw(), m->id.raw()));
1013
1014 /* Don't call queryInfo() for registered media to prevent the calling
1015 * thread (i.e. the VirtualBox server startup thread) from an unexpected
1016 * freeze but mark it as initially inaccessible instead. The vital UUID,
1017 * location and format properties are read from the registry file above; to
1018 * get the actual state and the rest of the data, the user will have to call
1019 * COMGETTER(State). */
1020
1021 AutoWriteLock treeLock(aVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
1022
1023 /* load all children */
1024 for (settings::MediaList::const_iterator it = data.llChildren.begin();
1025 it != data.llChildren.end();
1026 ++it)
1027 {
1028 const settings::Medium &med = *it;
1029
1030 ComObjPtr<Medium> pHD;
1031 pHD.createObject();
1032 rc = pHD->init(aVirtualBox,
1033 this, // parent
1034 aDeviceType,
1035 med); // child data
1036 if (FAILED(rc)) break;
1037
1038 rc = m->pVirtualBox->registerHardDisk(pHD, NULL /*pfNeedsSaveSettings*/);
1039 if (FAILED(rc)) break;
1040 }
1041
1042 /* Confirm a successful initialization when it's the case */
1043 if (SUCCEEDED(rc))
1044 autoInitSpan.setSucceeded();
1045
1046 return rc;
1047}
1048
1049/**
1050 * Initializes the medium object by providing the host drive information.
1051 * Not used for anything but the host floppy/host DVD case.
1052 *
1053 * @param aVirtualBox VirtualBox object.
1054 * @param aDeviceType Device type of the medium.
1055 * @param aLocation Location of the host drive.
1056 * @param aDescription Comment for this host drive.
1057 *
1058 * @note Locks VirtualBox lock for writing.
1059 */
1060HRESULT Medium::init(VirtualBox *aVirtualBox,
1061 DeviceType_T aDeviceType,
1062 const Utf8Str &aLocation,
1063 const Utf8Str &aDescription /* = Utf8Str::Empty */)
1064{
1065 ComAssertRet(aDeviceType == DeviceType_DVD || aDeviceType == DeviceType_Floppy, E_INVALIDARG);
1066 ComAssertRet(!aLocation.isEmpty(), E_INVALIDARG);
1067
1068 /* Enclose the state transition NotReady->InInit->Ready */
1069 AutoInitSpan autoInitSpan(this);
1070 AssertReturn(autoInitSpan.isOk(), E_FAIL);
1071
1072 /* share VirtualBox weakly (parent remains NULL so far) */
1073 unconst(m->pVirtualBox) = aVirtualBox;
1074
1075 /* fake up a UUID which is unique, but also reproducible */
1076 RTUUID uuid;
1077 RTUuidClear(&uuid);
1078 if (aDeviceType == DeviceType_DVD)
1079 memcpy(&uuid.au8[0], "DVD", 3);
1080 else
1081 memcpy(&uuid.au8[0], "FD", 2);
1082 /* use device name, adjusted to the end of uuid, shortened if necessary */
1083 size_t lenLocation = aLocation.length();
1084 if (lenLocation > 12)
1085 memcpy(&uuid.au8[4], aLocation.raw() + (lenLocation - 12), 12);
1086 else
1087 memcpy(&uuid.au8[4 + 12 - lenLocation], aLocation.raw(), lenLocation);
1088 unconst(m->id) = uuid;
1089
1090 m->type = MediumType_Writethrough;
1091 m->devType = aDeviceType;
1092 m->state = MediumState_Created;
1093 m->hostDrive = true;
1094 HRESULT rc = setFormat("RAW");
1095 if (FAILED(rc)) return rc;
1096 rc = setLocation(aLocation);
1097 if (FAILED(rc)) return rc;
1098 m->strDescription = aDescription;
1099
1100/// @todo generate uuid (similarly to host network interface uuid) from location and device type
1101
1102 autoInitSpan.setSucceeded();
1103 return S_OK;
1104}
1105
1106/**
1107 * Uninitializes the instance.
1108 *
1109 * Called either from FinalRelease() or by the parent when it gets destroyed.
1110 *
1111 * @note All children of this medium get uninitialized by calling their
1112 * uninit() methods.
1113 *
1114 * @note Caller must hold the tree lock of the medium tree this medium is on.
1115 */
1116void Medium::uninit()
1117{
1118 /* Enclose the state transition Ready->InUninit->NotReady */
1119 AutoUninitSpan autoUninitSpan(this);
1120 if (autoUninitSpan.uninitDone())
1121 return;
1122
1123 if (!m->formatObj.isNull())
1124 {
1125 /* remove the caller reference we added in setFormat() */
1126 m->formatObj->releaseCaller();
1127 m->formatObj.setNull();
1128 }
1129
1130 if (m->state == MediumState_Deleting)
1131 {
1132 /* we are being uninitialized after've been deleted by merge.
1133 * Reparenting has already been done so don't touch it here (we are
1134 * now orphans and removeDependentChild() will assert) */
1135 Assert(m->pParent.isNull());
1136 }
1137 else
1138 {
1139 MediaList::iterator it;
1140 for (it = m->llChildren.begin();
1141 it != m->llChildren.end();
1142 ++it)
1143 {
1144 Medium *pChild = *it;
1145 pChild->m->pParent.setNull();
1146 pChild->uninit();
1147 }
1148 m->llChildren.clear(); // this unsets all the ComPtrs and probably calls delete
1149
1150 if (m->pParent)
1151 {
1152 // this is a differencing disk: then remove it from the parent's children list
1153 deparent();
1154 }
1155 }
1156
1157 RTSemEventMultiSignal(m->queryInfoSem);
1158 RTSemEventMultiDestroy(m->queryInfoSem);
1159 m->queryInfoSem = NIL_RTSEMEVENTMULTI;
1160
1161 unconst(m->pVirtualBox) = NULL;
1162}
1163
1164/**
1165 * Internal helper that removes "this" from the list of children of its
1166 * parent. Used in uninit() and other places when reparenting is necessary.
1167 *
1168 * The caller must hold the medium tree lock!
1169 */
1170void Medium::deparent()
1171{
1172 MediaList &llParent = m->pParent->m->llChildren;
1173 for (MediaList::iterator it = llParent.begin();
1174 it != llParent.end();
1175 ++it)
1176 {
1177 Medium *pParentsChild = *it;
1178 if (this == pParentsChild)
1179 {
1180 llParent.erase(it);
1181 break;
1182 }
1183 }
1184 m->pParent.setNull();
1185}
1186
1187/**
1188 * Internal helper that removes "this" from the list of children of its
1189 * parent. Used in uninit() and other places when reparenting is necessary.
1190 *
1191 * The caller must hold the medium tree lock!
1192 */
1193void Medium::setParent(const ComObjPtr<Medium> &pParent)
1194{
1195 m->pParent = pParent;
1196 if (pParent)
1197 pParent->m->llChildren.push_back(this);
1198}
1199
1200
1201////////////////////////////////////////////////////////////////////////////////
1202//
1203// IMedium public methods
1204//
1205////////////////////////////////////////////////////////////////////////////////
1206
1207STDMETHODIMP Medium::COMGETTER(Id)(BSTR *aId)
1208{
1209 CheckComArgOutPointerValid(aId);
1210
1211 AutoCaller autoCaller(this);
1212 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1213
1214 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1215
1216 m->id.toUtf16().cloneTo(aId);
1217
1218 return S_OK;
1219}
1220
1221STDMETHODIMP Medium::COMGETTER(Description)(BSTR *aDescription)
1222{
1223 CheckComArgOutPointerValid(aDescription);
1224
1225 AutoCaller autoCaller(this);
1226 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1227
1228 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1229
1230 m->strDescription.cloneTo(aDescription);
1231
1232 return S_OK;
1233}
1234
1235STDMETHODIMP Medium::COMSETTER(Description)(IN_BSTR aDescription)
1236{
1237 AutoCaller autoCaller(this);
1238 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1239
1240// AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1241
1242 /// @todo update m->description and save the global registry (and local
1243 /// registries of portable VMs referring to this medium), this will also
1244 /// require to add the mRegistered flag to data
1245
1246 NOREF(aDescription);
1247
1248 ReturnComNotImplemented();
1249}
1250
1251STDMETHODIMP Medium::COMGETTER(State)(MediumState_T *aState)
1252{
1253 CheckComArgOutPointerValid(aState);
1254
1255 AutoCaller autoCaller(this);
1256 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1257
1258 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1259 *aState = m->state;
1260
1261 return S_OK;
1262}
1263
1264STDMETHODIMP Medium::COMGETTER(Variant)(MediumVariant_T *aVariant)
1265{
1266 CheckComArgOutPointerValid(aVariant);
1267
1268 AutoCaller autoCaller(this);
1269 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1270
1271 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1272 *aVariant = m->variant;
1273
1274 return S_OK;
1275}
1276
1277
1278STDMETHODIMP Medium::COMGETTER(Location)(BSTR *aLocation)
1279{
1280 CheckComArgOutPointerValid(aLocation);
1281
1282 AutoCaller autoCaller(this);
1283 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1284
1285 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1286
1287 m->strLocationFull.cloneTo(aLocation);
1288
1289 return S_OK;
1290}
1291
1292STDMETHODIMP Medium::COMSETTER(Location)(IN_BSTR aLocation)
1293{
1294 CheckComArgStrNotEmptyOrNull(aLocation);
1295
1296 AutoCaller autoCaller(this);
1297 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1298
1299 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1300
1301 /// @todo NEWMEDIA for file names, add the default extension if no extension
1302 /// is present (using the information from the VD backend which also implies
1303 /// that one more parameter should be passed to setLocation() requesting
1304 /// that functionality since it is only allwed when called from this method
1305
1306 /// @todo NEWMEDIA rename the file and set m->location on success, then save
1307 /// the global registry (and local registries of portable VMs referring to
1308 /// this medium), this will also require to add the mRegistered flag to data
1309
1310 ReturnComNotImplemented();
1311}
1312
1313STDMETHODIMP Medium::COMGETTER(Name)(BSTR *aName)
1314{
1315 CheckComArgOutPointerValid(aName);
1316
1317 AutoCaller autoCaller(this);
1318 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1319
1320 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1321
1322 getName().cloneTo(aName);
1323
1324 return S_OK;
1325}
1326
1327STDMETHODIMP Medium::COMGETTER(DeviceType)(DeviceType_T *aDeviceType)
1328{
1329 CheckComArgOutPointerValid(aDeviceType);
1330
1331 AutoCaller autoCaller(this);
1332 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1333
1334 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1335
1336 *aDeviceType = m->devType;
1337
1338 return S_OK;
1339}
1340
1341STDMETHODIMP Medium::COMGETTER(HostDrive)(BOOL *aHostDrive)
1342{
1343 CheckComArgOutPointerValid(aHostDrive);
1344
1345 AutoCaller autoCaller(this);
1346 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1347
1348 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1349
1350 *aHostDrive = m->hostDrive;
1351
1352 return S_OK;
1353}
1354
1355STDMETHODIMP Medium::COMGETTER(Size)(ULONG64 *aSize)
1356{
1357 CheckComArgOutPointerValid(aSize);
1358
1359 AutoCaller autoCaller(this);
1360 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1361
1362 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1363
1364 *aSize = m->size;
1365
1366 return S_OK;
1367}
1368
1369STDMETHODIMP Medium::COMGETTER(Format)(BSTR *aFormat)
1370{
1371 CheckComArgOutPointerValid(aFormat);
1372
1373 AutoCaller autoCaller(this);
1374 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1375
1376 /* no need to lock, m->strFormat is const */
1377 m->strFormat.cloneTo(aFormat);
1378
1379 return S_OK;
1380}
1381
1382STDMETHODIMP Medium::COMGETTER(MediumFormat)(IMediumFormat **aMediumFormat)
1383{
1384 CheckComArgOutPointerValid(aMediumFormat);
1385
1386 AutoCaller autoCaller(this);
1387 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1388
1389 /* no need to lock, m->formatObj is const */
1390 m->formatObj.queryInterfaceTo(aMediumFormat);
1391
1392 return S_OK;
1393}
1394
1395STDMETHODIMP Medium::COMGETTER(Type)(MediumType_T *aType)
1396{
1397 CheckComArgOutPointerValid(aType);
1398
1399 AutoCaller autoCaller(this);
1400 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1401
1402 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1403
1404 *aType = m->type;
1405
1406 return S_OK;
1407}
1408
1409STDMETHODIMP Medium::COMSETTER(Type)(MediumType_T aType)
1410{
1411 AutoCaller autoCaller(this);
1412 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1413
1414 // we access mParent and members
1415 AutoMultiWriteLock2 mlock(&m->pVirtualBox->getMediaTreeLockHandle(), this->lockHandle() COMMA_LOCKVAL_SRC_POS);
1416
1417 switch (m->state)
1418 {
1419 case MediumState_Created:
1420 case MediumState_Inaccessible:
1421 break;
1422 default:
1423 return setStateError();
1424 }
1425
1426 if (m->type == aType)
1427 {
1428 /* Nothing to do */
1429 return S_OK;
1430 }
1431
1432 /* cannot change the type of a differencing medium */
1433 if (m->pParent)
1434 return setError(VBOX_E_INVALID_OBJECT_STATE,
1435 tr("Cannot change the type of medium '%s' because it is a differencing medium"),
1436 m->strLocationFull.raw());
1437
1438 /* cannot change the type of a medium being in use by more than one VM */
1439 if (m->backRefs.size() > 1)
1440 return setError(VBOX_E_INVALID_OBJECT_STATE,
1441 tr("Cannot change the type of medium '%s' because it is attached to %d virtual machines"),
1442 m->strLocationFull.raw(), m->backRefs.size());
1443
1444 switch (aType)
1445 {
1446 case MediumType_Normal:
1447 case MediumType_Immutable:
1448 {
1449 /* normal can be easily converted to immutable and vice versa even
1450 * if they have children as long as they are not attached to any
1451 * machine themselves */
1452 break;
1453 }
1454 case MediumType_Writethrough:
1455 case MediumType_Shareable:
1456 {
1457 /* cannot change to writethrough or shareable if there are children */
1458 if (getChildren().size() != 0)
1459 return setError(VBOX_E_OBJECT_IN_USE,
1460 tr("Cannot change type for medium '%s' since it has %d child media"),
1461 m->strLocationFull.raw(), getChildren().size());
1462 if (aType == MediumType_Shareable)
1463 {
1464 MediumVariant_T variant = getVariant();
1465 if (!(variant & MediumVariant_Fixed))
1466 return setError(VBOX_E_INVALID_OBJECT_STATE,
1467 tr("Cannot change type for medium '%s' to 'Shareable' since it is a dynamic medium storage unit"),
1468 m->strLocationFull.raw());
1469 }
1470 break;
1471 }
1472 default:
1473 AssertFailedReturn(E_FAIL);
1474 }
1475
1476 m->type = aType;
1477
1478 // save the global settings; for that we should hold only the VirtualBox lock
1479 mlock.release();
1480 AutoWriteLock alock(m->pVirtualBox COMMA_LOCKVAL_SRC_POS);
1481 HRESULT rc = m->pVirtualBox->saveSettings();
1482
1483 return rc;
1484}
1485
1486STDMETHODIMP Medium::COMGETTER(Parent)(IMedium **aParent)
1487{
1488 CheckComArgOutPointerValid(aParent);
1489
1490 AutoCaller autoCaller(this);
1491 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1492
1493 /* we access mParent */
1494 AutoReadLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
1495
1496 m->pParent.queryInterfaceTo(aParent);
1497
1498 return S_OK;
1499}
1500
1501STDMETHODIMP Medium::COMGETTER(Children)(ComSafeArrayOut(IMedium *, aChildren))
1502{
1503 CheckComArgOutSafeArrayPointerValid(aChildren);
1504
1505 AutoCaller autoCaller(this);
1506 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1507
1508 /* we access children */
1509 AutoReadLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
1510
1511 SafeIfaceArray<IMedium> children(this->getChildren());
1512 children.detachTo(ComSafeArrayOutArg(aChildren));
1513
1514 return S_OK;
1515}
1516
1517STDMETHODIMP Medium::COMGETTER(Base)(IMedium **aBase)
1518{
1519 CheckComArgOutPointerValid(aBase);
1520
1521 /* base() will do callers/locking */
1522
1523 getBase().queryInterfaceTo(aBase);
1524
1525 return S_OK;
1526}
1527
1528STDMETHODIMP Medium::COMGETTER(ReadOnly)(BOOL *aReadOnly)
1529{
1530 CheckComArgOutPointerValid(aReadOnly);
1531
1532 AutoCaller autoCaller(this);
1533 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1534
1535 /* isRadOnly() will do locking */
1536
1537 *aReadOnly = isReadOnly();
1538
1539 return S_OK;
1540}
1541
1542STDMETHODIMP Medium::COMGETTER(LogicalSize)(ULONG64 *aLogicalSize)
1543{
1544 CheckComArgOutPointerValid(aLogicalSize);
1545
1546 {
1547 AutoCaller autoCaller(this);
1548 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1549
1550 /* we access mParent */
1551 AutoReadLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
1552
1553 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1554
1555 if (m->pParent.isNull())
1556 {
1557 *aLogicalSize = m->logicalSize;
1558
1559 return S_OK;
1560 }
1561 }
1562
1563 /* We assume that some backend may decide to return a meaningless value in
1564 * response to VDGetSize() for differencing media and therefore always
1565 * ask the base medium ourselves. */
1566
1567 /* base() will do callers/locking */
1568
1569 return getBase()->COMGETTER(LogicalSize)(aLogicalSize);
1570}
1571
1572STDMETHODIMP Medium::COMGETTER(AutoReset)(BOOL *aAutoReset)
1573{
1574 CheckComArgOutPointerValid(aAutoReset);
1575
1576 AutoCaller autoCaller(this);
1577 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1578
1579 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1580
1581 if (m->pParent.isNull())
1582 *aAutoReset = FALSE;
1583 else
1584 *aAutoReset = m->autoReset;
1585
1586 return S_OK;
1587}
1588
1589STDMETHODIMP Medium::COMSETTER(AutoReset)(BOOL aAutoReset)
1590{
1591 AutoCaller autoCaller(this);
1592 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1593
1594 AutoWriteLock mlock(this COMMA_LOCKVAL_SRC_POS);
1595
1596 if (m->pParent.isNull())
1597 return setError(VBOX_E_NOT_SUPPORTED,
1598 tr("Medium '%s' is not differencing"),
1599 m->strLocationFull.raw());
1600
1601 if (m->autoReset != !!aAutoReset)
1602 {
1603 m->autoReset = !!aAutoReset;
1604
1605 // save the global settings; for that we should hold only the VirtualBox lock
1606 mlock.release();
1607 AutoWriteLock alock(m->pVirtualBox COMMA_LOCKVAL_SRC_POS);
1608 return m->pVirtualBox->saveSettings();
1609 }
1610
1611 return S_OK;
1612}
1613STDMETHODIMP Medium::COMGETTER(LastAccessError)(BSTR *aLastAccessError)
1614{
1615 CheckComArgOutPointerValid(aLastAccessError);
1616
1617 AutoCaller autoCaller(this);
1618 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1619
1620 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1621
1622 m->strLastAccessError.cloneTo(aLastAccessError);
1623
1624 return S_OK;
1625}
1626
1627STDMETHODIMP Medium::COMGETTER(MachineIds)(ComSafeArrayOut(BSTR,aMachineIds))
1628{
1629 CheckComArgOutSafeArrayPointerValid(aMachineIds);
1630
1631 AutoCaller autoCaller(this);
1632 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1633
1634 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1635
1636 com::SafeArray<BSTR> machineIds;
1637
1638 if (m->backRefs.size() != 0)
1639 {
1640 machineIds.reset(m->backRefs.size());
1641
1642 size_t i = 0;
1643 for (BackRefList::const_iterator it = m->backRefs.begin();
1644 it != m->backRefs.end(); ++it, ++i)
1645 {
1646 it->machineId.toUtf16().detachTo(&machineIds[i]);
1647 }
1648 }
1649
1650 machineIds.detachTo(ComSafeArrayOutArg(aMachineIds));
1651
1652 return S_OK;
1653}
1654
1655STDMETHODIMP Medium::RefreshState(MediumState_T *aState)
1656{
1657 CheckComArgOutPointerValid(aState);
1658
1659 AutoCaller autoCaller(this);
1660 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1661
1662 /* queryInfo() locks this for writing. */
1663 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1664
1665 HRESULT rc = S_OK;
1666
1667 switch (m->state)
1668 {
1669 case MediumState_Created:
1670 case MediumState_Inaccessible:
1671 case MediumState_LockedRead:
1672 {
1673 rc = queryInfo();
1674 break;
1675 }
1676 default:
1677 break;
1678 }
1679
1680 *aState = m->state;
1681
1682 return rc;
1683}
1684
1685STDMETHODIMP Medium::GetSnapshotIds(IN_BSTR aMachineId,
1686 ComSafeArrayOut(BSTR, aSnapshotIds))
1687{
1688 CheckComArgExpr(aMachineId, Guid(aMachineId).isEmpty() == false);
1689 CheckComArgOutSafeArrayPointerValid(aSnapshotIds);
1690
1691 AutoCaller autoCaller(this);
1692 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1693
1694 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1695
1696 com::SafeArray<BSTR> snapshotIds;
1697
1698 Guid id(aMachineId);
1699 for (BackRefList::const_iterator it = m->backRefs.begin();
1700 it != m->backRefs.end(); ++it)
1701 {
1702 if (it->machineId == id)
1703 {
1704 size_t size = it->llSnapshotIds.size();
1705
1706 /* if the medium is attached to the machine in the current state, we
1707 * return its ID as the first element of the array */
1708 if (it->fInCurState)
1709 ++size;
1710
1711 if (size > 0)
1712 {
1713 snapshotIds.reset(size);
1714
1715 size_t j = 0;
1716 if (it->fInCurState)
1717 it->machineId.toUtf16().detachTo(&snapshotIds[j++]);
1718
1719 for (BackRef::GuidList::const_iterator jt = it->llSnapshotIds.begin();
1720 jt != it->llSnapshotIds.end();
1721 ++jt, ++j)
1722 {
1723 (*jt).toUtf16().detachTo(&snapshotIds[j]);
1724 }
1725 }
1726
1727 break;
1728 }
1729 }
1730
1731 snapshotIds.detachTo(ComSafeArrayOutArg(aSnapshotIds));
1732
1733 return S_OK;
1734}
1735
1736/**
1737 * @note @a aState may be NULL if the state value is not needed (only for
1738 * in-process calls).
1739 */
1740STDMETHODIMP Medium::LockRead(MediumState_T *aState)
1741{
1742 AutoCaller autoCaller(this);
1743 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1744
1745 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1746
1747 /* Wait for a concurrently running queryInfo() to complete */
1748 while (m->queryInfoRunning)
1749 {
1750 alock.leave();
1751 RTSemEventMultiWait(m->queryInfoSem, RT_INDEFINITE_WAIT);
1752 alock.enter();
1753 }
1754
1755 /* return the current state before */
1756 if (aState)
1757 *aState = m->state;
1758
1759 HRESULT rc = S_OK;
1760
1761 switch (m->state)
1762 {
1763 case MediumState_Created:
1764 case MediumState_Inaccessible:
1765 case MediumState_LockedRead:
1766 {
1767 ++m->readers;
1768
1769 ComAssertMsgBreak(m->readers != 0, ("Counter overflow"), rc = E_FAIL);
1770
1771 /* Remember pre-lock state */
1772 if (m->state != MediumState_LockedRead)
1773 m->preLockState = m->state;
1774
1775 LogFlowThisFunc(("Okay - prev state=%d readers=%d\n", m->state, m->readers));
1776 m->state = MediumState_LockedRead;
1777
1778 break;
1779 }
1780 default:
1781 {
1782 LogFlowThisFunc(("Failing - state=%d\n", m->state));
1783 rc = setStateError();
1784 break;
1785 }
1786 }
1787
1788 return rc;
1789}
1790
1791/**
1792 * @note @a aState may be NULL if the state value is not needed (only for
1793 * in-process calls).
1794 */
1795STDMETHODIMP Medium::UnlockRead(MediumState_T *aState)
1796{
1797 AutoCaller autoCaller(this);
1798 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1799
1800 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1801
1802 HRESULT rc = S_OK;
1803
1804 switch (m->state)
1805 {
1806 case MediumState_LockedRead:
1807 {
1808 Assert(m->readers != 0);
1809 --m->readers;
1810
1811 /* Reset the state after the last reader */
1812 if (m->readers == 0)
1813 {
1814 m->state = m->preLockState;
1815 /* There are cases where we inject the deleting state into
1816 * a medium locked for reading. Make sure #unmarkForDeletion()
1817 * gets the right state afterwards. */
1818 if (m->preLockState == MediumState_Deleting)
1819 m->preLockState = MediumState_Created;
1820 }
1821
1822 LogFlowThisFunc(("new state=%d\n", m->state));
1823 break;
1824 }
1825 default:
1826 {
1827 LogFlowThisFunc(("Failing - state=%d\n", m->state));
1828 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
1829 tr("Medium '%s' is not locked for reading"),
1830 m->strLocationFull.raw());
1831 break;
1832 }
1833 }
1834
1835 /* return the current state after */
1836 if (aState)
1837 *aState = m->state;
1838
1839 return rc;
1840}
1841
1842/**
1843 * @note @a aState may be NULL if the state value is not needed (only for
1844 * in-process calls).
1845 */
1846STDMETHODIMP Medium::LockWrite(MediumState_T *aState)
1847{
1848 AutoCaller autoCaller(this);
1849 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1850
1851 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1852
1853 /* Wait for a concurrently running queryInfo() to complete */
1854 while (m->queryInfoRunning)
1855 {
1856 alock.leave();
1857 RTSemEventMultiWait(m->queryInfoSem, RT_INDEFINITE_WAIT);
1858 alock.enter();
1859 }
1860
1861 /* return the current state before */
1862 if (aState)
1863 *aState = m->state;
1864
1865 HRESULT rc = S_OK;
1866
1867 switch (m->state)
1868 {
1869 case MediumState_Created:
1870 case MediumState_Inaccessible:
1871 {
1872 m->preLockState = m->state;
1873
1874 LogFlowThisFunc(("Okay - prev state=%d locationFull=%s\n", m->state, getLocationFull().c_str()));
1875 m->state = MediumState_LockedWrite;
1876 break;
1877 }
1878 default:
1879 {
1880 LogFlowThisFunc(("Failing - state=%d locationFull=%s\n", m->state, getLocationFull().c_str()));
1881 rc = setStateError();
1882 break;
1883 }
1884 }
1885
1886 return rc;
1887}
1888
1889/**
1890 * @note @a aState may be NULL if the state value is not needed (only for
1891 * in-process calls).
1892 */
1893STDMETHODIMP Medium::UnlockWrite(MediumState_T *aState)
1894{
1895 AutoCaller autoCaller(this);
1896 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1897
1898 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
1899
1900 HRESULT rc = S_OK;
1901
1902 switch (m->state)
1903 {
1904 case MediumState_LockedWrite:
1905 {
1906 m->state = m->preLockState;
1907 /* There are cases where we inject the deleting state into
1908 * a medium locked for writing. Make sure #unmarkForDeletion()
1909 * gets the right state afterwards. */
1910 if (m->preLockState == MediumState_Deleting)
1911 m->preLockState = MediumState_Created;
1912 LogFlowThisFunc(("new state=%d locationFull=%s\n", m->state, getLocationFull().c_str()));
1913 break;
1914 }
1915 default:
1916 {
1917 LogFlowThisFunc(("Failing - state=%d locationFull=%s\n", m->state, getLocationFull().c_str()));
1918 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
1919 tr("Medium '%s' is not locked for writing"),
1920 m->strLocationFull.raw());
1921 break;
1922 }
1923 }
1924
1925 /* return the current state after */
1926 if (aState)
1927 *aState = m->state;
1928
1929 return rc;
1930}
1931
1932STDMETHODIMP Medium::Close()
1933{
1934 AutoCaller autoCaller(this);
1935 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1936
1937 // make a copy of VirtualBox pointer which gets nulled by uninit()
1938 ComObjPtr<VirtualBox> pVirtualBox(m->pVirtualBox);
1939
1940 bool fNeedsSaveSettings = false;
1941 HRESULT rc = close(&fNeedsSaveSettings, autoCaller);
1942
1943 if (fNeedsSaveSettings)
1944 {
1945 AutoWriteLock vboxlock(pVirtualBox COMMA_LOCKVAL_SRC_POS);
1946 pVirtualBox->saveSettings();
1947 }
1948
1949 return rc;
1950}
1951
1952STDMETHODIMP Medium::GetProperty(IN_BSTR aName, BSTR *aValue)
1953{
1954 CheckComArgStrNotEmptyOrNull(aName);
1955 CheckComArgOutPointerValid(aValue);
1956
1957 AutoCaller autoCaller(this);
1958 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1959
1960 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
1961
1962 Data::PropertyMap::const_iterator it = m->properties.find(Bstr(aName));
1963 if (it == m->properties.end())
1964 return setError(VBOX_E_OBJECT_NOT_FOUND,
1965 tr("Property '%ls' does not exist"), aName);
1966
1967 it->second.cloneTo(aValue);
1968
1969 return S_OK;
1970}
1971
1972STDMETHODIMP Medium::SetProperty(IN_BSTR aName, IN_BSTR aValue)
1973{
1974 CheckComArgStrNotEmptyOrNull(aName);
1975
1976 AutoCaller autoCaller(this);
1977 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1978
1979 AutoWriteLock mlock(this COMMA_LOCKVAL_SRC_POS);
1980
1981 switch (m->state)
1982 {
1983 case MediumState_Created:
1984 case MediumState_Inaccessible:
1985 break;
1986 default:
1987 return setStateError();
1988 }
1989
1990 Data::PropertyMap::iterator it = m->properties.find(Bstr(aName));
1991 if (it == m->properties.end())
1992 return setError(VBOX_E_OBJECT_NOT_FOUND,
1993 tr("Property '%ls' does not exist"),
1994 aName);
1995
1996 if (aValue && !*aValue)
1997 it->second = (const char *)NULL;
1998 else
1999 it->second = aValue;
2000
2001 // save the global settings; for that we should hold only the VirtualBox lock
2002 mlock.release();
2003 AutoWriteLock alock(m->pVirtualBox COMMA_LOCKVAL_SRC_POS);
2004 HRESULT rc = m->pVirtualBox->saveSettings();
2005
2006 return rc;
2007}
2008
2009STDMETHODIMP Medium::GetProperties(IN_BSTR aNames,
2010 ComSafeArrayOut(BSTR, aReturnNames),
2011 ComSafeArrayOut(BSTR, aReturnValues))
2012{
2013 CheckComArgOutSafeArrayPointerValid(aReturnNames);
2014 CheckComArgOutSafeArrayPointerValid(aReturnValues);
2015
2016 AutoCaller autoCaller(this);
2017 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2018
2019 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2020
2021 /// @todo make use of aNames according to the documentation
2022 NOREF(aNames);
2023
2024 com::SafeArray<BSTR> names(m->properties.size());
2025 com::SafeArray<BSTR> values(m->properties.size());
2026 size_t i = 0;
2027
2028 for (Data::PropertyMap::const_iterator it = m->properties.begin();
2029 it != m->properties.end();
2030 ++it)
2031 {
2032 it->first.cloneTo(&names[i]);
2033 it->second.cloneTo(&values[i]);
2034 ++i;
2035 }
2036
2037 names.detachTo(ComSafeArrayOutArg(aReturnNames));
2038 values.detachTo(ComSafeArrayOutArg(aReturnValues));
2039
2040 return S_OK;
2041}
2042
2043STDMETHODIMP Medium::SetProperties(ComSafeArrayIn(IN_BSTR, aNames),
2044 ComSafeArrayIn(IN_BSTR, aValues))
2045{
2046 CheckComArgSafeArrayNotNull(aNames);
2047 CheckComArgSafeArrayNotNull(aValues);
2048
2049 AutoCaller autoCaller(this);
2050 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2051
2052 AutoWriteLock mlock(this COMMA_LOCKVAL_SRC_POS);
2053
2054 com::SafeArray<IN_BSTR> names(ComSafeArrayInArg(aNames));
2055 com::SafeArray<IN_BSTR> values(ComSafeArrayInArg(aValues));
2056
2057 /* first pass: validate names */
2058 for (size_t i = 0;
2059 i < names.size();
2060 ++i)
2061 {
2062 if (m->properties.find(Bstr(names[i])) == m->properties.end())
2063 return setError(VBOX_E_OBJECT_NOT_FOUND,
2064 tr("Property '%ls' does not exist"), names[i]);
2065 }
2066
2067 /* second pass: assign */
2068 for (size_t i = 0;
2069 i < names.size();
2070 ++i)
2071 {
2072 Data::PropertyMap::iterator it = m->properties.find(Bstr(names[i]));
2073 AssertReturn(it != m->properties.end(), E_FAIL);
2074
2075 if (values[i] && !*values[i])
2076 it->second = (const char *)NULL;
2077 else
2078 it->second = values[i];
2079 }
2080
2081 mlock.release();
2082
2083 // saveSettings needs vbox lock
2084 AutoWriteLock alock(m->pVirtualBox COMMA_LOCKVAL_SRC_POS);
2085 HRESULT rc = m->pVirtualBox->saveSettings();
2086
2087 return rc;
2088}
2089
2090STDMETHODIMP Medium::CreateBaseStorage(ULONG64 aLogicalSize,
2091 MediumVariant_T aVariant,
2092 IProgress **aProgress)
2093{
2094 CheckComArgOutPointerValid(aProgress);
2095
2096 AutoCaller autoCaller(this);
2097 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2098
2099 HRESULT rc = S_OK;
2100 ComObjPtr <Progress> pProgress;
2101 Medium::Task *pTask = NULL;
2102
2103 try
2104 {
2105 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2106
2107 aVariant = (MediumVariant_T)((unsigned)aVariant & (unsigned)~MediumVariant_Diff);
2108 if ( !(aVariant & MediumVariant_Fixed)
2109 && !(m->formatObj->getCapabilities() & MediumFormatCapabilities_CreateDynamic))
2110 throw setError(VBOX_E_NOT_SUPPORTED,
2111 tr("Medium format '%s' does not support dynamic storage creation"),
2112 m->strFormat.raw());
2113 if ( (aVariant & MediumVariant_Fixed)
2114 && !(m->formatObj->getCapabilities() & MediumFormatCapabilities_CreateDynamic))
2115 throw setError(VBOX_E_NOT_SUPPORTED,
2116 tr("Medium format '%s' does not support fixed storage creation"),
2117 m->strFormat.raw());
2118
2119 if (m->state != MediumState_NotCreated)
2120 throw setStateError();
2121
2122 pProgress.createObject();
2123 rc = pProgress->init(m->pVirtualBox,
2124 static_cast<IMedium*>(this),
2125 (aVariant & MediumVariant_Fixed)
2126 ? BstrFmt(tr("Creating fixed medium storage unit '%s'"), m->strLocationFull.raw())
2127 : BstrFmt(tr("Creating dynamic medium storage unit '%s'"), m->strLocationFull.raw()),
2128 TRUE /* aCancelable */);
2129 if (FAILED(rc))
2130 throw rc;
2131
2132 /* setup task object to carry out the operation asynchronously */
2133 pTask = new Medium::CreateBaseTask(this, pProgress, aLogicalSize,
2134 aVariant);
2135 rc = pTask->rc();
2136 AssertComRC(rc);
2137 if (FAILED(rc))
2138 throw rc;
2139
2140 m->state = MediumState_Creating;
2141 }
2142 catch (HRESULT aRC) { rc = aRC; }
2143
2144 if (SUCCEEDED(rc))
2145 {
2146 rc = startThread(pTask);
2147
2148 if (SUCCEEDED(rc))
2149 pProgress.queryInterfaceTo(aProgress);
2150 }
2151 else if (pTask != NULL)
2152 delete pTask;
2153
2154 return rc;
2155}
2156
2157STDMETHODIMP Medium::DeleteStorage(IProgress **aProgress)
2158{
2159 CheckComArgOutPointerValid(aProgress);
2160
2161 AutoCaller autoCaller(this);
2162 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2163
2164 bool fNeedsSaveSettings = false;
2165 ComObjPtr<Progress> pProgress;
2166
2167 HRESULT rc = deleteStorage(&pProgress,
2168 false /* aWait */,
2169 &fNeedsSaveSettings);
2170 if (fNeedsSaveSettings)
2171 {
2172 AutoWriteLock vboxlock(m->pVirtualBox COMMA_LOCKVAL_SRC_POS);
2173 m->pVirtualBox->saveSettings();
2174 }
2175
2176 if (SUCCEEDED(rc))
2177 pProgress.queryInterfaceTo(aProgress);
2178
2179 return rc;
2180}
2181
2182STDMETHODIMP Medium::CreateDiffStorage(IMedium *aTarget,
2183 MediumVariant_T aVariant,
2184 IProgress **aProgress)
2185{
2186 CheckComArgNotNull(aTarget);
2187 CheckComArgOutPointerValid(aProgress);
2188
2189 AutoCaller autoCaller(this);
2190 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2191
2192 ComObjPtr<Medium> diff = static_cast<Medium*>(aTarget);
2193
2194 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2195
2196 if (m->type == MediumType_Writethrough)
2197 return setError(VBOX_E_INVALID_OBJECT_STATE,
2198 tr("Medium type of '%s' is Writethrough"),
2199 m->strLocationFull.raw());
2200 else if (m->type == MediumType_Shareable)
2201 return setError(VBOX_E_INVALID_OBJECT_STATE,
2202 tr("Medium type of '%s' is Shareable"),
2203 m->strLocationFull.raw());
2204
2205 /* Apply the normal locking logic to the entire chain. */
2206 MediumLockList *pMediumLockList(new MediumLockList());
2207 HRESULT rc = diff->createMediumLockList(true /* fFailIfInaccessible */,
2208 true /* fMediumLockWrite */,
2209 this,
2210 *pMediumLockList);
2211 if (FAILED(rc))
2212 {
2213 delete pMediumLockList;
2214 return rc;
2215 }
2216
2217 ComObjPtr <Progress> pProgress;
2218
2219 rc = createDiffStorage(diff, aVariant, pMediumLockList, &pProgress,
2220 false /* aWait */, NULL /* pfNeedsSaveSettings*/);
2221 if (FAILED(rc))
2222 delete pMediumLockList;
2223 else
2224 pProgress.queryInterfaceTo(aProgress);
2225
2226 return rc;
2227}
2228
2229STDMETHODIMP Medium::MergeTo(IMedium *aTarget, IProgress **aProgress)
2230{
2231 CheckComArgNotNull(aTarget);
2232 CheckComArgOutPointerValid(aProgress);
2233 ComAssertRet(aTarget != this, E_INVALIDARG);
2234
2235 AutoCaller autoCaller(this);
2236 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2237
2238 ComObjPtr<Medium> pTarget = static_cast<Medium*>(aTarget);
2239
2240 bool fMergeForward = false;
2241 ComObjPtr<Medium> pParentForTarget;
2242 MediaList childrenToReparent;
2243 MediumLockList *pMediumLockList = NULL;
2244
2245 HRESULT rc = S_OK;
2246
2247 rc = prepareMergeTo(pTarget, NULL, NULL, true, fMergeForward,
2248 pParentForTarget, childrenToReparent, pMediumLockList);
2249 if (FAILED(rc)) return rc;
2250
2251 ComObjPtr <Progress> pProgress;
2252
2253 rc = mergeTo(pTarget, fMergeForward, pParentForTarget, childrenToReparent,
2254 pMediumLockList, &pProgress, false /* aWait */,
2255 NULL /* pfNeedsSaveSettings */);
2256 if (FAILED(rc))
2257 cancelMergeTo(childrenToReparent, pMediumLockList);
2258 else
2259 pProgress.queryInterfaceTo(aProgress);
2260
2261 return rc;
2262}
2263
2264STDMETHODIMP Medium::CloneTo(IMedium *aTarget,
2265 MediumVariant_T aVariant,
2266 IMedium *aParent,
2267 IProgress **aProgress)
2268{
2269 CheckComArgNotNull(aTarget);
2270 CheckComArgOutPointerValid(aProgress);
2271 ComAssertRet(aTarget != this, E_INVALIDARG);
2272
2273 AutoCaller autoCaller(this);
2274 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2275
2276 ComObjPtr<Medium> pTarget = static_cast<Medium*>(aTarget);
2277 ComObjPtr<Medium> pParent;
2278 if (aParent)
2279 pParent = static_cast<Medium*>(aParent);
2280
2281 HRESULT rc = S_OK;
2282 ComObjPtr<Progress> pProgress;
2283 Medium::Task *pTask = NULL;
2284
2285 try
2286 {
2287 // locking: we need the tree lock first because we access parent pointers
2288 AutoReadLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
2289 // and we need to write-lock the media involved
2290 AutoMultiWriteLock3 alock(this, pTarget, pParent COMMA_LOCKVAL_SRC_POS);
2291
2292 if ( pTarget->m->state != MediumState_NotCreated
2293 && pTarget->m->state != MediumState_Created)
2294 throw pTarget->setStateError();
2295
2296 /* Build the source lock list. */
2297 MediumLockList *pSourceMediumLockList(new MediumLockList());
2298 rc = createMediumLockList(true /* fFailIfInaccessible */,
2299 false /* fMediumLockWrite */,
2300 NULL,
2301 *pSourceMediumLockList);
2302 if (FAILED(rc))
2303 {
2304 delete pSourceMediumLockList;
2305 throw rc;
2306 }
2307
2308 /* Build the target lock list (including the to-be parent chain). */
2309 MediumLockList *pTargetMediumLockList(new MediumLockList());
2310 rc = pTarget->createMediumLockList(true /* fFailIfInaccessible */,
2311 true /* fMediumLockWrite */,
2312 pParent,
2313 *pTargetMediumLockList);
2314 if (FAILED(rc))
2315 {
2316 delete pSourceMediumLockList;
2317 delete pTargetMediumLockList;
2318 throw rc;
2319 }
2320
2321 rc = pSourceMediumLockList->Lock();
2322 if (FAILED(rc))
2323 {
2324 delete pSourceMediumLockList;
2325 delete pTargetMediumLockList;
2326 throw setError(rc,
2327 tr("Failed to lock source media '%s'"),
2328 getLocationFull().raw());
2329 }
2330 rc = pTargetMediumLockList->Lock();
2331 if (FAILED(rc))
2332 {
2333 delete pSourceMediumLockList;
2334 delete pTargetMediumLockList;
2335 throw setError(rc,
2336 tr("Failed to lock target media '%s'"),
2337 pTarget->getLocationFull().raw());
2338 }
2339
2340 pProgress.createObject();
2341 rc = pProgress->init(m->pVirtualBox,
2342 static_cast <IMedium *>(this),
2343 BstrFmt(tr("Creating clone medium '%s'"), pTarget->m->strLocationFull.raw()),
2344 TRUE /* aCancelable */);
2345 if (FAILED(rc))
2346 {
2347 delete pSourceMediumLockList;
2348 delete pTargetMediumLockList;
2349 throw rc;
2350 }
2351
2352 /* setup task object to carry out the operation asynchronously */
2353 pTask = new Medium::CloneTask(this, pProgress, pTarget, aVariant,
2354 pParent, pSourceMediumLockList,
2355 pTargetMediumLockList);
2356 rc = pTask->rc();
2357 AssertComRC(rc);
2358 if (FAILED(rc))
2359 throw rc;
2360
2361 if (pTarget->m->state == MediumState_NotCreated)
2362 pTarget->m->state = MediumState_Creating;
2363 }
2364 catch (HRESULT aRC) { rc = aRC; }
2365
2366 if (SUCCEEDED(rc))
2367 {
2368 rc = startThread(pTask);
2369
2370 if (SUCCEEDED(rc))
2371 pProgress.queryInterfaceTo(aProgress);
2372 }
2373 else if (pTask != NULL)
2374 delete pTask;
2375
2376 return rc;
2377}
2378
2379STDMETHODIMP Medium::Compact(IProgress **aProgress)
2380{
2381 CheckComArgOutPointerValid(aProgress);
2382
2383 AutoCaller autoCaller(this);
2384 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2385
2386 HRESULT rc = S_OK;
2387 ComObjPtr <Progress> pProgress;
2388 Medium::Task *pTask = NULL;
2389
2390 try
2391 {
2392 /* We need to lock both the current object, and the tree lock (would
2393 * cause a lock order violation otherwise) for createMediumLockList. */
2394 AutoMultiWriteLock2 multilock(&m->pVirtualBox->getMediaTreeLockHandle(),
2395 this->lockHandle()
2396 COMMA_LOCKVAL_SRC_POS);
2397
2398 /* Build the medium lock list. */
2399 MediumLockList *pMediumLockList(new MediumLockList());
2400 rc = createMediumLockList(true /* fFailIfInaccessible */ ,
2401 true /* fMediumLockWrite */,
2402 NULL,
2403 *pMediumLockList);
2404 if (FAILED(rc))
2405 {
2406 delete pMediumLockList;
2407 throw rc;
2408 }
2409
2410 rc = pMediumLockList->Lock();
2411 if (FAILED(rc))
2412 {
2413 delete pMediumLockList;
2414 throw setError(rc,
2415 tr("Failed to lock media when compacting '%s'"),
2416 getLocationFull().raw());
2417 }
2418
2419 pProgress.createObject();
2420 rc = pProgress->init(m->pVirtualBox,
2421 static_cast <IMedium *>(this),
2422 BstrFmt(tr("Compacting medium '%s'"), m->strLocationFull.raw()),
2423 TRUE /* aCancelable */);
2424 if (FAILED(rc))
2425 {
2426 delete pMediumLockList;
2427 throw rc;
2428 }
2429
2430 /* setup task object to carry out the operation asynchronously */
2431 pTask = new Medium::CompactTask(this, pProgress, pMediumLockList);
2432 rc = pTask->rc();
2433 AssertComRC(rc);
2434 if (FAILED(rc))
2435 throw rc;
2436 }
2437 catch (HRESULT aRC) { rc = aRC; }
2438
2439 if (SUCCEEDED(rc))
2440 {
2441 rc = startThread(pTask);
2442
2443 if (SUCCEEDED(rc))
2444 pProgress.queryInterfaceTo(aProgress);
2445 }
2446 else if (pTask != NULL)
2447 delete pTask;
2448
2449 return rc;
2450}
2451
2452STDMETHODIMP Medium::Resize(ULONG64 aLogicalSize, IProgress **aProgress)
2453{
2454 CheckComArgOutPointerValid(aProgress);
2455
2456 AutoCaller autoCaller(this);
2457 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2458
2459 NOREF(aLogicalSize);
2460 NOREF(aProgress);
2461 ReturnComNotImplemented();
2462}
2463
2464STDMETHODIMP Medium::Reset(IProgress **aProgress)
2465{
2466 CheckComArgOutPointerValid(aProgress);
2467
2468 AutoCaller autoCaller(this);
2469 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2470
2471 HRESULT rc = S_OK;
2472 ComObjPtr <Progress> pProgress;
2473 Medium::Task *pTask = NULL;
2474
2475 try
2476 {
2477 /* canClose() needs the tree lock */
2478 AutoMultiWriteLock2 multilock(&m->pVirtualBox->getMediaTreeLockHandle(),
2479 this->lockHandle()
2480 COMMA_LOCKVAL_SRC_POS);
2481
2482 LogFlowThisFunc(("ENTER for medium %s\n", m->strLocationFull.c_str()));
2483
2484 if (m->pParent.isNull())
2485 throw setError(VBOX_E_NOT_SUPPORTED,
2486 tr("Medium type of '%s' is not differencing"),
2487 m->strLocationFull.raw());
2488
2489 rc = canClose();
2490 if (FAILED(rc))
2491 throw rc;
2492
2493 /* Build the medium lock list. */
2494 MediumLockList *pMediumLockList(new MediumLockList());
2495 rc = createMediumLockList(true /* fFailIfInaccessible */,
2496 true /* fMediumLockWrite */,
2497 NULL,
2498 *pMediumLockList);
2499 if (FAILED(rc))
2500 {
2501 delete pMediumLockList;
2502 throw rc;
2503 }
2504
2505 rc = pMediumLockList->Lock();
2506 if (FAILED(rc))
2507 {
2508 delete pMediumLockList;
2509 throw setError(rc,
2510 tr("Failed to lock media when resetting '%s'"),
2511 getLocationFull().raw());
2512 }
2513
2514 pProgress.createObject();
2515 rc = pProgress->init(m->pVirtualBox,
2516 static_cast<IMedium*>(this),
2517 BstrFmt(tr("Resetting differencing medium '%s'"), m->strLocationFull.raw()),
2518 FALSE /* aCancelable */);
2519 if (FAILED(rc))
2520 throw rc;
2521
2522 /* setup task object to carry out the operation asynchronously */
2523 pTask = new Medium::ResetTask(this, pProgress, pMediumLockList);
2524 rc = pTask->rc();
2525 AssertComRC(rc);
2526 if (FAILED(rc))
2527 throw rc;
2528 }
2529 catch (HRESULT aRC) { rc = aRC; }
2530
2531 if (SUCCEEDED(rc))
2532 {
2533 rc = startThread(pTask);
2534
2535 if (SUCCEEDED(rc))
2536 pProgress.queryInterfaceTo(aProgress);
2537 }
2538 else
2539 {
2540 /* Note: on success, the task will unlock this */
2541 {
2542 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2543 HRESULT rc2 = UnlockWrite(NULL);
2544 AssertComRC(rc2);
2545 }
2546 if (pTask != NULL)
2547 delete pTask;
2548 }
2549
2550 LogFlowThisFunc(("LEAVE, rc=%Rhrc\n", rc));
2551
2552 return rc;
2553}
2554
2555////////////////////////////////////////////////////////////////////////////////
2556//
2557// Medium public internal methods
2558//
2559////////////////////////////////////////////////////////////////////////////////
2560
2561/**
2562 * Internal method to return the medium's parent medium. Must have caller + locking!
2563 * @return
2564 */
2565const ComObjPtr<Medium>& Medium::getParent() const
2566{
2567 return m->pParent;
2568}
2569
2570/**
2571 * Internal method to return the medium's list of child media. Must have caller + locking!
2572 * @return
2573 */
2574const MediaList& Medium::getChildren() const
2575{
2576 return m->llChildren;
2577}
2578
2579/**
2580 * Internal method to return the medium's GUID. Must have caller + locking!
2581 * @return
2582 */
2583const Guid& Medium::getId() const
2584{
2585 return m->id;
2586}
2587
2588/**
2589 * Internal method to return the medium's state. Must have caller + locking!
2590 * @return
2591 */
2592MediumState_T Medium::getState() const
2593{
2594 return m->state;
2595}
2596
2597/**
2598 * Internal method to return the medium's variant. Must have caller + locking!
2599 * @return
2600 */
2601MediumVariant_T Medium::getVariant() const
2602{
2603 return m->variant;
2604}
2605
2606/**
2607 * Internal method which returns true if this medium represents a host drive.
2608 * @return
2609 */
2610bool Medium::isHostDrive() const
2611{
2612 return m->hostDrive;
2613}
2614
2615/**
2616 * Internal method to return the medium's location. Must have caller + locking!
2617 * @return
2618 */
2619const Utf8Str& Medium::getLocation() const
2620{
2621 return m->strLocation;
2622}
2623
2624/**
2625 * Internal method to return the medium's full location. Must have caller + locking!
2626 * @return
2627 */
2628const Utf8Str& Medium::getLocationFull() const
2629{
2630 return m->strLocationFull;
2631}
2632
2633/**
2634 * Internal method to return the medium's format string. Must have caller + locking!
2635 * @return
2636 */
2637const Utf8Str& Medium::getFormat() const
2638{
2639 return m->strFormat;
2640}
2641
2642/**
2643 * Internal method to return the medium's format object. Must have caller + locking!
2644 * @return
2645 */
2646const ComObjPtr<MediumFormat>& Medium::getMediumFormat() const
2647{
2648 return m->formatObj;
2649}
2650
2651/**
2652 * Internal method to return the medium's size. Must have caller + locking!
2653 * @return
2654 */
2655uint64_t Medium::getSize() const
2656{
2657 return m->size;
2658}
2659
2660/**
2661 * Adds the given machine and optionally the snapshot to the list of the objects
2662 * this medium is attached to.
2663 *
2664 * @param aMachineId Machine ID.
2665 * @param aSnapshotId Snapshot ID; when non-empty, adds a snapshot attachment.
2666 */
2667HRESULT Medium::addBackReference(const Guid &aMachineId,
2668 const Guid &aSnapshotId /*= Guid::Empty*/)
2669{
2670 AssertReturn(!aMachineId.isEmpty(), E_FAIL);
2671
2672 LogFlowThisFunc(("ENTER, aMachineId: {%RTuuid}, aSnapshotId: {%RTuuid}\n", aMachineId.raw(), aSnapshotId.raw()));
2673
2674 AutoCaller autoCaller(this);
2675 AssertComRCReturnRC(autoCaller.rc());
2676
2677 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2678
2679 switch (m->state)
2680 {
2681 case MediumState_Created:
2682 case MediumState_Inaccessible:
2683 case MediumState_LockedRead:
2684 case MediumState_LockedWrite:
2685 break;
2686
2687 default:
2688 return setStateError();
2689 }
2690
2691 if (m->numCreateDiffTasks > 0)
2692 return setError(VBOX_E_OBJECT_IN_USE,
2693 tr("Cannot attach medium '%s' {%RTuuid}: %u differencing child media are being created"),
2694 m->strLocationFull.raw(),
2695 m->id.raw(),
2696 m->numCreateDiffTasks);
2697
2698 BackRefList::iterator it = std::find_if(m->backRefs.begin(),
2699 m->backRefs.end(),
2700 BackRef::EqualsTo(aMachineId));
2701 if (it == m->backRefs.end())
2702 {
2703 BackRef ref(aMachineId, aSnapshotId);
2704 m->backRefs.push_back(ref);
2705
2706 return S_OK;
2707 }
2708
2709 // if the caller has not supplied a snapshot ID, then we're attaching
2710 // to a machine a medium which represents the machine's current state,
2711 // so set the flag
2712 if (aSnapshotId.isEmpty())
2713 {
2714 /* sanity: no duplicate attachments */
2715 AssertReturn(!it->fInCurState, E_FAIL);
2716 it->fInCurState = true;
2717
2718 return S_OK;
2719 }
2720
2721 // otherwise: a snapshot medium is being attached
2722
2723 /* sanity: no duplicate attachments */
2724 for (BackRef::GuidList::const_iterator jt = it->llSnapshotIds.begin();
2725 jt != it->llSnapshotIds.end();
2726 ++jt)
2727 {
2728 const Guid &idOldSnapshot = *jt;
2729
2730 if (idOldSnapshot == aSnapshotId)
2731 {
2732#ifdef DEBUG
2733 dumpBackRefs();
2734#endif
2735 return setError(VBOX_E_OBJECT_IN_USE,
2736 tr("Cannot attach medium '%s' {%RTuuid} from snapshot '%RTuuid': medium is already in use by this snapshot!"),
2737 m->strLocationFull.raw(),
2738 m->id.raw(),
2739 aSnapshotId.raw(),
2740 idOldSnapshot.raw());
2741 }
2742 }
2743
2744 it->llSnapshotIds.push_back(aSnapshotId);
2745 it->fInCurState = false;
2746
2747 LogFlowThisFuncLeave();
2748
2749 return S_OK;
2750}
2751
2752/**
2753 * Removes the given machine and optionally the snapshot from the list of the
2754 * objects this medium is attached to.
2755 *
2756 * @param aMachineId Machine ID.
2757 * @param aSnapshotId Snapshot ID; when non-empty, removes the snapshot
2758 * attachment.
2759 */
2760HRESULT Medium::removeBackReference(const Guid &aMachineId,
2761 const Guid &aSnapshotId /*= Guid::Empty*/)
2762{
2763 AssertReturn(!aMachineId.isEmpty(), E_FAIL);
2764
2765 AutoCaller autoCaller(this);
2766 AssertComRCReturnRC(autoCaller.rc());
2767
2768 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2769
2770 BackRefList::iterator it =
2771 std::find_if(m->backRefs.begin(), m->backRefs.end(),
2772 BackRef::EqualsTo(aMachineId));
2773 AssertReturn(it != m->backRefs.end(), E_FAIL);
2774
2775 if (aSnapshotId.isEmpty())
2776 {
2777 /* remove the current state attachment */
2778 it->fInCurState = false;
2779 }
2780 else
2781 {
2782 /* remove the snapshot attachment */
2783 BackRef::GuidList::iterator jt =
2784 std::find(it->llSnapshotIds.begin(), it->llSnapshotIds.end(), aSnapshotId);
2785
2786 AssertReturn(jt != it->llSnapshotIds.end(), E_FAIL);
2787 it->llSnapshotIds.erase(jt);
2788 }
2789
2790 /* if the backref becomes empty, remove it */
2791 if (it->fInCurState == false && it->llSnapshotIds.size() == 0)
2792 m->backRefs.erase(it);
2793
2794 return S_OK;
2795}
2796
2797/**
2798 * Internal method to return the medium's list of backrefs. Must have caller + locking!
2799 * @return
2800 */
2801const Guid* Medium::getFirstMachineBackrefId() const
2802{
2803 if (!m->backRefs.size())
2804 return NULL;
2805
2806 return &m->backRefs.front().machineId;
2807}
2808
2809const Guid* Medium::getFirstMachineBackrefSnapshotId() const
2810{
2811 if (!m->backRefs.size())
2812 return NULL;
2813
2814 const BackRef &ref = m->backRefs.front();
2815 if (!ref.llSnapshotIds.size())
2816 return NULL;
2817
2818 return &ref.llSnapshotIds.front();
2819}
2820
2821#ifdef DEBUG
2822/**
2823 * Debugging helper that gets called after VirtualBox initialization that writes all
2824 * machine backreferences to the debug log.
2825 */
2826void Medium::dumpBackRefs()
2827{
2828 AutoCaller autoCaller(this);
2829 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2830
2831 LogFlowThisFunc(("Dumping backrefs for medium '%s':\n", m->strLocationFull.raw()));
2832
2833 for (BackRefList::iterator it2 = m->backRefs.begin();
2834 it2 != m->backRefs.end();
2835 ++it2)
2836 {
2837 const BackRef &ref = *it2;
2838 LogFlowThisFunc((" Backref from machine {%RTuuid} (fInCurState: %d)\n", ref.machineId.raw(), ref.fInCurState));
2839
2840 for (BackRef::GuidList::const_iterator jt2 = it2->llSnapshotIds.begin();
2841 jt2 != it2->llSnapshotIds.end();
2842 ++jt2)
2843 {
2844 const Guid &id = *jt2;
2845 LogFlowThisFunc((" Backref from snapshot {%RTuuid}\n", id.raw()));
2846 }
2847 }
2848}
2849#endif
2850
2851/**
2852 * Checks if the given change of \a aOldPath to \a aNewPath affects the location
2853 * of this media and updates it if necessary to reflect the new location.
2854 *
2855 * @param aOldPath Old path (full).
2856 * @param aNewPath New path (full).
2857 *
2858 * @note Locks this object for writing.
2859 */
2860HRESULT Medium::updatePath(const Utf8Str &strOldPath, const Utf8Str &strNewPath)
2861{
2862 AssertReturn(!strOldPath.isEmpty(), E_FAIL);
2863 AssertReturn(!strNewPath.isEmpty(), E_FAIL);
2864
2865 AutoCaller autoCaller(this);
2866 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2867
2868 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2869
2870 LogFlowThisFunc(("locationFull.before='%s'\n", m->strLocationFull.raw()));
2871
2872 const char *pcszMediumPath = m->strLocationFull.c_str();
2873
2874 if (RTPathStartsWith(pcszMediumPath, strOldPath.c_str()))
2875 {
2876 Utf8Str newPath(strNewPath);
2877 newPath.append(pcszMediumPath + strOldPath.length());
2878 unconst(m->strLocationFull) = newPath;
2879
2880 Utf8Str path;
2881 m->pVirtualBox->copyPathRelativeToConfig(newPath, path);
2882 unconst(m->strLocation) = path;
2883
2884 LogFlowThisFunc(("locationFull.after='%s'\n", m->strLocationFull.raw()));
2885 }
2886
2887 return S_OK;
2888}
2889
2890/**
2891 * Returns the base medium of the media chain this medium is part of.
2892 *
2893 * The base medium is found by walking up the parent-child relationship axis.
2894 * If the medium doesn't have a parent (i.e. it's a base medium), it
2895 * returns itself in response to this method.
2896 *
2897 * @param aLevel Where to store the number of ancestors of this medium
2898 * (zero for the base), may be @c NULL.
2899 *
2900 * @note Locks medium tree for reading.
2901 */
2902ComObjPtr<Medium> Medium::getBase(uint32_t *aLevel /*= NULL*/)
2903{
2904 ComObjPtr<Medium> pBase;
2905 uint32_t level;
2906
2907 AutoCaller autoCaller(this);
2908 AssertReturn(autoCaller.isOk(), pBase);
2909
2910 /* we access mParent */
2911 AutoReadLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
2912
2913 pBase = this;
2914 level = 0;
2915
2916 if (m->pParent)
2917 {
2918 for (;;)
2919 {
2920 AutoCaller baseCaller(pBase);
2921 AssertReturn(baseCaller.isOk(), pBase);
2922
2923 if (pBase->m->pParent.isNull())
2924 break;
2925
2926 pBase = pBase->m->pParent;
2927 ++level;
2928 }
2929 }
2930
2931 if (aLevel != NULL)
2932 *aLevel = level;
2933
2934 return pBase;
2935}
2936
2937/**
2938 * Returns @c true if this medium cannot be modified because it has
2939 * dependants (children) or is part of the snapshot. Related to the medium
2940 * type and posterity, not to the current media state.
2941 *
2942 * @note Locks this object and medium tree for reading.
2943 */
2944bool Medium::isReadOnly()
2945{
2946 AutoCaller autoCaller(this);
2947 AssertComRCReturn(autoCaller.rc(), false);
2948
2949 /* we access children */
2950 AutoReadLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
2951
2952 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2953
2954 switch (m->type)
2955 {
2956 case MediumType_Normal:
2957 {
2958 if (getChildren().size() != 0)
2959 return true;
2960
2961 for (BackRefList::const_iterator it = m->backRefs.begin();
2962 it != m->backRefs.end(); ++it)
2963 if (it->llSnapshotIds.size() != 0)
2964 return true;
2965
2966 return false;
2967 }
2968 case MediumType_Immutable:
2969 return true;
2970 case MediumType_Writethrough:
2971 case MediumType_Shareable:
2972 return false;
2973 default:
2974 break;
2975 }
2976
2977 AssertFailedReturn(false);
2978}
2979
2980/**
2981 * Saves medium data by appending a new child node to the given
2982 * parent XML settings node.
2983 *
2984 * @param data Settings struct to be updated.
2985 *
2986 * @note Locks this object, medium tree and children for reading.
2987 */
2988HRESULT Medium::saveSettings(settings::Medium &data)
2989{
2990 AutoCaller autoCaller(this);
2991 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2992
2993 /* we access mParent */
2994 AutoReadLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
2995
2996 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2997
2998 data.uuid = m->id;
2999 data.strLocation = m->strLocation;
3000 data.strFormat = m->strFormat;
3001
3002 /* optional, only for diffs, default is false */
3003 if (m->pParent)
3004 data.fAutoReset = m->autoReset;
3005 else
3006 data.fAutoReset = false;
3007
3008 /* optional */
3009 data.strDescription = m->strDescription;
3010
3011 /* optional properties */
3012 data.properties.clear();
3013 for (Data::PropertyMap::const_iterator it = m->properties.begin();
3014 it != m->properties.end();
3015 ++it)
3016 {
3017 /* only save properties that have non-default values */
3018 if (!it->second.isEmpty())
3019 {
3020 Utf8Str name = it->first;
3021 Utf8Str value = it->second;
3022 data.properties[name] = value;
3023 }
3024 }
3025
3026 /* only for base media */
3027 if (m->pParent.isNull())
3028 data.hdType = m->type;
3029
3030 /* save all children */
3031 for (MediaList::const_iterator it = getChildren().begin();
3032 it != getChildren().end();
3033 ++it)
3034 {
3035 settings::Medium med;
3036 HRESULT rc = (*it)->saveSettings(med);
3037 AssertComRCReturnRC(rc);
3038 data.llChildren.push_back(med);
3039 }
3040
3041 return S_OK;
3042}
3043
3044/**
3045 * Compares the location of this medium to the given location.
3046 *
3047 * The comparison takes the location details into account. For example, if the
3048 * location is a file in the host's filesystem, a case insensitive comparison
3049 * will be performed for case insensitive filesystems.
3050 *
3051 * @param aLocation Location to compare to (as is).
3052 * @param aResult Where to store the result of comparison: 0 if locations
3053 * are equal, 1 if this object's location is greater than
3054 * the specified location, and -1 otherwise.
3055 */
3056HRESULT Medium::compareLocationTo(const char *aLocation, int &aResult)
3057{
3058 AutoCaller autoCaller(this);
3059 AssertComRCReturnRC(autoCaller.rc());
3060
3061 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3062
3063 Utf8Str locationFull(m->strLocationFull);
3064
3065 /// @todo NEWMEDIA delegate the comparison to the backend?
3066
3067 if (m->formatObj->getCapabilities() & MediumFormatCapabilities_File)
3068 {
3069 Utf8Str location(aLocation);
3070
3071 /* For locations represented by files, append the default path if
3072 * only the name is given, and then get the full path. */
3073 if (!RTPathHavePath(aLocation))
3074 {
3075 location = Utf8StrFmt("%s%c%s",
3076 m->pVirtualBox->getDefaultHardDiskFolder().raw(),
3077 RTPATH_DELIMITER,
3078 aLocation);
3079 }
3080
3081 int vrc = m->pVirtualBox->calculateFullPath(location, location);
3082 if (RT_FAILURE(vrc))
3083 return setError(VBOX_E_FILE_ERROR,
3084 tr("Invalid medium storage file location '%s' (%Rrc)"),
3085 location.raw(),
3086 vrc);
3087
3088 aResult = RTPathCompare(locationFull.c_str(), location.c_str());
3089 }
3090 else
3091 aResult = locationFull.compare(aLocation);
3092
3093 return S_OK;
3094}
3095
3096/**
3097 * Constructs a medium lock list for this medium. The lock is not taken.
3098 *
3099 * @note Locks the medium tree for reading.
3100 *
3101 * @param fFailIfInaccessible If true, this fails with an error if a medium is inaccessible. If false,
3102 * inaccessible media are silently skipped and not locked (i.e. their state remains "Inaccessible");
3103 * this is necessary for a VM's removable media VM startup for which we do not want to fail.
3104 * @param fMediumLockWrite Whether to associate a write lock with this medium.
3105 * @param pToBeParent Medium which will become the parent of this medium.
3106 * @param mediumLockList Where to store the resulting list.
3107 */
3108HRESULT Medium::createMediumLockList(bool fFailIfInaccessible,
3109 bool fMediumLockWrite,
3110 Medium *pToBeParent,
3111 MediumLockList &mediumLockList)
3112{
3113 AutoCaller autoCaller(this);
3114 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3115
3116 HRESULT rc = S_OK;
3117
3118 /* we access parent medium objects */
3119 AutoReadLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
3120
3121 /* paranoid sanity checking if the medium has a to-be parent medium */
3122 if (pToBeParent)
3123 {
3124 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3125 ComAssertRet(getParent().isNull(), E_FAIL);
3126 ComAssertRet(getChildren().size() == 0, E_FAIL);
3127 }
3128
3129 ErrorInfoKeeper eik;
3130 MultiResult mrc(S_OK);
3131
3132 ComObjPtr<Medium> pMedium = this;
3133 while (!pMedium.isNull())
3134 {
3135 // need write lock for RefreshState if medium is inaccessible
3136 AutoWriteLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
3137
3138 /* Accessibility check must be first, otherwise locking interferes
3139 * with getting the medium state. Lock lists are not created for
3140 * fun, and thus getting the medium status is no luxury. */
3141 MediumState_T mediumState = pMedium->getState();
3142 if (mediumState == MediumState_Inaccessible)
3143 {
3144 rc = pMedium->RefreshState(&mediumState);
3145 if (FAILED(rc)) return rc;
3146
3147 if (mediumState == MediumState_Inaccessible)
3148 {
3149 // ignore inaccessible ISO media and silently return S_OK,
3150 // otherwise VM startup (esp. restore) may fail without good reason
3151 if (!fFailIfInaccessible)
3152 return S_OK;
3153
3154 // otherwise report an error
3155 Bstr error;
3156 rc = pMedium->COMGETTER(LastAccessError)(error.asOutParam());
3157 if (FAILED(rc)) return rc;
3158
3159 /* collect multiple errors */
3160 eik.restore();
3161 Assert(!error.isEmpty());
3162 mrc = setError(E_FAIL,
3163 "%ls",
3164 error.raw());
3165 // error message will be something like
3166 // "Could not open the medium ... VD: error VERR_FILE_NOT_FOUND opening image file ... (VERR_FILE_NOT_FOUND).
3167 eik.fetch();
3168 }
3169 }
3170
3171 if (pMedium == this)
3172 mediumLockList.Prepend(pMedium, fMediumLockWrite);
3173 else
3174 mediumLockList.Prepend(pMedium, false);
3175
3176 pMedium = pMedium->getParent();
3177 if (pMedium.isNull() && pToBeParent)
3178 {
3179 pMedium = pToBeParent;
3180 pToBeParent = NULL;
3181 }
3182 }
3183
3184 return mrc;
3185}
3186
3187/**
3188 * Returns a preferred format for differencing media.
3189 */
3190Utf8Str Medium::getPreferredDiffFormat()
3191{
3192 AutoCaller autoCaller(this);
3193 AssertComRCReturn(autoCaller.rc(), Utf8Str::Empty);
3194
3195 /* check that our own format supports diffs */
3196 if (!(m->formatObj->getCapabilities() & MediumFormatCapabilities_Differencing))
3197 /* use the default format if not */
3198 return m->pVirtualBox->getDefaultHardDiskFormat();
3199
3200 /* m->strFormat is const, no need to lock */
3201 return m->strFormat;
3202}
3203
3204/**
3205 * Returns the medium device type. Must have caller + locking!
3206 * @return
3207 */
3208DeviceType_T Medium::getDeviceType() const
3209{
3210 return m->devType;
3211}
3212
3213/**
3214 * Returns the medium type. Must have caller + locking!
3215 * @return
3216 */
3217MediumType_T Medium::getType() const
3218{
3219 return m->type;
3220}
3221
3222/**
3223 * Returns a short version of the location attribute.
3224 *
3225 * @note Must be called from under this object's read or write lock.
3226 */
3227Utf8Str Medium::getName()
3228{
3229 Utf8Str name = RTPathFilename(m->strLocationFull.c_str());
3230 return name;
3231}
3232
3233/**
3234 * Sets the value of m->strLocation and calculates the value of m->strLocationFull.
3235 *
3236 * Treats non-FS-path locations specially, and prepends the default medium
3237 * folder if the given location string does not contain any path information
3238 * at all.
3239 *
3240 * Also, if the specified location is a file path that ends with '/' then the
3241 * file name part will be generated by this method automatically in the format
3242 * '{<uuid>}.<ext>' where <uuid> is a fresh UUID that this method will generate
3243 * and assign to this medium, and <ext> is the default extension for this
3244 * medium's storage format. Note that this procedure requires the media state to
3245 * be NotCreated and will return a failure otherwise.
3246 *
3247 * @param aLocation Location of the storage unit. If the location is a FS-path,
3248 * then it can be relative to the VirtualBox home directory.
3249 * @param aFormat Optional fallback format if it is an import and the format
3250 * cannot be determined.
3251 *
3252 * @note Must be called from under this object's write lock.
3253 */
3254HRESULT Medium::setLocation(const Utf8Str &aLocation,
3255 const Utf8Str &aFormat /* = Utf8Str::Empty */)
3256{
3257 AssertReturn(!aLocation.isEmpty(), E_FAIL);
3258
3259 AutoCaller autoCaller(this);
3260 AssertComRCReturnRC(autoCaller.rc());
3261
3262 /* formatObj may be null only when initializing from an existing path and
3263 * no format is known yet */
3264 AssertReturn( (!m->strFormat.isEmpty() && !m->formatObj.isNull())
3265 || ( autoCaller.state() == InInit
3266 && m->state != MediumState_NotCreated
3267 && m->id.isEmpty()
3268 && m->strFormat.isEmpty()
3269 && m->formatObj.isNull()),
3270 E_FAIL);
3271
3272 /* are we dealing with a new medium constructed using the existing
3273 * location? */
3274 bool isImport = m->strFormat.isEmpty();
3275
3276 if ( isImport
3277 || ( (m->formatObj->getCapabilities() & MediumFormatCapabilities_File)
3278 && !m->hostDrive))
3279 {
3280 Guid id;
3281
3282 Utf8Str location(aLocation);
3283
3284 if (m->state == MediumState_NotCreated)
3285 {
3286 /* must be a file (formatObj must be already known) */
3287 Assert(m->formatObj->getCapabilities() & MediumFormatCapabilities_File);
3288
3289 if (RTPathFilename(location.c_str()) == NULL)
3290 {
3291 /* no file name is given (either an empty string or ends with a
3292 * slash), generate a new UUID + file name if the state allows
3293 * this */
3294
3295 ComAssertMsgRet(!m->formatObj->getFileExtensions().empty(),
3296 ("Must be at least one extension if it is MediumFormatCapabilities_File\n"),
3297 E_FAIL);
3298
3299 Utf8Str strExt = m->formatObj->getFileExtensions().front();
3300 ComAssertMsgRet(!strExt.isEmpty(),
3301 ("Default extension must not be empty\n"),
3302 E_FAIL);
3303
3304 id.create();
3305
3306 location = Utf8StrFmt("%s{%RTuuid}.%s",
3307 location.raw(), id.raw(), strExt.c_str());
3308 }
3309 }
3310
3311 /* append the default folder if no path is given */
3312 if (!RTPathHavePath(location.c_str()))
3313 location = Utf8StrFmt("%s%c%s",
3314 m->pVirtualBox->getDefaultHardDiskFolder().raw(),
3315 RTPATH_DELIMITER,
3316 location.raw());
3317
3318 /* get the full file name */
3319 Utf8Str locationFull;
3320 int vrc = m->pVirtualBox->calculateFullPath(location, locationFull);
3321 if (RT_FAILURE(vrc))
3322 return setError(VBOX_E_FILE_ERROR,
3323 tr("Invalid medium storage file location '%s' (%Rrc)"),
3324 location.raw(), vrc);
3325
3326 /* detect the backend from the storage unit if importing */
3327 if (isImport)
3328 {
3329 char *backendName = NULL;
3330
3331 /* is it a file? */
3332 {
3333 RTFILE file;
3334 vrc = RTFileOpen(&file, locationFull.c_str(), RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_NONE);
3335 if (RT_SUCCESS(vrc))
3336 RTFileClose(file);
3337 }
3338 if (RT_SUCCESS(vrc))
3339 {
3340 vrc = VDGetFormat(NULL, locationFull.c_str(), &backendName);
3341 }
3342 else if (vrc != VERR_FILE_NOT_FOUND && vrc != VERR_PATH_NOT_FOUND)
3343 {
3344 /* assume it's not a file, restore the original location */
3345 location = locationFull = aLocation;
3346 vrc = VDGetFormat(NULL, locationFull.c_str(), &backendName);
3347 }
3348
3349 if (RT_FAILURE(vrc))
3350 {
3351 if (vrc == VERR_FILE_NOT_FOUND || vrc == VERR_PATH_NOT_FOUND)
3352 return setError(VBOX_E_FILE_ERROR,
3353 tr("Could not find file for the medium '%s' (%Rrc)"),
3354 locationFull.raw(), vrc);
3355 else if (aFormat.isEmpty())
3356 return setError(VBOX_E_IPRT_ERROR,
3357 tr("Could not get the storage format of the medium '%s' (%Rrc)"),
3358 locationFull.raw(), vrc);
3359 else
3360 {
3361 HRESULT rc = setFormat(aFormat);
3362 /* setFormat() must not fail since we've just used the backend so
3363 * the format object must be there */
3364 AssertComRCReturnRC(rc);
3365 }
3366 }
3367 else
3368 {
3369 ComAssertRet(backendName != NULL && *backendName != '\0', E_FAIL);
3370
3371 HRESULT rc = setFormat(backendName);
3372 RTStrFree(backendName);
3373
3374 /* setFormat() must not fail since we've just used the backend so
3375 * the format object must be there */
3376 AssertComRCReturnRC(rc);
3377 }
3378 }
3379
3380 /* is it still a file? */
3381 if (m->formatObj->getCapabilities() & MediumFormatCapabilities_File)
3382 {
3383 m->strLocation = location;
3384 m->strLocationFull = locationFull;
3385
3386 if (m->state == MediumState_NotCreated)
3387 {
3388 /* assign a new UUID (this UUID will be used when calling
3389 * VDCreateBase/VDCreateDiff as a wanted UUID). Note that we
3390 * also do that if we didn't generate it to make sure it is
3391 * either generated by us or reset to null */
3392 unconst(m->id) = id;
3393 }
3394 }
3395 else
3396 {
3397 m->strLocation = locationFull;
3398 m->strLocationFull = locationFull;
3399 }
3400 }
3401 else
3402 {
3403 m->strLocation = aLocation;
3404 m->strLocationFull = aLocation;
3405 }
3406
3407 return S_OK;
3408}
3409
3410/**
3411 * Queries information from the medium.
3412 *
3413 * As a result of this call, the accessibility state and data members such as
3414 * size and description will be updated with the current information.
3415 *
3416 * @note This method may block during a system I/O call that checks storage
3417 * accessibility.
3418 *
3419 * @note Locks medium tree for reading and writing (for new diff media checked
3420 * for the first time). Locks mParent for reading. Locks this object for
3421 * writing.
3422 */
3423HRESULT Medium::queryInfo()
3424{
3425 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3426
3427 if ( m->state != MediumState_Created
3428 && m->state != MediumState_Inaccessible
3429 && m->state != MediumState_LockedRead)
3430 return E_FAIL;
3431
3432 HRESULT rc = S_OK;
3433
3434 int vrc = VINF_SUCCESS;
3435
3436 /* check if a blocking queryInfo() call is in progress on some other thread,
3437 * and wait for it to finish if so instead of querying data ourselves */
3438 if (m->queryInfoRunning)
3439 {
3440 Assert( m->state == MediumState_LockedRead
3441 || m->state == MediumState_LockedWrite);
3442
3443 alock.leave();
3444 vrc = RTSemEventMultiWait(m->queryInfoSem, RT_INDEFINITE_WAIT);
3445 alock.enter();
3446
3447 AssertRC(vrc);
3448
3449 return S_OK;
3450 }
3451
3452 bool success = false;
3453 Utf8Str lastAccessError;
3454
3455 /* are we dealing with a new medium constructed using the existing
3456 * location? */
3457 bool isImport = m->id.isEmpty();
3458 unsigned uOpenFlags = VD_OPEN_FLAGS_INFO;
3459
3460 /* Note that we don't use VD_OPEN_FLAGS_READONLY when opening new
3461 * media because that would prevent necessary modifications
3462 * when opening media of some third-party formats for the first
3463 * time in VirtualBox (such as VMDK for which VDOpen() needs to
3464 * generate an UUID if it is missing) */
3465 if ( (m->hddOpenMode == OpenReadOnly)
3466 || !isImport
3467 )
3468 uOpenFlags |= VD_OPEN_FLAGS_READONLY;
3469
3470 /* Open shareable medium with the appropriate flags */
3471 if (m->type == MediumType_Shareable)
3472 uOpenFlags |= VD_OPEN_FLAGS_SHAREABLE;
3473
3474 /* Lock the medium, which makes the behavior much more consistent */
3475 if (uOpenFlags & (VD_OPEN_FLAGS_READONLY || VD_OPEN_FLAGS_SHAREABLE))
3476 rc = LockRead(NULL);
3477 else
3478 rc = LockWrite(NULL);
3479 if (FAILED(rc)) return rc;
3480
3481 /* Copies of the input state fields which are not read-only,
3482 * as we're dropping the lock. CAUTION: be extremely careful what
3483 * you do with the contents of this medium object, as you will
3484 * create races if there are concurrent changes. */
3485 Utf8Str format(m->strFormat);
3486 Utf8Str location(m->strLocationFull);
3487 ComObjPtr<MediumFormat> formatObj = m->formatObj;
3488
3489 /* "Output" values which can't be set because the lock isn't held
3490 * at the time the values are determined. */
3491 Guid mediumId = m->id;
3492 uint64_t mediumSize = 0;
3493 uint64_t mediumLogicalSize = 0;
3494
3495 /* leave the lock before a lengthy operation */
3496 vrc = RTSemEventMultiReset(m->queryInfoSem);
3497 AssertRCReturn(vrc, E_FAIL);
3498 m->queryInfoRunning = true;
3499 alock.leave();
3500
3501 try
3502 {
3503 /* skip accessibility checks for host drives */
3504 if (m->hostDrive)
3505 {
3506 success = true;
3507 throw S_OK;
3508 }
3509
3510 PVBOXHDD hdd;
3511 vrc = VDCreate(m->vdDiskIfaces, &hdd);
3512 ComAssertRCThrow(vrc, E_FAIL);
3513
3514 try
3515 {
3516 /** @todo This kind of opening of media is assuming that diff
3517 * media can be opened as base media. Should be documented that
3518 * it must work for all medium format backends. */
3519 vrc = VDOpen(hdd,
3520 format.c_str(),
3521 location.c_str(),
3522 uOpenFlags,
3523 m->vdDiskIfaces);
3524 if (RT_FAILURE(vrc))
3525 {
3526 lastAccessError = Utf8StrFmt(tr("Could not open the medium '%s'%s"),
3527 location.c_str(), vdError(vrc).c_str());
3528 throw S_OK;
3529 }
3530
3531 if (formatObj->getCapabilities() & MediumFormatCapabilities_Uuid)
3532 {
3533 /* Modify the UUIDs if necessary. The associated fields are
3534 * not modified by other code, so no need to copy. */
3535 if (m->setImageId)
3536 {
3537 vrc = VDSetUuid(hdd, 0, m->imageId);
3538 ComAssertRCThrow(vrc, E_FAIL);
3539 }
3540 if (m->setParentId)
3541 {
3542 vrc = VDSetParentUuid(hdd, 0, m->parentId);
3543 ComAssertRCThrow(vrc, E_FAIL);
3544 }
3545 /* zap the information, these are no long-term members */
3546 m->setImageId = false;
3547 unconst(m->imageId).clear();
3548 m->setParentId = false;
3549 unconst(m->parentId).clear();
3550
3551 /* check the UUID */
3552 RTUUID uuid;
3553 vrc = VDGetUuid(hdd, 0, &uuid);
3554 ComAssertRCThrow(vrc, E_FAIL);
3555
3556 if (isImport)
3557 {
3558 mediumId = uuid;
3559
3560 if (mediumId.isEmpty() && (m->hddOpenMode == OpenReadOnly))
3561 // only when importing a VDMK that has no UUID, create one in memory
3562 mediumId.create();
3563 }
3564 else
3565 {
3566 Assert(!mediumId.isEmpty());
3567
3568 if (mediumId != uuid)
3569 {
3570 lastAccessError = Utf8StrFmt(
3571 tr("UUID {%RTuuid} of the medium '%s' does not match the value {%RTuuid} stored in the media registry ('%s')"),
3572 &uuid,
3573 location.c_str(),
3574 mediumId.raw(),
3575 m->pVirtualBox->settingsFilePath().c_str());
3576 throw S_OK;
3577 }
3578 }
3579 }
3580 else
3581 {
3582 /* the backend does not support storing UUIDs within the
3583 * underlying storage so use what we store in XML */
3584
3585 /* generate an UUID for an imported UUID-less medium */
3586 if (isImport)
3587 {
3588 if (m->setImageId)
3589 mediumId = m->imageId;
3590 else
3591 mediumId.create();
3592 }
3593 }
3594
3595 /* get the medium variant */
3596 unsigned uImageFlags;
3597 vrc = VDGetImageFlags(hdd, 0, &uImageFlags);
3598 ComAssertRCThrow(vrc, E_FAIL);
3599 m->variant = (MediumVariant_T)uImageFlags;
3600
3601 /* check/get the parent uuid and update corresponding state */
3602 if (uImageFlags & VD_IMAGE_FLAGS_DIFF)
3603 {
3604 RTUUID parentId;
3605 vrc = VDGetParentUuid(hdd, 0, &parentId);
3606 ComAssertRCThrow(vrc, E_FAIL);
3607
3608 if (isImport)
3609 {
3610 /* the parent must be known to us. Note that we freely
3611 * call locking methods of mVirtualBox and parent, as all
3612 * relevant locks must be already held. There may be no
3613 * concurrent access to the just opened medium on other
3614 * threads yet (and init() will fail if this method reports
3615 * MediumState_Inaccessible) */
3616
3617 Guid id = parentId;
3618 ComObjPtr<Medium> pParent;
3619 rc = m->pVirtualBox->findHardDisk(&id, NULL, false /* aSetError */, &pParent);
3620 if (FAILED(rc))
3621 {
3622 lastAccessError = Utf8StrFmt(
3623 tr("Parent medium with UUID {%RTuuid} of the medium '%s' is not found in the media registry ('%s')"),
3624 &parentId, location.c_str(),
3625 m->pVirtualBox->settingsFilePath().c_str());
3626 throw S_OK;
3627 }
3628
3629 /* we set mParent & children() */
3630 AutoWriteLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
3631
3632 Assert(m->pParent.isNull());
3633 m->pParent = pParent;
3634 m->pParent->m->llChildren.push_back(this);
3635 }
3636 else
3637 {
3638 /* we access mParent */
3639 AutoReadLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
3640
3641 /* check that parent UUIDs match. Note that there's no need
3642 * for the parent's AutoCaller (our lifetime is bound to
3643 * it) */
3644
3645 if (m->pParent.isNull())
3646 {
3647 lastAccessError = Utf8StrFmt(
3648 tr("Medium type of '%s' is differencing but it is not associated with any parent medium in the media registry ('%s')"),
3649 location.c_str(),
3650 m->pVirtualBox->settingsFilePath().c_str());
3651 throw S_OK;
3652 }
3653
3654 AutoReadLock parentLock(m->pParent COMMA_LOCKVAL_SRC_POS);
3655 if ( m->pParent->getState() != MediumState_Inaccessible
3656 && m->pParent->getId() != parentId)
3657 {
3658 lastAccessError = Utf8StrFmt(
3659 tr("Parent UUID {%RTuuid} of the medium '%s' does not match UUID {%RTuuid} of its parent medium stored in the media registry ('%s')"),
3660 &parentId, location.c_str(),
3661 m->pParent->getId().raw(),
3662 m->pVirtualBox->settingsFilePath().c_str());
3663 throw S_OK;
3664 }
3665
3666 /// @todo NEWMEDIA what to do if the parent is not
3667 /// accessible while the diff is? Probably nothing. The
3668 /// real code will detect the mismatch anyway.
3669 }
3670 }
3671
3672 mediumSize = VDGetFileSize(hdd, 0);
3673 mediumLogicalSize = VDGetSize(hdd, 0) / _1M;
3674
3675 success = true;
3676 }
3677 catch (HRESULT aRC)
3678 {
3679 rc = aRC;
3680 }
3681
3682 VDDestroy(hdd);
3683
3684 }
3685 catch (HRESULT aRC)
3686 {
3687 rc = aRC;
3688 }
3689
3690 alock.enter();
3691
3692 if (isImport)
3693 unconst(m->id) = mediumId;
3694
3695 if (success)
3696 {
3697 m->size = mediumSize;
3698 m->logicalSize = mediumLogicalSize;
3699 m->strLastAccessError.setNull();
3700 }
3701 else
3702 {
3703 m->strLastAccessError = lastAccessError;
3704 LogWarningFunc(("'%s' is not accessible (error='%s', rc=%Rhrc, vrc=%Rrc)\n",
3705 location.c_str(), m->strLastAccessError.c_str(),
3706 rc, vrc));
3707 }
3708
3709 /* inform other callers if there are any */
3710 RTSemEventMultiSignal(m->queryInfoSem);
3711 m->queryInfoRunning = false;
3712
3713 /* Set the proper state according to the result of the check */
3714 if (success)
3715 m->preLockState = MediumState_Created;
3716 else
3717 m->preLockState = MediumState_Inaccessible;
3718
3719 if (uOpenFlags & (VD_OPEN_FLAGS_READONLY || VD_OPEN_FLAGS_SHAREABLE))
3720 rc = UnlockRead(NULL);
3721 else
3722 rc = UnlockWrite(NULL);
3723 if (FAILED(rc)) return rc;
3724
3725 return rc;
3726}
3727
3728/**
3729 * Sets the extended error info according to the current media state.
3730 *
3731 * @note Must be called from under this object's write or read lock.
3732 */
3733HRESULT Medium::setStateError()
3734{
3735 HRESULT rc = E_FAIL;
3736
3737 switch (m->state)
3738 {
3739 case MediumState_NotCreated:
3740 {
3741 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
3742 tr("Storage for the medium '%s' is not created"),
3743 m->strLocationFull.raw());
3744 break;
3745 }
3746 case MediumState_Created:
3747 {
3748 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
3749 tr("Storage for the medium '%s' is already created"),
3750 m->strLocationFull.raw());
3751 break;
3752 }
3753 case MediumState_LockedRead:
3754 {
3755 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
3756 tr("Medium '%s' is locked for reading by another task"),
3757 m->strLocationFull.raw());
3758 break;
3759 }
3760 case MediumState_LockedWrite:
3761 {
3762 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
3763 tr("Medium '%s' is locked for writing by another task"),
3764 m->strLocationFull.raw());
3765 break;
3766 }
3767 case MediumState_Inaccessible:
3768 {
3769 /* be in sync with Console::powerUpThread() */
3770 if (!m->strLastAccessError.isEmpty())
3771 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
3772 tr("Medium '%s' is not accessible. %s"),
3773 m->strLocationFull.raw(), m->strLastAccessError.c_str());
3774 else
3775 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
3776 tr("Medium '%s' is not accessible"),
3777 m->strLocationFull.raw());
3778 break;
3779 }
3780 case MediumState_Creating:
3781 {
3782 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
3783 tr("Storage for the medium '%s' is being created"),
3784 m->strLocationFull.raw());
3785 break;
3786 }
3787 case MediumState_Deleting:
3788 {
3789 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
3790 tr("Storage for the medium '%s' is being deleted"),
3791 m->strLocationFull.raw());
3792 break;
3793 }
3794 default:
3795 {
3796 AssertFailed();
3797 break;
3798 }
3799 }
3800
3801 return rc;
3802}
3803
3804/**
3805 * Implementation for the public Medium::Close() with the exception of calling
3806 * VirtualBox::saveSettings(), in case someone wants to call this for several
3807 * media.
3808 *
3809 * After this returns with success, uninit() has been called on the medium, and
3810 * the object is no longer usable ("not ready" state).
3811 *
3812 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
3813 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
3814 * This only works in "wait" mode; otherwise saveSettings gets called automatically by the thread that was created,
3815 * and this parameter is ignored.
3816 * @param autoCaller AutoCaller instance which must have been created on the caller's stack for this medium. This gets released here
3817 * upon which the Medium instance gets uninitialized.
3818 * @return
3819 */
3820HRESULT Medium::close(bool *pfNeedsSaveSettings, AutoCaller &autoCaller)
3821{
3822 // we're accessing parent/child and backrefs, so lock the tree first, then ourselves
3823 AutoMultiWriteLock2 multilock(&m->pVirtualBox->getMediaTreeLockHandle(),
3824 this->lockHandle()
3825 COMMA_LOCKVAL_SRC_POS);
3826
3827 LogFlowFunc(("ENTER for %s\n", getLocationFull().c_str()));
3828
3829 bool wasCreated = true;
3830
3831 switch (m->state)
3832 {
3833 case MediumState_NotCreated:
3834 wasCreated = false;
3835 break;
3836 case MediumState_Created:
3837 case MediumState_Inaccessible:
3838 break;
3839 default:
3840 return setStateError();
3841 }
3842
3843 if (m->backRefs.size() != 0)
3844 return setError(VBOX_E_OBJECT_IN_USE,
3845 tr("Medium '%s' cannot be closed because it is still attached to %d virtual machines"),
3846 m->strLocationFull.raw(), m->backRefs.size());
3847
3848 // perform extra media-dependent close checks
3849 HRESULT rc = canClose();
3850 if (FAILED(rc)) return rc;
3851
3852 if (wasCreated)
3853 {
3854 // remove from the list of known media before performing actual
3855 // uninitialization (to keep the media registry consistent on
3856 // failure to do so)
3857 rc = unregisterWithVirtualBox(pfNeedsSaveSettings);
3858 if (FAILED(rc)) return rc;
3859 }
3860
3861 // leave the AutoCaller, as otherwise uninit() will simply hang
3862 autoCaller.release();
3863
3864 // Keep the locks held until after uninit, as otherwise the consistency
3865 // of the medium tree cannot be guaranteed.
3866 uninit();
3867
3868 LogFlowFuncLeave();
3869
3870 return rc;
3871}
3872
3873/**
3874 * Deletes the medium storage unit.
3875 *
3876 * If @a aProgress is not NULL but the object it points to is @c null then a new
3877 * progress object will be created and assigned to @a *aProgress on success,
3878 * otherwise the existing progress object is used. If Progress is NULL, then no
3879 * progress object is created/used at all.
3880 *
3881 * When @a aWait is @c false, this method will create a thread to perform the
3882 * delete operation asynchronously and will return immediately. Otherwise, it
3883 * will perform the operation on the calling thread and will not return to the
3884 * caller until the operation is completed. Note that @a aProgress cannot be
3885 * NULL when @a aWait is @c false (this method will assert in this case).
3886 *
3887 * @param aProgress Where to find/store a Progress object to track operation
3888 * completion.
3889 * @param aWait @c true if this method should block instead of creating
3890 * an asynchronous thread.
3891 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
3892 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
3893 * This only works in "wait" mode; otherwise saveSettings gets called automatically by the thread that was created,
3894 * and this parameter is ignored.
3895 *
3896 * @note Locks mVirtualBox and this object for writing. Locks medium tree for
3897 * writing.
3898 */
3899HRESULT Medium::deleteStorage(ComObjPtr<Progress> *aProgress,
3900 bool aWait,
3901 bool *pfNeedsSaveSettings)
3902{
3903 AssertReturn(aProgress != NULL || aWait == true, E_FAIL);
3904
3905 AutoCaller autoCaller(this);
3906 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3907
3908 HRESULT rc = S_OK;
3909 ComObjPtr<Progress> pProgress;
3910 Medium::Task *pTask = NULL;
3911
3912 try
3913 {
3914 /* we're accessing the media tree, and canClose() needs it too */
3915 AutoMultiWriteLock2 multilock(&m->pVirtualBox->getMediaTreeLockHandle(),
3916 this->lockHandle()
3917 COMMA_LOCKVAL_SRC_POS);
3918 LogFlowThisFunc(("aWait=%RTbool locationFull=%s\n", aWait, getLocationFull().c_str() ));
3919
3920 if ( !(m->formatObj->getCapabilities() & ( MediumFormatCapabilities_CreateDynamic
3921 | MediumFormatCapabilities_CreateFixed)))
3922 throw setError(VBOX_E_NOT_SUPPORTED,
3923 tr("Medium format '%s' does not support storage deletion"),
3924 m->strFormat.raw());
3925
3926 /* Note that we are fine with Inaccessible state too: a) for symmetry
3927 * with create calls and b) because it doesn't really harm to try, if
3928 * it is really inaccessible, the delete operation will fail anyway.
3929 * Accepting Inaccessible state is especially important because all
3930 * registered media are initially Inaccessible upon VBoxSVC startup
3931 * until COMGETTER(RefreshState) is called. Accept Deleting state
3932 * because some callers need to put the medium in this state early
3933 * to prevent races. */
3934 switch (m->state)
3935 {
3936 case MediumState_Created:
3937 case MediumState_Deleting:
3938 case MediumState_Inaccessible:
3939 break;
3940 default:
3941 throw setStateError();
3942 }
3943
3944 if (m->backRefs.size() != 0)
3945 {
3946 Utf8Str strMachines;
3947 for (BackRefList::const_iterator it = m->backRefs.begin();
3948 it != m->backRefs.end();
3949 ++it)
3950 {
3951 const BackRef &b = *it;
3952 if (strMachines.length())
3953 strMachines.append(", ");
3954 strMachines.append(b.machineId.toString().c_str());
3955 }
3956#ifdef DEBUG
3957 dumpBackRefs();
3958#endif
3959 throw setError(VBOX_E_OBJECT_IN_USE,
3960 tr("Cannot delete storage: medium '%s' is still attached to the following %d virtual machine(s): %s"),
3961 m->strLocationFull.c_str(),
3962 m->backRefs.size(),
3963 strMachines.c_str());
3964 }
3965
3966 rc = canClose();
3967 if (FAILED(rc))
3968 throw rc;
3969
3970 /* go to Deleting state, so that the medium is not actually locked */
3971 if (m->state != MediumState_Deleting)
3972 {
3973 rc = markForDeletion();
3974 if (FAILED(rc))
3975 throw rc;
3976 }
3977
3978 /* Build the medium lock list. */
3979 MediumLockList *pMediumLockList(new MediumLockList());
3980 rc = createMediumLockList(true /* fFailIfInaccessible */,
3981 true /* fMediumLockWrite */,
3982 NULL,
3983 *pMediumLockList);
3984 if (FAILED(rc))
3985 {
3986 delete pMediumLockList;
3987 throw rc;
3988 }
3989
3990 rc = pMediumLockList->Lock();
3991 if (FAILED(rc))
3992 {
3993 delete pMediumLockList;
3994 throw setError(rc,
3995 tr("Failed to lock media when deleting '%s'"),
3996 getLocationFull().raw());
3997 }
3998
3999 /* try to remove from the list of known media before performing
4000 * actual deletion (we favor the consistency of the media registry
4001 * which would have been broken if unregisterWithVirtualBox() failed
4002 * after we successfully deleted the storage) */
4003 rc = unregisterWithVirtualBox(pfNeedsSaveSettings);
4004 if (FAILED(rc))
4005 throw rc;
4006 // no longer need lock
4007 multilock.release();
4008
4009 if (aProgress != NULL)
4010 {
4011 /* use the existing progress object... */
4012 pProgress = *aProgress;
4013
4014 /* ...but create a new one if it is null */
4015 if (pProgress.isNull())
4016 {
4017 pProgress.createObject();
4018 rc = pProgress->init(m->pVirtualBox,
4019 static_cast<IMedium*>(this),
4020 BstrFmt(tr("Deleting medium storage unit '%s'"), m->strLocationFull.raw()),
4021 FALSE /* aCancelable */);
4022 if (FAILED(rc))
4023 throw rc;
4024 }
4025 }
4026
4027 /* setup task object to carry out the operation sync/async */
4028 pTask = new Medium::DeleteTask(this, pProgress, pMediumLockList);
4029 rc = pTask->rc();
4030 AssertComRC(rc);
4031 if (FAILED(rc))
4032 throw rc;
4033 }
4034 catch (HRESULT aRC) { rc = aRC; }
4035
4036 if (SUCCEEDED(rc))
4037 {
4038 if (aWait)
4039 rc = runNow(pTask, NULL /* pfNeedsSaveSettings*/);
4040 else
4041 rc = startThread(pTask);
4042
4043 if (SUCCEEDED(rc) && aProgress != NULL)
4044 *aProgress = pProgress;
4045
4046 }
4047 else
4048 {
4049 if (pTask)
4050 delete pTask;
4051
4052 /* Undo deleting state if necessary. */
4053 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4054 unmarkForDeletion();
4055 }
4056
4057 return rc;
4058}
4059
4060/**
4061 * Mark a medium for deletion.
4062 *
4063 * @note Caller must hold the write lock on this medium!
4064 */
4065HRESULT Medium::markForDeletion()
4066{
4067 ComAssertRet(this->lockHandle()->isWriteLockOnCurrentThread(), E_FAIL);
4068 switch (m->state)
4069 {
4070 case MediumState_Created:
4071 case MediumState_Inaccessible:
4072 m->preLockState = m->state;
4073 m->state = MediumState_Deleting;
4074 return S_OK;
4075 default:
4076 return setStateError();
4077 }
4078}
4079
4080/**
4081 * Removes the "mark for deletion".
4082 *
4083 * @note Caller must hold the write lock on this medium!
4084 */
4085HRESULT Medium::unmarkForDeletion()
4086{
4087 ComAssertRet(this->lockHandle()->isWriteLockOnCurrentThread(), E_FAIL);
4088 switch (m->state)
4089 {
4090 case MediumState_Deleting:
4091 m->state = m->preLockState;
4092 return S_OK;
4093 default:
4094 return setStateError();
4095 }
4096}
4097
4098/**
4099 * Mark a medium for deletion which is in locked state.
4100 *
4101 * @note Caller must hold the write lock on this medium!
4102 */
4103HRESULT Medium::markLockedForDeletion()
4104{
4105 ComAssertRet(this->lockHandle()->isWriteLockOnCurrentThread(), E_FAIL);
4106 if ( ( m->state == MediumState_LockedRead
4107 || m->state == MediumState_LockedWrite)
4108 && m->preLockState == MediumState_Created)
4109 {
4110 m->preLockState = MediumState_Deleting;
4111 return S_OK;
4112 }
4113 else
4114 return setStateError();
4115}
4116
4117/**
4118 * Removes the "mark for deletion" for a medium in locked state.
4119 *
4120 * @note Caller must hold the write lock on this medium!
4121 */
4122HRESULT Medium::unmarkLockedForDeletion()
4123{
4124 ComAssertRet(this->lockHandle()->isWriteLockOnCurrentThread(), E_FAIL);
4125 if ( ( m->state == MediumState_LockedRead
4126 || m->state == MediumState_LockedWrite)
4127 && m->preLockState == MediumState_Deleting)
4128 {
4129 m->preLockState = MediumState_Created;
4130 return S_OK;
4131 }
4132 else
4133 return setStateError();
4134}
4135
4136/**
4137 * Creates a new differencing storage unit using the format of the given target
4138 * medium and the location. Note that @c aTarget must be NotCreated.
4139 *
4140 * The @a aMediumLockList parameter contains the associated medium lock list,
4141 * which must be in locked state. If @a aWait is @c true then the caller is
4142 * responsible for unlocking.
4143 *
4144 * If @a aProgress is not NULL but the object it points to is @c null then a
4145 * new progress object will be created and assigned to @a *aProgress on
4146 * success, otherwise the existing progress object is used. If @a aProgress is
4147 * NULL, then no progress object is created/used at all.
4148 *
4149 * When @a aWait is @c false, this method will create a thread to perform the
4150 * create operation asynchronously and will return immediately. Otherwise, it
4151 * will perform the operation on the calling thread and will not return to the
4152 * caller until the operation is completed. Note that @a aProgress cannot be
4153 * NULL when @a aWait is @c false (this method will assert in this case).
4154 *
4155 * @param aTarget Target medium.
4156 * @param aVariant Precise medium variant to create.
4157 * @param aMediumLockList List of media which should be locked.
4158 * @param aProgress Where to find/store a Progress object to track
4159 * operation completion.
4160 * @param aWait @c true if this method should block instead of
4161 * creating an asynchronous thread.
4162 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been
4163 * initialized to false and that will be set to true
4164 * by this function if the caller should invoke
4165 * VirtualBox::saveSettings() because the global
4166 * settings have changed. This only works in "wait"
4167 * mode; otherwise saveSettings is called
4168 * automatically by the thread that was created,
4169 * and this parameter is ignored.
4170 *
4171 * @note Locks this object and @a aTarget for writing.
4172 */
4173HRESULT Medium::createDiffStorage(ComObjPtr<Medium> &aTarget,
4174 MediumVariant_T aVariant,
4175 MediumLockList *aMediumLockList,
4176 ComObjPtr<Progress> *aProgress,
4177 bool aWait,
4178 bool *pfNeedsSaveSettings)
4179{
4180 AssertReturn(!aTarget.isNull(), E_FAIL);
4181 AssertReturn(aMediumLockList, E_FAIL);
4182 AssertReturn(aProgress != NULL || aWait == true, E_FAIL);
4183
4184 AutoCaller autoCaller(this);
4185 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4186
4187 AutoCaller targetCaller(aTarget);
4188 if (FAILED(targetCaller.rc())) return targetCaller.rc();
4189
4190 HRESULT rc = S_OK;
4191 ComObjPtr<Progress> pProgress;
4192 Medium::Task *pTask = NULL;
4193
4194 try
4195 {
4196 AutoMultiWriteLock2 alock(this, aTarget COMMA_LOCKVAL_SRC_POS);
4197
4198 ComAssertThrow( m->type != MediumType_Writethrough
4199 && m->type != MediumType_Shareable, E_FAIL);
4200 ComAssertThrow(m->state == MediumState_LockedRead, E_FAIL);
4201
4202 if (aTarget->m->state != MediumState_NotCreated)
4203 throw aTarget->setStateError();
4204
4205 /* Check that the medium is not attached to the current state of
4206 * any VM referring to it. */
4207 for (BackRefList::const_iterator it = m->backRefs.begin();
4208 it != m->backRefs.end();
4209 ++it)
4210 {
4211 if (it->fInCurState)
4212 {
4213 /* Note: when a VM snapshot is being taken, all normal media
4214 * attached to the VM in the current state will be, as an
4215 * exception, also associated with the snapshot which is about
4216 * to create (see SnapshotMachine::init()) before deassociating
4217 * them from the current state (which takes place only on
4218 * success in Machine::fixupHardDisks()), so that the size of
4219 * snapshotIds will be 1 in this case. The extra condition is
4220 * used to filter out this legal situation. */
4221 if (it->llSnapshotIds.size() == 0)
4222 throw setError(VBOX_E_INVALID_OBJECT_STATE,
4223 tr("Medium '%s' is attached to a virtual machine with UUID {%RTuuid}. No differencing media based on it may be created until it is detached"),
4224 m->strLocationFull.raw(), it->machineId.raw());
4225
4226 Assert(it->llSnapshotIds.size() == 1);
4227 }
4228 }
4229
4230 if (aProgress != NULL)
4231 {
4232 /* use the existing progress object... */
4233 pProgress = *aProgress;
4234
4235 /* ...but create a new one if it is null */
4236 if (pProgress.isNull())
4237 {
4238 pProgress.createObject();
4239 rc = pProgress->init(m->pVirtualBox,
4240 static_cast<IMedium*>(this),
4241 BstrFmt(tr("Creating differencing medium storage unit '%s'"), aTarget->m->strLocationFull.raw()),
4242 TRUE /* aCancelable */);
4243 if (FAILED(rc))
4244 throw rc;
4245 }
4246 }
4247
4248 /* setup task object to carry out the operation sync/async */
4249 pTask = new Medium::CreateDiffTask(this, pProgress, aTarget, aVariant,
4250 aMediumLockList,
4251 aWait /* fKeepMediumLockList */);
4252 rc = pTask->rc();
4253 AssertComRC(rc);
4254 if (FAILED(rc))
4255 throw rc;
4256
4257 /* register a task (it will deregister itself when done) */
4258 ++m->numCreateDiffTasks;
4259 Assert(m->numCreateDiffTasks != 0); /* overflow? */
4260
4261 aTarget->m->state = MediumState_Creating;
4262 }
4263 catch (HRESULT aRC) { rc = aRC; }
4264
4265 if (SUCCEEDED(rc))
4266 {
4267 if (aWait)
4268 rc = runNow(pTask, pfNeedsSaveSettings);
4269 else
4270 rc = startThread(pTask);
4271
4272 if (SUCCEEDED(rc) && aProgress != NULL)
4273 *aProgress = pProgress;
4274 }
4275 else if (pTask != NULL)
4276 delete pTask;
4277
4278 return rc;
4279}
4280
4281/**
4282 * Prepares this (source) medium, target medium and all intermediate media
4283 * for the merge operation.
4284 *
4285 * This method is to be called prior to calling the #mergeTo() to perform
4286 * necessary consistency checks and place involved media to appropriate
4287 * states. If #mergeTo() is not called or fails, the state modifications
4288 * performed by this method must be undone by #cancelMergeTo().
4289 *
4290 * See #mergeTo() for more information about merging.
4291 *
4292 * @param pTarget Target medium.
4293 * @param aMachineId Allowed machine attachment. NULL means do not check.
4294 * @param aSnapshotId Allowed snapshot attachment. NULL or empty UUID means
4295 * do not check.
4296 * @param fLockMedia Flag whether to lock the medium lock list or not.
4297 * If set to false and the medium lock list locking fails
4298 * later you must call #cancelMergeTo().
4299 * @param fMergeForward Resulting merge direction (out).
4300 * @param pParentForTarget New parent for target medium after merge (out).
4301 * @param aChildrenToReparent List of children of the source which will have
4302 * to be reparented to the target after merge (out).
4303 * @param aMediumLockList Medium locking information (out).
4304 *
4305 * @note Locks medium tree for reading. Locks this object, aTarget and all
4306 * intermediate media for writing.
4307 */
4308HRESULT Medium::prepareMergeTo(const ComObjPtr<Medium> &pTarget,
4309 const Guid *aMachineId,
4310 const Guid *aSnapshotId,
4311 bool fLockMedia,
4312 bool &fMergeForward,
4313 ComObjPtr<Medium> &pParentForTarget,
4314 MediaList &aChildrenToReparent,
4315 MediumLockList * &aMediumLockList)
4316{
4317 AssertReturn(pTarget != NULL, E_FAIL);
4318 AssertReturn(pTarget != this, E_FAIL);
4319
4320 AutoCaller autoCaller(this);
4321 AssertComRCReturnRC(autoCaller.rc());
4322
4323 AutoCaller targetCaller(pTarget);
4324 AssertComRCReturnRC(targetCaller.rc());
4325
4326 HRESULT rc = S_OK;
4327 fMergeForward = false;
4328 pParentForTarget.setNull();
4329 aChildrenToReparent.clear();
4330 Assert(aMediumLockList == NULL);
4331 aMediumLockList = NULL;
4332
4333 try
4334 {
4335 // locking: we need the tree lock first because we access parent pointers
4336 AutoReadLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
4337
4338 /* more sanity checking and figuring out the merge direction */
4339 ComObjPtr<Medium> pMedium = getParent();
4340 while (!pMedium.isNull() && pMedium != pTarget)
4341 pMedium = pMedium->getParent();
4342 if (pMedium == pTarget)
4343 fMergeForward = false;
4344 else
4345 {
4346 pMedium = pTarget->getParent();
4347 while (!pMedium.isNull() && pMedium != this)
4348 pMedium = pMedium->getParent();
4349 if (pMedium == this)
4350 fMergeForward = true;
4351 else
4352 {
4353 Utf8Str tgtLoc;
4354 {
4355 AutoReadLock alock(pTarget COMMA_LOCKVAL_SRC_POS);
4356 tgtLoc = pTarget->getLocationFull();
4357 }
4358
4359 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4360 throw setError(VBOX_E_INVALID_OBJECT_STATE,
4361 tr("Media '%s' and '%s' are unrelated"),
4362 m->strLocationFull.raw(), tgtLoc.raw());
4363 }
4364 }
4365
4366 /* Build the lock list. */
4367 aMediumLockList = new MediumLockList();
4368 if (fMergeForward)
4369 rc = pTarget->createMediumLockList(true /* fFailIfInaccessible */,
4370 true /* fMediumLockWrite */,
4371 NULL,
4372 *aMediumLockList);
4373 else
4374 rc = createMediumLockList(true /* fFailIfInaccessible */,
4375 false /* fMediumLockWrite */,
4376 NULL,
4377 *aMediumLockList);
4378 if (FAILED(rc))
4379 throw rc;
4380
4381 /* Sanity checking, must be after lock list creation as it depends on
4382 * valid medium states. The medium objects must be accessible. Only
4383 * do this if immediate locking is requested, otherwise it fails when
4384 * we construct a medium lock list for an already running VM. Snapshot
4385 * deletion uses this to simplify its life. */
4386 if (fLockMedia)
4387 {
4388 {
4389 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4390 if (m->state != MediumState_Created)
4391 throw setStateError();
4392 }
4393 {
4394 AutoReadLock alock(pTarget COMMA_LOCKVAL_SRC_POS);
4395 if (pTarget->m->state != MediumState_Created)
4396 throw pTarget->setStateError();
4397 }
4398 }
4399
4400 /* check medium attachment and other sanity conditions */
4401 if (fMergeForward)
4402 {
4403 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4404 if (getChildren().size() > 1)
4405 {
4406 throw setError(VBOX_E_INVALID_OBJECT_STATE,
4407 tr("Medium '%s' involved in the merge operation has more than one child medium (%d)"),
4408 m->strLocationFull.raw(), getChildren().size());
4409 }
4410 /* One backreference is only allowed if the machine ID is not empty
4411 * and it matches the machine the medium is attached to (including
4412 * the snapshot ID if not empty). */
4413 if ( m->backRefs.size() != 0
4414 && ( !aMachineId
4415 || m->backRefs.size() != 1
4416 || aMachineId->isEmpty()
4417 || *getFirstMachineBackrefId() != *aMachineId
4418 || ( (!aSnapshotId || !aSnapshotId->isEmpty())
4419 && *getFirstMachineBackrefSnapshotId() != *aSnapshotId)))
4420 throw setError(VBOX_E_OBJECT_IN_USE,
4421 tr("Medium '%s' is attached to %d virtual machines"),
4422 m->strLocationFull.raw(), m->backRefs.size());
4423 if (m->type == MediumType_Immutable)
4424 throw setError(VBOX_E_INVALID_OBJECT_STATE,
4425 tr("Medium '%s' is immutable"),
4426 m->strLocationFull.raw());
4427 }
4428 else
4429 {
4430 AutoReadLock alock(pTarget COMMA_LOCKVAL_SRC_POS);
4431 if (pTarget->getChildren().size() > 1)
4432 {
4433 throw setError(VBOX_E_OBJECT_IN_USE,
4434 tr("Medium '%s' involved in the merge operation has more than one child medium (%d)"),
4435 pTarget->m->strLocationFull.raw(),
4436 pTarget->getChildren().size());
4437 }
4438 if (pTarget->m->type == MediumType_Immutable)
4439 throw setError(VBOX_E_INVALID_OBJECT_STATE,
4440 tr("Medium '%s' is immutable"),
4441 pTarget->m->strLocationFull.raw());
4442 }
4443 ComObjPtr<Medium> pLast(fMergeForward ? (Medium *)pTarget : this);
4444 ComObjPtr<Medium> pLastIntermediate = pLast->getParent();
4445 for (pLast = pLastIntermediate;
4446 !pLast.isNull() && pLast != pTarget && pLast != this;
4447 pLast = pLast->getParent())
4448 {
4449 AutoReadLock alock(pLast COMMA_LOCKVAL_SRC_POS);
4450 if (pLast->getChildren().size() > 1)
4451 {
4452 throw setError(VBOX_E_OBJECT_IN_USE,
4453 tr("Medium '%s' involved in the merge operation has more than one child medium (%d)"),
4454 pLast->m->strLocationFull.raw(),
4455 pLast->getChildren().size());
4456 }
4457 if (pLast->m->backRefs.size() != 0)
4458 throw setError(VBOX_E_OBJECT_IN_USE,
4459 tr("Medium '%s' is attached to %d virtual machines"),
4460 pLast->m->strLocationFull.raw(),
4461 pLast->m->backRefs.size());
4462
4463 }
4464
4465 /* Update medium states appropriately */
4466 if (m->state == MediumState_Created)
4467 {
4468 rc = markForDeletion();
4469 if (FAILED(rc))
4470 throw rc;
4471 }
4472 else
4473 {
4474 if (fLockMedia)
4475 throw setStateError();
4476 else if ( m->state == MediumState_LockedWrite
4477 || m->state == MediumState_LockedRead)
4478 {
4479 /* Either mark it for deletiion in locked state or allow
4480 * others to have done so. */
4481 if (m->preLockState == MediumState_Created)
4482 markLockedForDeletion();
4483 else if (m->preLockState != MediumState_Deleting)
4484 throw setStateError();
4485 }
4486 else
4487 throw setStateError();
4488 }
4489
4490 if (fMergeForward)
4491 {
4492 /* we will need parent to reparent target */
4493 pParentForTarget = m->pParent;
4494 }
4495 else
4496 {
4497 /* we will need to reparent children of the source */
4498 for (MediaList::const_iterator it = getChildren().begin();
4499 it != getChildren().end();
4500 ++it)
4501 {
4502 pMedium = *it;
4503 if (fLockMedia)
4504 {
4505 rc = pMedium->LockWrite(NULL);
4506 if (FAILED(rc))
4507 throw rc;
4508 }
4509
4510 aChildrenToReparent.push_back(pMedium);
4511 }
4512 }
4513 for (pLast = pLastIntermediate;
4514 !pLast.isNull() && pLast != pTarget && pLast != this;
4515 pLast = pLast->getParent())
4516 {
4517 AutoWriteLock alock(pLast COMMA_LOCKVAL_SRC_POS);
4518 if (pLast->m->state == MediumState_Created)
4519 {
4520 rc = pLast->markForDeletion();
4521 if (FAILED(rc))
4522 throw rc;
4523 }
4524 else
4525 throw pLast->setStateError();
4526 }
4527
4528 /* Tweak the lock list in the backward merge case, as the target
4529 * isn't marked to be locked for writing yet. */
4530 if (!fMergeForward)
4531 {
4532 MediumLockList::Base::iterator lockListBegin =
4533 aMediumLockList->GetBegin();
4534 MediumLockList::Base::iterator lockListEnd =
4535 aMediumLockList->GetEnd();
4536 lockListEnd--;
4537 for (MediumLockList::Base::iterator it = lockListBegin;
4538 it != lockListEnd;
4539 ++it)
4540 {
4541 MediumLock &mediumLock = *it;
4542 if (mediumLock.GetMedium() == pTarget)
4543 {
4544 HRESULT rc2 = mediumLock.UpdateLock(true);
4545 AssertComRC(rc2);
4546 break;
4547 }
4548 }
4549 }
4550
4551 if (fLockMedia)
4552 {
4553 rc = aMediumLockList->Lock();
4554 if (FAILED(rc))
4555 {
4556 AutoReadLock alock(pTarget COMMA_LOCKVAL_SRC_POS);
4557 throw setError(rc,
4558 tr("Failed to lock media when merging to '%s'"),
4559 pTarget->getLocationFull().raw());
4560 }
4561 }
4562 }
4563 catch (HRESULT aRC) { rc = aRC; }
4564
4565 if (FAILED(rc))
4566 {
4567 delete aMediumLockList;
4568 aMediumLockList = NULL;
4569 }
4570
4571 return rc;
4572}
4573
4574/**
4575 * Merges this medium to the specified medium which must be either its
4576 * direct ancestor or descendant.
4577 *
4578 * Given this medium is SOURCE and the specified medium is TARGET, we will
4579 * get two variants of the merge operation:
4580 *
4581 * forward merge
4582 * ------------------------->
4583 * [Extra] <- SOURCE <- Intermediate <- TARGET
4584 * Any Del Del LockWr
4585 *
4586 *
4587 * backward merge
4588 * <-------------------------
4589 * TARGET <- Intermediate <- SOURCE <- [Extra]
4590 * LockWr Del Del LockWr
4591 *
4592 * Each diagram shows the involved media on the media chain where
4593 * SOURCE and TARGET belong. Under each medium there is a state value which
4594 * the medium must have at a time of the mergeTo() call.
4595 *
4596 * The media in the square braces may be absent (e.g. when the forward
4597 * operation takes place and SOURCE is the base medium, or when the backward
4598 * merge operation takes place and TARGET is the last child in the chain) but if
4599 * they present they are involved too as shown.
4600 *
4601 * Neither the source medium nor intermediate media may be attached to
4602 * any VM directly or in the snapshot, otherwise this method will assert.
4603 *
4604 * The #prepareMergeTo() method must be called prior to this method to place all
4605 * involved to necessary states and perform other consistency checks.
4606 *
4607 * If @a aWait is @c true then this method will perform the operation on the
4608 * calling thread and will not return to the caller until the operation is
4609 * completed. When this method succeeds, all intermediate medium objects in
4610 * the chain will be uninitialized, the state of the target medium (and all
4611 * involved extra media) will be restored. @a aMediumLockList will not be
4612 * deleted, whether the operation is successful or not. The caller has to do
4613 * this if appropriate. Note that this (source) medium is not uninitialized
4614 * because of possible AutoCaller instances held by the caller of this method
4615 * on the current thread. It's therefore the responsibility of the caller to
4616 * call Medium::uninit() after releasing all callers.
4617 *
4618 * If @a aWait is @c false then this method will create a thread to perform the
4619 * operation asynchronously and will return immediately. If the operation
4620 * succeeds, the thread will uninitialize the source medium object and all
4621 * intermediate medium objects in the chain, reset the state of the target
4622 * medium (and all involved extra media) and delete @a aMediumLockList.
4623 * If the operation fails, the thread will only reset the states of all
4624 * involved media and delete @a aMediumLockList.
4625 *
4626 * When this method fails (regardless of the @a aWait mode), it is a caller's
4627 * responsiblity to undo state changes and delete @a aMediumLockList using
4628 * #cancelMergeTo().
4629 *
4630 * If @a aProgress is not NULL but the object it points to is @c null then a new
4631 * progress object will be created and assigned to @a *aProgress on success,
4632 * otherwise the existing progress object is used. If Progress is NULL, then no
4633 * progress object is created/used at all. Note that @a aProgress cannot be
4634 * NULL when @a aWait is @c false (this method will assert in this case).
4635 *
4636 * @param pTarget Target medium.
4637 * @param fMergeForward Merge direction.
4638 * @param pParentForTarget New parent for target medium after merge.
4639 * @param aChildrenToReparent List of children of the source which will have
4640 * to be reparented to the target after merge.
4641 * @param aMediumLockList Medium locking information.
4642 * @param aProgress Where to find/store a Progress object to track operation
4643 * completion.
4644 * @param aWait @c true if this method should block instead of creating
4645 * an asynchronous thread.
4646 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
4647 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
4648 * This only works in "wait" mode; otherwise saveSettings gets called automatically by the thread that was created,
4649 * and this parameter is ignored.
4650 *
4651 * @note Locks the tree lock for writing. Locks the media from the chain
4652 * for writing.
4653 */
4654HRESULT Medium::mergeTo(const ComObjPtr<Medium> &pTarget,
4655 bool fMergeForward,
4656 const ComObjPtr<Medium> &pParentForTarget,
4657 const MediaList &aChildrenToReparent,
4658 MediumLockList *aMediumLockList,
4659 ComObjPtr <Progress> *aProgress,
4660 bool aWait,
4661 bool *pfNeedsSaveSettings)
4662{
4663 AssertReturn(pTarget != NULL, E_FAIL);
4664 AssertReturn(pTarget != this, E_FAIL);
4665 AssertReturn(aMediumLockList != NULL, E_FAIL);
4666 AssertReturn(aProgress != NULL || aWait == true, E_FAIL);
4667
4668 AutoCaller autoCaller(this);
4669 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4670
4671 AutoCaller targetCaller(pTarget);
4672 AssertComRCReturnRC(targetCaller.rc());
4673
4674 HRESULT rc = S_OK;
4675 ComObjPtr <Progress> pProgress;
4676 Medium::Task *pTask = NULL;
4677
4678 try
4679 {
4680 if (aProgress != NULL)
4681 {
4682 /* use the existing progress object... */
4683 pProgress = *aProgress;
4684
4685 /* ...but create a new one if it is null */
4686 if (pProgress.isNull())
4687 {
4688 Utf8Str tgtName;
4689 {
4690 AutoReadLock alock(pTarget COMMA_LOCKVAL_SRC_POS);
4691 tgtName = pTarget->getName();
4692 }
4693
4694 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4695
4696 pProgress.createObject();
4697 rc = pProgress->init(m->pVirtualBox,
4698 static_cast<IMedium*>(this),
4699 BstrFmt(tr("Merging medium '%s' to '%s'"),
4700 getName().raw(),
4701 tgtName.raw()),
4702 TRUE /* aCancelable */);
4703 if (FAILED(rc))
4704 throw rc;
4705 }
4706 }
4707
4708 /* setup task object to carry out the operation sync/async */
4709 pTask = new Medium::MergeTask(this, pTarget, fMergeForward,
4710 pParentForTarget, aChildrenToReparent,
4711 pProgress, aMediumLockList,
4712 aWait /* fKeepMediumLockList */);
4713 rc = pTask->rc();
4714 AssertComRC(rc);
4715 if (FAILED(rc))
4716 throw rc;
4717 }
4718 catch (HRESULT aRC) { rc = aRC; }
4719
4720 if (SUCCEEDED(rc))
4721 {
4722 if (aWait)
4723 rc = runNow(pTask, pfNeedsSaveSettings);
4724 else
4725 rc = startThread(pTask);
4726
4727 if (SUCCEEDED(rc) && aProgress != NULL)
4728 *aProgress = pProgress;
4729 }
4730 else if (pTask != NULL)
4731 delete pTask;
4732
4733 return rc;
4734}
4735
4736/**
4737 * Undoes what #prepareMergeTo() did. Must be called if #mergeTo() is not
4738 * called or fails. Frees memory occupied by @a aMediumLockList and unlocks
4739 * the medium objects in @a aChildrenToReparent.
4740 *
4741 * @param aChildrenToReparent List of children of the source which will have
4742 * to be reparented to the target after merge.
4743 * @param aMediumLockList Medium locking information.
4744 *
4745 * @note Locks the media from the chain for writing.
4746 */
4747void Medium::cancelMergeTo(const MediaList &aChildrenToReparent,
4748 MediumLockList *aMediumLockList)
4749{
4750 AutoCaller autoCaller(this);
4751 AssertComRCReturnVoid(autoCaller.rc());
4752
4753 AssertReturnVoid(aMediumLockList != NULL);
4754
4755 /* Revert media marked for deletion to previous state. */
4756 HRESULT rc;
4757 MediumLockList::Base::const_iterator mediumListBegin =
4758 aMediumLockList->GetBegin();
4759 MediumLockList::Base::const_iterator mediumListEnd =
4760 aMediumLockList->GetEnd();
4761 for (MediumLockList::Base::const_iterator it = mediumListBegin;
4762 it != mediumListEnd;
4763 ++it)
4764 {
4765 const MediumLock &mediumLock = *it;
4766 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
4767 AutoWriteLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
4768
4769 if (pMedium->m->state == MediumState_Deleting)
4770 {
4771 rc = pMedium->unmarkForDeletion();
4772 AssertComRC(rc);
4773 }
4774 }
4775
4776 /* the destructor will do the work */
4777 delete aMediumLockList;
4778
4779 /* unlock the children which had to be reparented */
4780 for (MediaList::const_iterator it = aChildrenToReparent.begin();
4781 it != aChildrenToReparent.end();
4782 ++it)
4783 {
4784 const ComObjPtr<Medium> &pMedium = *it;
4785
4786 AutoWriteLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
4787 pMedium->UnlockWrite(NULL);
4788 }
4789}
4790
4791////////////////////////////////////////////////////////////////////////////////
4792//
4793// Private methods
4794//
4795////////////////////////////////////////////////////////////////////////////////
4796
4797/**
4798 * Performs extra checks if the medium can be closed and returns S_OK in
4799 * this case. Otherwise, returns a respective error message. Called by
4800 * Close() under the medium tree lock and the medium lock.
4801 *
4802 * @note Also reused by Medium::Reset().
4803 *
4804 * @note Caller must hold the media tree write lock!
4805 */
4806HRESULT Medium::canClose()
4807{
4808 Assert(m->pVirtualBox->getMediaTreeLockHandle().isWriteLockOnCurrentThread());
4809
4810 if (getChildren().size() != 0)
4811 return setError(VBOX_E_OBJECT_IN_USE,
4812 tr("Cannot close medium '%s' because it has %d child media"),
4813 m->strLocationFull.raw(), getChildren().size());
4814
4815 return S_OK;
4816}
4817
4818/**
4819 * Unregisters this medium with mVirtualBox. Called by close() under the medium tree lock.
4820 *
4821 * This calls either VirtualBox::unregisterImage or VirtualBox::unregisterHardDisk depending
4822 * on the device type of this medium.
4823 *
4824 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
4825 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
4826 *
4827 * @note Caller must have locked the media tree lock for writing!
4828 */
4829HRESULT Medium::unregisterWithVirtualBox(bool *pfNeedsSaveSettings)
4830{
4831 /* Note that we need to de-associate ourselves from the parent to let
4832 * unregisterHardDisk() properly save the registry */
4833
4834 /* we modify mParent and access children */
4835 Assert(m->pVirtualBox->getMediaTreeLockHandle().isWriteLockOnCurrentThread());
4836
4837 Medium *pParentBackup = m->pParent;
4838 AssertReturn(getChildren().size() == 0, E_FAIL);
4839 if (m->pParent)
4840 deparent();
4841
4842 HRESULT rc = E_FAIL;
4843 switch (m->devType)
4844 {
4845 case DeviceType_DVD:
4846 rc = m->pVirtualBox->unregisterImage(this, DeviceType_DVD, pfNeedsSaveSettings);
4847 break;
4848
4849 case DeviceType_Floppy:
4850 rc = m->pVirtualBox->unregisterImage(this, DeviceType_Floppy, pfNeedsSaveSettings);
4851 break;
4852
4853 case DeviceType_HardDisk:
4854 rc = m->pVirtualBox->unregisterHardDisk(this, pfNeedsSaveSettings);
4855 break;
4856
4857 default:
4858 break;
4859 }
4860
4861 if (FAILED(rc))
4862 {
4863 if (pParentBackup)
4864 {
4865 // re-associate with the parent as we are still relatives in the registry
4866 m->pParent = pParentBackup;
4867 m->pParent->m->llChildren.push_back(this);
4868 }
4869 }
4870
4871 return rc;
4872}
4873
4874/**
4875 * Checks that the format ID is valid and sets it on success.
4876 *
4877 * Note that this method will caller-reference the format object on success!
4878 * This reference must be released somewhere to let the MediumFormat object be
4879 * uninitialized.
4880 *
4881 * @note Must be called from under this object's write lock.
4882 */
4883HRESULT Medium::setFormat(const Utf8Str &aFormat)
4884{
4885 /* get the format object first */
4886 {
4887 SystemProperties *pSysProps = m->pVirtualBox->getSystemProperties();
4888 AutoReadLock propsLock(pSysProps COMMA_LOCKVAL_SRC_POS);
4889
4890 unconst(m->formatObj) = pSysProps->mediumFormat(aFormat);
4891 if (m->formatObj.isNull())
4892 return setError(E_INVALIDARG,
4893 tr("Invalid medium storage format '%s'"),
4894 aFormat.c_str());
4895
4896 /* reference the format permanently to prevent its unexpected
4897 * uninitialization */
4898 HRESULT rc = m->formatObj->addCaller();
4899 AssertComRCReturnRC(rc);
4900
4901 /* get properties (preinsert them as keys in the map). Note that the
4902 * map doesn't grow over the object life time since the set of
4903 * properties is meant to be constant. */
4904
4905 Assert(m->properties.empty());
4906
4907 for (MediumFormat::PropertyList::const_iterator it = m->formatObj->getProperties().begin();
4908 it != m->formatObj->getProperties().end();
4909 ++it)
4910 {
4911 m->properties.insert(std::make_pair(it->strName, Utf8Str::Empty));
4912 }
4913 }
4914
4915 unconst(m->strFormat) = aFormat;
4916
4917 return S_OK;
4918}
4919
4920/**
4921 * Returns the last error message collected by the vdErrorCall callback and
4922 * resets it.
4923 *
4924 * The error message is returned prepended with a dot and a space, like this:
4925 * <code>
4926 * ". <error_text> (%Rrc)"
4927 * </code>
4928 * to make it easily appendable to a more general error message. The @c %Rrc
4929 * format string is given @a aVRC as an argument.
4930 *
4931 * If there is no last error message collected by vdErrorCall or if it is a
4932 * null or empty string, then this function returns the following text:
4933 * <code>
4934 * " (%Rrc)"
4935 * </code>
4936 *
4937 * @note Doesn't do any object locking; it is assumed that the caller makes sure
4938 * the callback isn't called by more than one thread at a time.
4939 *
4940 * @param aVRC VBox error code to use when no error message is provided.
4941 */
4942Utf8Str Medium::vdError(int aVRC)
4943{
4944 Utf8Str error;
4945
4946 if (m->vdError.isEmpty())
4947 error = Utf8StrFmt(" (%Rrc)", aVRC);
4948 else
4949 error = Utf8StrFmt(".\n%s", m->vdError.raw());
4950
4951 m->vdError.setNull();
4952
4953 return error;
4954}
4955
4956/**
4957 * Error message callback.
4958 *
4959 * Puts the reported error message to the m->vdError field.
4960 *
4961 * @note Doesn't do any object locking; it is assumed that the caller makes sure
4962 * the callback isn't called by more than one thread at a time.
4963 *
4964 * @param pvUser The opaque data passed on container creation.
4965 * @param rc The VBox error code.
4966 * @param RT_SRC_POS_DECL Use RT_SRC_POS.
4967 * @param pszFormat Error message format string.
4968 * @param va Error message arguments.
4969 */
4970/*static*/
4971DECLCALLBACK(void) Medium::vdErrorCall(void *pvUser, int rc, RT_SRC_POS_DECL,
4972 const char *pszFormat, va_list va)
4973{
4974 NOREF(pszFile); NOREF(iLine); NOREF(pszFunction); /* RT_SRC_POS_DECL */
4975
4976 Medium *that = static_cast<Medium*>(pvUser);
4977 AssertReturnVoid(that != NULL);
4978
4979 if (that->m->vdError.isEmpty())
4980 that->m->vdError =
4981 Utf8StrFmt("%s (%Rrc)", Utf8StrFmtVA(pszFormat, va).raw(), rc);
4982 else
4983 that->m->vdError =
4984 Utf8StrFmt("%s.\n%s (%Rrc)", that->m->vdError.raw(),
4985 Utf8StrFmtVA(pszFormat, va).raw(), rc);
4986}
4987
4988/* static */
4989DECLCALLBACK(bool) Medium::vdConfigAreKeysValid(void *pvUser,
4990 const char * /* pszzValid */)
4991{
4992 Medium *that = static_cast<Medium*>(pvUser);
4993 AssertReturn(that != NULL, false);
4994
4995 /* we always return true since the only keys we have are those found in
4996 * VDBACKENDINFO */
4997 return true;
4998}
4999
5000/* static */
5001DECLCALLBACK(int) Medium::vdConfigQuerySize(void *pvUser, const char *pszName,
5002 size_t *pcbValue)
5003{
5004 AssertReturn(VALID_PTR(pcbValue), VERR_INVALID_POINTER);
5005
5006 Medium *that = static_cast<Medium*>(pvUser);
5007 AssertReturn(that != NULL, VERR_GENERAL_FAILURE);
5008
5009 Data::PropertyMap::const_iterator it =
5010 that->m->properties.find(Bstr(pszName));
5011 if (it == that->m->properties.end())
5012 return VERR_CFGM_VALUE_NOT_FOUND;
5013
5014 /* we interpret null values as "no value" in Medium */
5015 if (it->second.isEmpty())
5016 return VERR_CFGM_VALUE_NOT_FOUND;
5017
5018 *pcbValue = it->second.length() + 1 /* include terminator */;
5019
5020 return VINF_SUCCESS;
5021}
5022
5023/* static */
5024DECLCALLBACK(int) Medium::vdConfigQuery(void *pvUser, const char *pszName,
5025 char *pszValue, size_t cchValue)
5026{
5027 AssertReturn(VALID_PTR(pszValue), VERR_INVALID_POINTER);
5028
5029 Medium *that = static_cast<Medium*>(pvUser);
5030 AssertReturn(that != NULL, VERR_GENERAL_FAILURE);
5031
5032 Data::PropertyMap::const_iterator it =
5033 that->m->properties.find(Bstr(pszName));
5034 if (it == that->m->properties.end())
5035 return VERR_CFGM_VALUE_NOT_FOUND;
5036
5037 Utf8Str value = it->second;
5038 if (value.length() >= cchValue)
5039 return VERR_CFGM_NOT_ENOUGH_SPACE;
5040
5041 /* we interpret null values as "no value" in Medium */
5042 if (it->second.isEmpty())
5043 return VERR_CFGM_VALUE_NOT_FOUND;
5044
5045 memcpy(pszValue, value.c_str(), value.length() + 1);
5046
5047 return VINF_SUCCESS;
5048}
5049
5050DECLCALLBACK(int) Medium::vdTcpSocketCreate(uint32_t fFlags, PVDSOCKET pSock)
5051{
5052 PVDSOCKETINT pSocketInt = NULL;
5053
5054 if ((fFlags & VD_INTERFACETCPNET_CONNECT_EXTENDED_SELECT) != 0)
5055 return VERR_NOT_SUPPORTED;
5056
5057 pSocketInt = (PVDSOCKETINT)RTMemAllocZ(sizeof(VDSOCKETINT));
5058 if (!pSocketInt)
5059 return VERR_NO_MEMORY;
5060
5061 pSocketInt->hSocket = NIL_RTSOCKET;
5062 *pSock = pSocketInt;
5063 return VINF_SUCCESS;
5064}
5065
5066DECLCALLBACK(int) Medium::vdTcpSocketDestroy(VDSOCKET Sock)
5067{
5068 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
5069
5070 if (pSocketInt->hSocket != NIL_RTSOCKET)
5071 RTTcpClientClose(pSocketInt->hSocket);
5072
5073 RTMemFree(pSocketInt);
5074
5075 return VINF_SUCCESS;
5076}
5077
5078DECLCALLBACK(int) Medium::vdTcpClientConnect(VDSOCKET Sock, const char *pszAddress, uint32_t uPort)
5079{
5080 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
5081
5082 return RTTcpClientConnect(pszAddress, uPort, &pSocketInt->hSocket);
5083}
5084
5085DECLCALLBACK(int) Medium::vdTcpClientClose(VDSOCKET Sock)
5086{
5087 int rc = VINF_SUCCESS;
5088 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
5089
5090 rc = RTTcpClientClose(pSocketInt->hSocket);
5091 pSocketInt->hSocket = NIL_RTSOCKET;
5092 return rc;
5093}
5094
5095DECLCALLBACK(bool) Medium::vdTcpIsClientConnected(VDSOCKET Sock)
5096{
5097 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
5098 return pSocketInt->hSocket != NIL_RTSOCKET;
5099}
5100
5101DECLCALLBACK(int) Medium::vdTcpSelectOne(VDSOCKET Sock, RTMSINTERVAL cMillies)
5102{
5103 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
5104 return RTTcpSelectOne(pSocketInt->hSocket, cMillies);
5105}
5106
5107DECLCALLBACK(int) Medium::vdTcpRead(VDSOCKET Sock, void *pvBuffer, size_t cbBuffer, size_t *pcbRead)
5108{
5109 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
5110 return RTTcpRead(pSocketInt->hSocket, pvBuffer, cbBuffer, pcbRead);
5111}
5112
5113DECLCALLBACK(int) Medium::vdTcpWrite(VDSOCKET Sock, const void *pvBuffer, size_t cbBuffer)
5114{
5115 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
5116 return RTTcpWrite(pSocketInt->hSocket, pvBuffer, cbBuffer);
5117}
5118
5119DECLCALLBACK(int) Medium::vdTcpSgWrite(VDSOCKET Sock, PCRTSGBUF pSgBuf)
5120{
5121 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
5122 return RTTcpSgWrite(pSocketInt->hSocket, pSgBuf);
5123}
5124
5125DECLCALLBACK(int) Medium::vdTcpFlush(VDSOCKET Sock)
5126{
5127 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
5128 return RTTcpFlush(pSocketInt->hSocket);
5129}
5130
5131DECLCALLBACK(int) Medium::vdTcpSetSendCoalescing(VDSOCKET Sock, bool fEnable)
5132{
5133 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
5134 return RTTcpSetSendCoalescing(pSocketInt->hSocket, fEnable);
5135}
5136
5137DECLCALLBACK(int) Medium::vdTcpGetLocalAddress(VDSOCKET Sock, PRTNETADDR pAddr)
5138{
5139 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
5140 return RTTcpGetLocalAddress(pSocketInt->hSocket, pAddr);
5141}
5142
5143DECLCALLBACK(int) Medium::vdTcpGetPeerAddress(VDSOCKET Sock, PRTNETADDR pAddr)
5144{
5145 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
5146 return RTTcpGetPeerAddress(pSocketInt->hSocket, pAddr);
5147}
5148
5149
5150/**
5151 * Starts a new thread driven by the appropriate Medium::Task::handler() method.
5152 *
5153 * @note When the task is executed by this method, IProgress::notifyComplete()
5154 * is automatically called for the progress object associated with this
5155 * task when the task is finished to signal the operation completion for
5156 * other threads asynchronously waiting for it.
5157 */
5158HRESULT Medium::startThread(Medium::Task *pTask)
5159{
5160#ifdef VBOX_WITH_MAIN_LOCK_VALIDATION
5161 /* Extreme paranoia: The calling thread should not hold the medium
5162 * tree lock or any medium lock. Since there is no separate lock class
5163 * for medium objects be even more strict: no other object locks. */
5164 Assert(!AutoLockHoldsLocksInClass(LOCKCLASS_LISTOFMEDIA));
5165 Assert(!AutoLockHoldsLocksInClass(getLockingClass()));
5166#endif
5167
5168 /// @todo use a more descriptive task name
5169 int vrc = RTThreadCreate(NULL, Medium::Task::fntMediumTask, pTask,
5170 0, RTTHREADTYPE_MAIN_HEAVY_WORKER, 0,
5171 "Medium::Task");
5172 if (RT_FAILURE(vrc))
5173 {
5174 delete pTask;
5175 return setError(E_FAIL, "Could not create Medium::Task thread (%Rrc)\n", vrc);
5176 }
5177
5178 return S_OK;
5179}
5180
5181/**
5182 * Fix the parent UUID of all children to point to this medium as their
5183 * parent.
5184 */
5185HRESULT Medium::fixParentUuidOfChildren(const MediaList &childrenToReparent)
5186{
5187 MediumLockList mediumLockList;
5188 HRESULT rc = createMediumLockList(true /* fFailIfInaccessible */,
5189 false /* fMediumLockWrite */,
5190 this,
5191 mediumLockList);
5192 AssertComRCReturnRC(rc);
5193
5194 try
5195 {
5196 PVBOXHDD hdd;
5197 int vrc = VDCreate(m->vdDiskIfaces, &hdd);
5198 ComAssertRCThrow(vrc, E_FAIL);
5199
5200 try
5201 {
5202 MediumLockList::Base::iterator lockListBegin =
5203 mediumLockList.GetBegin();
5204 MediumLockList::Base::iterator lockListEnd =
5205 mediumLockList.GetEnd();
5206 for (MediumLockList::Base::iterator it = lockListBegin;
5207 it != lockListEnd;
5208 ++it)
5209 {
5210 MediumLock &mediumLock = *it;
5211 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
5212 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
5213
5214 // open the medium
5215 vrc = VDOpen(hdd,
5216 pMedium->m->strFormat.c_str(),
5217 pMedium->m->strLocationFull.c_str(),
5218 VD_OPEN_FLAGS_READONLY,
5219 pMedium->m->vdDiskIfaces);
5220 if (RT_FAILURE(vrc))
5221 throw vrc;
5222 }
5223
5224 for (MediaList::const_iterator it = childrenToReparent.begin();
5225 it != childrenToReparent.end();
5226 ++it)
5227 {
5228 /* VD_OPEN_FLAGS_INFO since UUID is wrong yet */
5229 vrc = VDOpen(hdd,
5230 (*it)->m->strFormat.c_str(),
5231 (*it)->m->strLocationFull.c_str(),
5232 VD_OPEN_FLAGS_INFO,
5233 (*it)->m->vdDiskIfaces);
5234 if (RT_FAILURE(vrc))
5235 throw vrc;
5236
5237 vrc = VDSetParentUuid(hdd, VD_LAST_IMAGE, m->id);
5238 if (RT_FAILURE(vrc))
5239 throw vrc;
5240
5241 vrc = VDClose(hdd, false /* fDelete */);
5242 if (RT_FAILURE(vrc))
5243 throw vrc;
5244
5245 (*it)->UnlockWrite(NULL);
5246 }
5247 }
5248 catch (HRESULT aRC) { rc = aRC; }
5249 catch (int aVRC)
5250 {
5251 throw setError(E_FAIL,
5252 tr("Could not update medium UUID references to parent '%s' (%s)"),
5253 m->strLocationFull.raw(),
5254 vdError(aVRC).raw());
5255 }
5256
5257 VDDestroy(hdd);
5258 }
5259 catch (HRESULT aRC) { rc = aRC; }
5260
5261 return rc;
5262}
5263
5264/**
5265 * Runs Medium::Task::handler() on the current thread instead of creating
5266 * a new one.
5267 *
5268 * This call implies that it is made on another temporary thread created for
5269 * some asynchronous task. Avoid calling it from a normal thread since the task
5270 * operations are potentially lengthy and will block the calling thread in this
5271 * case.
5272 *
5273 * @note When the task is executed by this method, IProgress::notifyComplete()
5274 * is not called for the progress object associated with this task when
5275 * the task is finished. Instead, the result of the operation is returned
5276 * by this method directly and it's the caller's responsibility to
5277 * complete the progress object in this case.
5278 */
5279HRESULT Medium::runNow(Medium::Task *pTask,
5280 bool *pfNeedsSaveSettings)
5281{
5282#ifdef VBOX_WITH_MAIN_LOCK_VALIDATION
5283 /* Extreme paranoia: The calling thread should not hold the medium
5284 * tree lock or any medium lock. Since there is no separate lock class
5285 * for medium objects be even more strict: no other object locks. */
5286 Assert(!AutoLockHoldsLocksInClass(LOCKCLASS_LISTOFMEDIA));
5287 Assert(!AutoLockHoldsLocksInClass(getLockingClass()));
5288#endif
5289
5290 pTask->m_pfNeedsSaveSettings = pfNeedsSaveSettings;
5291
5292 /* NIL_RTTHREAD indicates synchronous call. */
5293 return (HRESULT)Medium::Task::fntMediumTask(NIL_RTTHREAD, pTask);
5294}
5295
5296/**
5297 * Implementation code for the "create base" task.
5298 *
5299 * This only gets started from Medium::CreateBaseStorage() and always runs
5300 * asynchronously. As a result, we always save the VirtualBox.xml file when
5301 * we're done here.
5302 *
5303 * @param task
5304 * @return
5305 */
5306HRESULT Medium::taskCreateBaseHandler(Medium::CreateBaseTask &task)
5307{
5308 HRESULT rc = S_OK;
5309
5310 /* these parameters we need after creation */
5311 uint64_t size = 0, logicalSize = 0;
5312 MediumVariant_T variant = MediumVariant_Standard;
5313 bool fGenerateUuid = false;
5314
5315 try
5316 {
5317 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
5318
5319 /* The object may request a specific UUID (through a special form of
5320 * the setLocation() argument). Otherwise we have to generate it */
5321 Guid id = m->id;
5322 fGenerateUuid = id.isEmpty();
5323 if (fGenerateUuid)
5324 {
5325 id.create();
5326 /* VirtualBox::registerHardDisk() will need UUID */
5327 unconst(m->id) = id;
5328 }
5329
5330 Utf8Str format(m->strFormat);
5331 Utf8Str location(m->strLocationFull);
5332 uint64_t capabilities = m->formatObj->getCapabilities();
5333 ComAssertThrow(capabilities & ( VD_CAP_CREATE_FIXED
5334 | VD_CAP_CREATE_DYNAMIC), E_FAIL);
5335 Assert(m->state == MediumState_Creating);
5336
5337 PVBOXHDD hdd;
5338 int vrc = VDCreate(m->vdDiskIfaces, &hdd);
5339 ComAssertRCThrow(vrc, E_FAIL);
5340
5341 /* unlock before the potentially lengthy operation */
5342 thisLock.release();
5343
5344 try
5345 {
5346 /* ensure the directory exists */
5347 rc = VirtualBox::ensureFilePathExists(location);
5348 if (FAILED(rc))
5349 throw rc;
5350
5351 PDMMEDIAGEOMETRY geo = { 0, 0, 0 }; /* auto-detect */
5352
5353 vrc = VDCreateBase(hdd,
5354 format.c_str(),
5355 location.c_str(),
5356 task.mSize * _1M,
5357 task.mVariant,
5358 NULL,
5359 &geo,
5360 &geo,
5361 id.raw(),
5362 VD_OPEN_FLAGS_NORMAL,
5363 NULL,
5364 task.mVDOperationIfaces);
5365 if (RT_FAILURE(vrc))
5366 throw setError(VBOX_E_FILE_ERROR,
5367 tr("Could not create the medium storage unit '%s'%s"),
5368 location.raw(), vdError(vrc).raw());
5369
5370 size = VDGetFileSize(hdd, 0);
5371 logicalSize = VDGetSize(hdd, 0) / _1M;
5372 unsigned uImageFlags;
5373 vrc = VDGetImageFlags(hdd, 0, &uImageFlags);
5374 if (RT_SUCCESS(vrc))
5375 variant = (MediumVariant_T)uImageFlags;
5376 }
5377 catch (HRESULT aRC) { rc = aRC; }
5378
5379 VDDestroy(hdd);
5380 }
5381 catch (HRESULT aRC) { rc = aRC; }
5382
5383 if (SUCCEEDED(rc))
5384 {
5385 /* register with mVirtualBox as the last step and move to
5386 * Created state only on success (leaving an orphan file is
5387 * better than breaking media registry consistency) */
5388 bool fNeedsSaveSettings = false;
5389 AutoWriteLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
5390 rc = m->pVirtualBox->registerHardDisk(this, &fNeedsSaveSettings);
5391 treeLock.release();
5392
5393 if (fNeedsSaveSettings)
5394 {
5395 AutoWriteLock vboxlock(m->pVirtualBox COMMA_LOCKVAL_SRC_POS);
5396 m->pVirtualBox->saveSettings();
5397 }
5398 }
5399
5400 // reenter the lock before changing state
5401 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
5402
5403 if (SUCCEEDED(rc))
5404 {
5405 m->state = MediumState_Created;
5406
5407 m->size = size;
5408 m->logicalSize = logicalSize;
5409 m->variant = variant;
5410 }
5411 else
5412 {
5413 /* back to NotCreated on failure */
5414 m->state = MediumState_NotCreated;
5415
5416 /* reset UUID to prevent it from being reused next time */
5417 if (fGenerateUuid)
5418 unconst(m->id).clear();
5419 }
5420
5421 return rc;
5422}
5423
5424/**
5425 * Implementation code for the "create diff" task.
5426 *
5427 * This task always gets started from Medium::createDiffStorage() and can run
5428 * synchronously or asynchronously depending on the "wait" parameter passed to
5429 * that function. If we run synchronously, the caller expects the bool
5430 * *pfNeedsSaveSettings to be set before returning; otherwise (in asynchronous
5431 * mode), we save the settings ourselves.
5432 *
5433 * @param task
5434 * @return
5435 */
5436HRESULT Medium::taskCreateDiffHandler(Medium::CreateDiffTask &task)
5437{
5438 HRESULT rc = S_OK;
5439
5440 bool fNeedsSaveSettings = false;
5441
5442 const ComObjPtr<Medium> &pTarget = task.mTarget;
5443
5444 uint64_t size = 0, logicalSize = 0;
5445 MediumVariant_T variant = MediumVariant_Standard;
5446 bool fGenerateUuid = false;
5447
5448 try
5449 {
5450 /* Lock both in {parent,child} order. */
5451 AutoMultiWriteLock2 mediaLock(this, pTarget COMMA_LOCKVAL_SRC_POS);
5452
5453 /* The object may request a specific UUID (through a special form of
5454 * the setLocation() argument). Otherwise we have to generate it */
5455 Guid targetId = pTarget->m->id;
5456 fGenerateUuid = targetId.isEmpty();
5457 if (fGenerateUuid)
5458 {
5459 targetId.create();
5460 /* VirtualBox::registerHardDisk() will need UUID */
5461 unconst(pTarget->m->id) = targetId;
5462 }
5463
5464 Guid id = m->id;
5465
5466 Utf8Str targetFormat(pTarget->m->strFormat);
5467 Utf8Str targetLocation(pTarget->m->strLocationFull);
5468 uint64_t capabilities = m->formatObj->getCapabilities();
5469 ComAssertThrow(capabilities & VD_CAP_CREATE_DYNAMIC, E_FAIL);
5470
5471 Assert(pTarget->m->state == MediumState_Creating);
5472 Assert(m->state == MediumState_LockedRead);
5473
5474 PVBOXHDD hdd;
5475 int vrc = VDCreate(m->vdDiskIfaces, &hdd);
5476 ComAssertRCThrow(vrc, E_FAIL);
5477
5478 /* the two media are now protected by their non-default states;
5479 * unlock the media before the potentially lengthy operation */
5480 mediaLock.release();
5481
5482 try
5483 {
5484 /* Open all media in the target chain but the last. */
5485 MediumLockList::Base::const_iterator targetListBegin =
5486 task.mpMediumLockList->GetBegin();
5487 MediumLockList::Base::const_iterator targetListEnd =
5488 task.mpMediumLockList->GetEnd();
5489 for (MediumLockList::Base::const_iterator it = targetListBegin;
5490 it != targetListEnd;
5491 ++it)
5492 {
5493 const MediumLock &mediumLock = *it;
5494 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
5495
5496 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
5497
5498 /* Skip over the target diff medium */
5499 if (pMedium->m->state == MediumState_Creating)
5500 continue;
5501
5502 /* sanity check */
5503 Assert(pMedium->m->state == MediumState_LockedRead);
5504
5505 /* Open all media in appropriate mode. */
5506 vrc = VDOpen(hdd,
5507 pMedium->m->strFormat.c_str(),
5508 pMedium->m->strLocationFull.c_str(),
5509 VD_OPEN_FLAGS_READONLY,
5510 pMedium->m->vdDiskIfaces);
5511 if (RT_FAILURE(vrc))
5512 throw setError(VBOX_E_FILE_ERROR,
5513 tr("Could not open the medium storage unit '%s'%s"),
5514 pMedium->m->strLocationFull.raw(),
5515 vdError(vrc).raw());
5516 }
5517
5518 /* ensure the target directory exists */
5519 rc = VirtualBox::ensureFilePathExists(targetLocation);
5520 if (FAILED(rc))
5521 throw rc;
5522
5523 vrc = VDCreateDiff(hdd,
5524 targetFormat.c_str(),
5525 targetLocation.c_str(),
5526 task.mVariant | VD_IMAGE_FLAGS_DIFF,
5527 NULL,
5528 targetId.raw(),
5529 id.raw(),
5530 VD_OPEN_FLAGS_NORMAL,
5531 pTarget->m->vdDiskIfaces,
5532 task.mVDOperationIfaces);
5533 if (RT_FAILURE(vrc))
5534 throw setError(VBOX_E_FILE_ERROR,
5535 tr("Could not create the differencing medium storage unit '%s'%s"),
5536 targetLocation.raw(), vdError(vrc).raw());
5537
5538 size = VDGetFileSize(hdd, VD_LAST_IMAGE);
5539 logicalSize = VDGetSize(hdd, VD_LAST_IMAGE) / _1M;
5540 unsigned uImageFlags;
5541 vrc = VDGetImageFlags(hdd, 0, &uImageFlags);
5542 if (RT_SUCCESS(vrc))
5543 variant = (MediumVariant_T)uImageFlags;
5544 }
5545 catch (HRESULT aRC) { rc = aRC; }
5546
5547 VDDestroy(hdd);
5548 }
5549 catch (HRESULT aRC) { rc = aRC; }
5550
5551 if (SUCCEEDED(rc))
5552 {
5553 AutoWriteLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
5554
5555 Assert(pTarget->m->pParent.isNull());
5556
5557 /* associate the child with the parent */
5558 pTarget->m->pParent = this;
5559 m->llChildren.push_back(pTarget);
5560
5561 /** @todo r=klaus neither target nor base() are locked,
5562 * potential race! */
5563 /* diffs for immutable media are auto-reset by default */
5564 pTarget->m->autoReset = (getBase()->m->type == MediumType_Immutable);
5565
5566 /* register with mVirtualBox as the last step and move to
5567 * Created state only on success (leaving an orphan file is
5568 * better than breaking media registry consistency) */
5569 rc = m->pVirtualBox->registerHardDisk(pTarget, &fNeedsSaveSettings);
5570
5571 if (FAILED(rc))
5572 /* break the parent association on failure to register */
5573 deparent();
5574 }
5575
5576 AutoMultiWriteLock2 mediaLock(this, pTarget COMMA_LOCKVAL_SRC_POS);
5577
5578 if (SUCCEEDED(rc))
5579 {
5580 pTarget->m->state = MediumState_Created;
5581
5582 pTarget->m->size = size;
5583 pTarget->m->logicalSize = logicalSize;
5584 pTarget->m->variant = variant;
5585 }
5586 else
5587 {
5588 /* back to NotCreated on failure */
5589 pTarget->m->state = MediumState_NotCreated;
5590
5591 pTarget->m->autoReset = false;
5592
5593 /* reset UUID to prevent it from being reused next time */
5594 if (fGenerateUuid)
5595 unconst(pTarget->m->id).clear();
5596 }
5597
5598 // deregister the task registered in createDiffStorage()
5599 Assert(m->numCreateDiffTasks != 0);
5600 --m->numCreateDiffTasks;
5601
5602 if (task.isAsync())
5603 {
5604 if (fNeedsSaveSettings)
5605 {
5606 // save the global settings; for that we should hold only the VirtualBox lock
5607 mediaLock.release();
5608 AutoWriteLock vboxlock(m->pVirtualBox COMMA_LOCKVAL_SRC_POS);
5609 m->pVirtualBox->saveSettings();
5610 }
5611 }
5612 else
5613 // synchronous mode: report save settings result to caller
5614 if (task.m_pfNeedsSaveSettings)
5615 *task.m_pfNeedsSaveSettings = fNeedsSaveSettings;
5616
5617 /* Note that in sync mode, it's the caller's responsibility to
5618 * unlock the medium. */
5619
5620 return rc;
5621}
5622
5623/**
5624 * Implementation code for the "merge" task.
5625 *
5626 * This task always gets started from Medium::mergeTo() and can run
5627 * synchronously or asynchrously depending on the "wait" parameter passed to
5628 * that function. If we run synchronously, the caller expects the bool
5629 * *pfNeedsSaveSettings to be set before returning; otherwise (in asynchronous
5630 * mode), we save the settings ourselves.
5631 *
5632 * @param task
5633 * @return
5634 */
5635HRESULT Medium::taskMergeHandler(Medium::MergeTask &task)
5636{
5637 HRESULT rc = S_OK;
5638
5639 const ComObjPtr<Medium> &pTarget = task.mTarget;
5640
5641 try
5642 {
5643 PVBOXHDD hdd;
5644 int vrc = VDCreate(m->vdDiskIfaces, &hdd);
5645 ComAssertRCThrow(vrc, E_FAIL);
5646
5647 try
5648 {
5649 // Similar code appears in SessionMachine::onlineMergeMedium, so
5650 // if you make any changes below check whether they are applicable
5651 // in that context as well.
5652
5653 unsigned uTargetIdx = VD_LAST_IMAGE;
5654 unsigned uSourceIdx = VD_LAST_IMAGE;
5655 /* Open all media in the chain. */
5656 MediumLockList::Base::iterator lockListBegin =
5657 task.mpMediumLockList->GetBegin();
5658 MediumLockList::Base::iterator lockListEnd =
5659 task.mpMediumLockList->GetEnd();
5660 unsigned i = 0;
5661 for (MediumLockList::Base::iterator it = lockListBegin;
5662 it != lockListEnd;
5663 ++it)
5664 {
5665 MediumLock &mediumLock = *it;
5666 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
5667
5668 if (pMedium == this)
5669 uSourceIdx = i;
5670 else if (pMedium == pTarget)
5671 uTargetIdx = i;
5672
5673 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
5674
5675 /*
5676 * complex sanity (sane complexity)
5677 *
5678 * The current medium must be in the Deleting (medium is merged)
5679 * or LockedRead (parent medium) state if it is not the target.
5680 * If it is the target it must be in the LockedWrite state.
5681 */
5682 Assert( ( pMedium != pTarget
5683 && ( pMedium->m->state == MediumState_Deleting
5684 || pMedium->m->state == MediumState_LockedRead))
5685 || ( pMedium == pTarget
5686 && pMedium->m->state == MediumState_LockedWrite));
5687
5688 /*
5689 * Medium must be the target, in the LockedRead state
5690 * or Deleting state where it is not allowed to be attached
5691 * to a virtual machine.
5692 */
5693 Assert( pMedium == pTarget
5694 || pMedium->m->state == MediumState_LockedRead
5695 || ( pMedium->m->backRefs.size() == 0
5696 && pMedium->m->state == MediumState_Deleting));
5697 /* The source medium must be in Deleting state. */
5698 Assert( pMedium != this
5699 || pMedium->m->state == MediumState_Deleting);
5700
5701 unsigned uOpenFlags = VD_OPEN_FLAGS_NORMAL;
5702
5703 if ( pMedium->m->state == MediumState_LockedRead
5704 || pMedium->m->state == MediumState_Deleting)
5705 uOpenFlags = VD_OPEN_FLAGS_READONLY;
5706 if (pMedium->m->type == MediumType_Shareable)
5707 uOpenFlags |= VD_OPEN_FLAGS_SHAREABLE;
5708
5709 /* Open the medium */
5710 vrc = VDOpen(hdd,
5711 pMedium->m->strFormat.c_str(),
5712 pMedium->m->strLocationFull.c_str(),
5713 uOpenFlags,
5714 pMedium->m->vdDiskIfaces);
5715 if (RT_FAILURE(vrc))
5716 throw vrc;
5717
5718 i++;
5719 }
5720
5721 ComAssertThrow( uSourceIdx != VD_LAST_IMAGE
5722 && uTargetIdx != VD_LAST_IMAGE, E_FAIL);
5723
5724 vrc = VDMerge(hdd, uSourceIdx, uTargetIdx,
5725 task.mVDOperationIfaces);
5726 if (RT_FAILURE(vrc))
5727 throw vrc;
5728
5729 /* update parent UUIDs */
5730 if (!task.mfMergeForward)
5731 {
5732 /* we need to update UUIDs of all source's children
5733 * which cannot be part of the container at once so
5734 * add each one in there individually */
5735 if (task.mChildrenToReparent.size() > 0)
5736 {
5737 for (MediaList::const_iterator it = task.mChildrenToReparent.begin();
5738 it != task.mChildrenToReparent.end();
5739 ++it)
5740 {
5741 /* VD_OPEN_FLAGS_INFO since UUID is wrong yet */
5742 vrc = VDOpen(hdd,
5743 (*it)->m->strFormat.c_str(),
5744 (*it)->m->strLocationFull.c_str(),
5745 VD_OPEN_FLAGS_INFO,
5746 (*it)->m->vdDiskIfaces);
5747 if (RT_FAILURE(vrc))
5748 throw vrc;
5749
5750 vrc = VDSetParentUuid(hdd, VD_LAST_IMAGE,
5751 pTarget->m->id);
5752 if (RT_FAILURE(vrc))
5753 throw vrc;
5754
5755 vrc = VDClose(hdd, false /* fDelete */);
5756 if (RT_FAILURE(vrc))
5757 throw vrc;
5758
5759 (*it)->UnlockWrite(NULL);
5760 }
5761 }
5762 }
5763 }
5764 catch (HRESULT aRC) { rc = aRC; }
5765 catch (int aVRC)
5766 {
5767 throw setError(VBOX_E_FILE_ERROR,
5768 tr("Could not merge the medium '%s' to '%s'%s"),
5769 m->strLocationFull.raw(),
5770 pTarget->m->strLocationFull.raw(),
5771 vdError(aVRC).raw());
5772 }
5773
5774 VDDestroy(hdd);
5775 }
5776 catch (HRESULT aRC) { rc = aRC; }
5777
5778 HRESULT rc2;
5779
5780 if (SUCCEEDED(rc))
5781 {
5782 /* all media but the target were successfully deleted by
5783 * VDMerge; reparent the last one and uninitialize deleted media. */
5784
5785 AutoWriteLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
5786
5787 if (task.mfMergeForward)
5788 {
5789 /* first, unregister the target since it may become a base
5790 * medium which needs re-registration */
5791 rc2 = m->pVirtualBox->unregisterHardDisk(pTarget, NULL /*&fNeedsSaveSettings*/);
5792 AssertComRC(rc2);
5793
5794 /* then, reparent it and disconnect the deleted branch at
5795 * both ends (chain->parent() is source's parent) */
5796 pTarget->deparent();
5797 pTarget->m->pParent = task.mParentForTarget;
5798 if (pTarget->m->pParent)
5799 {
5800 pTarget->m->pParent->m->llChildren.push_back(pTarget);
5801 deparent();
5802 }
5803
5804 /* then, register again */
5805 rc2 = m->pVirtualBox->registerHardDisk(pTarget, NULL /*&fNeedsSaveSettings*/);
5806 AssertComRC(rc2);
5807 }
5808 else
5809 {
5810 Assert(pTarget->getChildren().size() == 1);
5811 Medium *targetChild = pTarget->getChildren().front();
5812
5813 /* disconnect the deleted branch at the elder end */
5814 targetChild->deparent();
5815
5816 /* reparent source's children and disconnect the deleted
5817 * branch at the younger end */
5818 if (task.mChildrenToReparent.size() > 0)
5819 {
5820 /* obey {parent,child} lock order */
5821 AutoWriteLock sourceLock(this COMMA_LOCKVAL_SRC_POS);
5822
5823 for (MediaList::const_iterator it = task.mChildrenToReparent.begin();
5824 it != task.mChildrenToReparent.end();
5825 it++)
5826 {
5827 Medium *pMedium = *it;
5828 AutoWriteLock childLock(pMedium COMMA_LOCKVAL_SRC_POS);
5829
5830 pMedium->deparent(); // removes pMedium from source
5831 pMedium->setParent(pTarget);
5832 }
5833 }
5834 }
5835
5836 /* unregister and uninitialize all media removed by the merge */
5837 MediumLockList::Base::iterator lockListBegin =
5838 task.mpMediumLockList->GetBegin();
5839 MediumLockList::Base::iterator lockListEnd =
5840 task.mpMediumLockList->GetEnd();
5841 for (MediumLockList::Base::iterator it = lockListBegin;
5842 it != lockListEnd;
5843 )
5844 {
5845 MediumLock &mediumLock = *it;
5846 /* Create a real copy of the medium pointer, as the medium
5847 * lock deletion below would invalidate the referenced object. */
5848 const ComObjPtr<Medium> pMedium = mediumLock.GetMedium();
5849
5850 /* The target and all media not merged (readonly) are skipped */
5851 if ( pMedium == pTarget
5852 || pMedium->m->state == MediumState_LockedRead)
5853 {
5854 ++it;
5855 continue;
5856 }
5857
5858 rc2 = pMedium->m->pVirtualBox->unregisterHardDisk(pMedium,
5859 NULL /*pfNeedsSaveSettings*/);
5860 AssertComRC(rc2);
5861
5862 /* now, uninitialize the deleted medium (note that
5863 * due to the Deleting state, uninit() will not touch
5864 * the parent-child relationship so we need to
5865 * uninitialize each disk individually) */
5866
5867 /* note that the operation initiator medium (which is
5868 * normally also the source medium) is a special case
5869 * -- there is one more caller added by Task to it which
5870 * we must release. Also, if we are in sync mode, the
5871 * caller may still hold an AutoCaller instance for it
5872 * and therefore we cannot uninit() it (it's therefore
5873 * the caller's responsibility) */
5874 if (pMedium == this)
5875 {
5876 Assert(getChildren().size() == 0);
5877 Assert(m->backRefs.size() == 0);
5878 task.mMediumCaller.release();
5879 }
5880
5881 /* Delete the medium lock list entry, which also releases the
5882 * caller added by MergeChain before uninit() and updates the
5883 * iterator to point to the right place. */
5884 rc2 = task.mpMediumLockList->RemoveByIterator(it);
5885 AssertComRC(rc2);
5886
5887 if (task.isAsync() || pMedium != this)
5888 pMedium->uninit();
5889 }
5890 }
5891
5892 if (task.isAsync())
5893 {
5894 // in asynchronous mode, save settings now
5895 // for that we should hold only the VirtualBox lock
5896 AutoWriteLock vboxlock(m->pVirtualBox COMMA_LOCKVAL_SRC_POS);
5897 m->pVirtualBox->saveSettings();
5898 }
5899 else
5900 // synchronous mode: report save settings result to caller
5901 if (task.m_pfNeedsSaveSettings)
5902 *task.m_pfNeedsSaveSettings = true;
5903
5904 if (FAILED(rc))
5905 {
5906 /* Here we come if either VDMerge() failed (in which case we
5907 * assume that it tried to do everything to make a further
5908 * retry possible -- e.g. not deleted intermediate media
5909 * and so on) or VirtualBox::saveSettings() failed (where we
5910 * should have the original tree but with intermediate storage
5911 * units deleted by VDMerge()). We have to only restore states
5912 * (through the MergeChain dtor) unless we are run synchronously
5913 * in which case it's the responsibility of the caller as stated
5914 * in the mergeTo() docs. The latter also implies that we
5915 * don't own the merge chain, so release it in this case. */
5916 if (task.isAsync())
5917 {
5918 Assert(task.mChildrenToReparent.size() == 0);
5919 cancelMergeTo(task.mChildrenToReparent, task.mpMediumLockList);
5920 }
5921 }
5922
5923 return rc;
5924}
5925
5926/**
5927 * Implementation code for the "clone" task.
5928 *
5929 * This only gets started from Medium::CloneTo() and always runs asynchronously.
5930 * As a result, we always save the VirtualBox.xml file when we're done here.
5931 *
5932 * @param task
5933 * @return
5934 */
5935HRESULT Medium::taskCloneHandler(Medium::CloneTask &task)
5936{
5937 HRESULT rc = S_OK;
5938
5939 const ComObjPtr<Medium> &pTarget = task.mTarget;
5940 const ComObjPtr<Medium> &pParent = task.mParent;
5941
5942 bool fCreatingTarget = false;
5943
5944 uint64_t size = 0, logicalSize = 0;
5945 MediumVariant_T variant = MediumVariant_Standard;
5946 bool fGenerateUuid = false;
5947
5948 try
5949 {
5950 /* Lock all in {parent,child} order. The lock is also used as a
5951 * signal from the task initiator (which releases it only after
5952 * RTThreadCreate()) that we can start the job. */
5953 AutoMultiWriteLock3 thisLock(this, pTarget, pParent COMMA_LOCKVAL_SRC_POS);
5954
5955 fCreatingTarget = pTarget->m->state == MediumState_Creating;
5956
5957 /* The object may request a specific UUID (through a special form of
5958 * the setLocation() argument). Otherwise we have to generate it */
5959 Guid targetId = pTarget->m->id;
5960 fGenerateUuid = targetId.isEmpty();
5961 if (fGenerateUuid)
5962 {
5963 targetId.create();
5964 /* VirtualBox::registerHardDisk() will need UUID */
5965 unconst(pTarget->m->id) = targetId;
5966 }
5967
5968 PVBOXHDD hdd;
5969 int vrc = VDCreate(m->vdDiskIfaces, &hdd);
5970 ComAssertRCThrow(vrc, E_FAIL);
5971
5972 try
5973 {
5974 /* Open all media in the source chain. */
5975 MediumLockList::Base::const_iterator sourceListBegin =
5976 task.mpSourceMediumLockList->GetBegin();
5977 MediumLockList::Base::const_iterator sourceListEnd =
5978 task.mpSourceMediumLockList->GetEnd();
5979 for (MediumLockList::Base::const_iterator it = sourceListBegin;
5980 it != sourceListEnd;
5981 ++it)
5982 {
5983 const MediumLock &mediumLock = *it;
5984 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
5985 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
5986
5987 /* sanity check */
5988 Assert(pMedium->m->state == MediumState_LockedRead);
5989
5990 /** Open all media in read-only mode. */
5991 vrc = VDOpen(hdd,
5992 pMedium->m->strFormat.c_str(),
5993 pMedium->m->strLocationFull.c_str(),
5994 VD_OPEN_FLAGS_READONLY,
5995 pMedium->m->vdDiskIfaces);
5996 if (RT_FAILURE(vrc))
5997 throw setError(VBOX_E_FILE_ERROR,
5998 tr("Could not open the medium storage unit '%s'%s"),
5999 pMedium->m->strLocationFull.raw(),
6000 vdError(vrc).raw());
6001 }
6002
6003 Utf8Str targetFormat(pTarget->m->strFormat);
6004 Utf8Str targetLocation(pTarget->m->strLocationFull);
6005
6006 Assert( pTarget->m->state == MediumState_Creating
6007 || pTarget->m->state == MediumState_LockedWrite);
6008 Assert(m->state == MediumState_LockedRead);
6009 Assert(pParent.isNull() || pParent->m->state == MediumState_LockedRead);
6010
6011 /* unlock before the potentially lengthy operation */
6012 thisLock.release();
6013
6014 /* ensure the target directory exists */
6015 rc = VirtualBox::ensureFilePathExists(targetLocation);
6016 if (FAILED(rc))
6017 throw rc;
6018
6019 PVBOXHDD targetHdd;
6020 vrc = VDCreate(m->vdDiskIfaces, &targetHdd);
6021 ComAssertRCThrow(vrc, E_FAIL);
6022
6023 try
6024 {
6025 /* Open all media in the target chain. */
6026 MediumLockList::Base::const_iterator targetListBegin =
6027 task.mpTargetMediumLockList->GetBegin();
6028 MediumLockList::Base::const_iterator targetListEnd =
6029 task.mpTargetMediumLockList->GetEnd();
6030 for (MediumLockList::Base::const_iterator it = targetListBegin;
6031 it != targetListEnd;
6032 ++it)
6033 {
6034 const MediumLock &mediumLock = *it;
6035 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
6036
6037 /* If the target medium is not created yet there's no
6038 * reason to open it. */
6039 if (pMedium == pTarget && fCreatingTarget)
6040 continue;
6041
6042 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
6043
6044 /* sanity check */
6045 Assert( pMedium->m->state == MediumState_LockedRead
6046 || pMedium->m->state == MediumState_LockedWrite);
6047
6048 unsigned uOpenFlags = VD_OPEN_FLAGS_NORMAL;
6049 if (pMedium->m->state != MediumState_LockedWrite)
6050 uOpenFlags = VD_OPEN_FLAGS_READONLY;
6051 if (pMedium->m->type == MediumType_Shareable)
6052 uOpenFlags |= VD_OPEN_FLAGS_SHAREABLE;
6053
6054 /* Open all media in appropriate mode. */
6055 vrc = VDOpen(targetHdd,
6056 pMedium->m->strFormat.c_str(),
6057 pMedium->m->strLocationFull.c_str(),
6058 uOpenFlags,
6059 pMedium->m->vdDiskIfaces);
6060 if (RT_FAILURE(vrc))
6061 throw setError(VBOX_E_FILE_ERROR,
6062 tr("Could not open the medium storage unit '%s'%s"),
6063 pMedium->m->strLocationFull.raw(),
6064 vdError(vrc).raw());
6065 }
6066
6067 /** @todo r=klaus target isn't locked, race getting the state */
6068 vrc = VDCopy(hdd,
6069 VD_LAST_IMAGE,
6070 targetHdd,
6071 targetFormat.c_str(),
6072 (fCreatingTarget) ? targetLocation.raw() : (char *)NULL,
6073 false,
6074 0,
6075 task.mVariant,
6076 targetId.raw(),
6077 NULL,
6078 pTarget->m->vdDiskIfaces,
6079 task.mVDOperationIfaces);
6080 if (RT_FAILURE(vrc))
6081 throw setError(VBOX_E_FILE_ERROR,
6082 tr("Could not create the clone medium '%s'%s"),
6083 targetLocation.raw(), vdError(vrc).raw());
6084
6085 size = VDGetFileSize(targetHdd, VD_LAST_IMAGE);
6086 logicalSize = VDGetSize(targetHdd, VD_LAST_IMAGE) / _1M;
6087 unsigned uImageFlags;
6088 vrc = VDGetImageFlags(targetHdd, 0, &uImageFlags);
6089 if (RT_SUCCESS(vrc))
6090 variant = (MediumVariant_T)uImageFlags;
6091 }
6092 catch (HRESULT aRC) { rc = aRC; }
6093
6094 VDDestroy(targetHdd);
6095 }
6096 catch (HRESULT aRC) { rc = aRC; }
6097
6098 VDDestroy(hdd);
6099 }
6100 catch (HRESULT aRC) { rc = aRC; }
6101
6102 /* Only do the parent changes for newly created media. */
6103 if (SUCCEEDED(rc) && fCreatingTarget)
6104 {
6105 /* we set mParent & children() */
6106 AutoWriteLock alock2(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
6107
6108 Assert(pTarget->m->pParent.isNull());
6109
6110 if (pParent)
6111 {
6112 /* associate the clone with the parent and deassociate
6113 * from VirtualBox */
6114 pTarget->m->pParent = pParent;
6115 pParent->m->llChildren.push_back(pTarget);
6116
6117 /* register with mVirtualBox as the last step and move to
6118 * Created state only on success (leaving an orphan file is
6119 * better than breaking media registry consistency) */
6120 rc = pParent->m->pVirtualBox->registerHardDisk(pTarget, NULL /* pfNeedsSaveSettings */);
6121
6122 if (FAILED(rc))
6123 /* break parent association on failure to register */
6124 pTarget->deparent(); // removes target from parent
6125 }
6126 else
6127 {
6128 /* just register */
6129 rc = m->pVirtualBox->registerHardDisk(pTarget, NULL /* pfNeedsSaveSettings */);
6130 }
6131 }
6132
6133 if (fCreatingTarget)
6134 {
6135 AutoWriteLock mLock(pTarget COMMA_LOCKVAL_SRC_POS);
6136
6137 if (SUCCEEDED(rc))
6138 {
6139 pTarget->m->state = MediumState_Created;
6140
6141 pTarget->m->size = size;
6142 pTarget->m->logicalSize = logicalSize;
6143 pTarget->m->variant = variant;
6144 }
6145 else
6146 {
6147 /* back to NotCreated on failure */
6148 pTarget->m->state = MediumState_NotCreated;
6149
6150 /* reset UUID to prevent it from being reused next time */
6151 if (fGenerateUuid)
6152 unconst(pTarget->m->id).clear();
6153 }
6154 }
6155
6156 // now, at the end of this task (always asynchronous), save the settings
6157 {
6158 AutoWriteLock vboxlock(m->pVirtualBox COMMA_LOCKVAL_SRC_POS);
6159 m->pVirtualBox->saveSettings();
6160 }
6161
6162 /* Everything is explicitly unlocked when the task exits,
6163 * as the task destruction also destroys the source chain. */
6164
6165 /* Make sure the source chain is released early. It could happen
6166 * that we get a deadlock in Appliance::Import when Medium::Close
6167 * is called & the source chain is released at the same time. */
6168 task.mpSourceMediumLockList->Clear();
6169
6170 return rc;
6171}
6172
6173/**
6174 * Implementation code for the "delete" task.
6175 *
6176 * This task always gets started from Medium::deleteStorage() and can run
6177 * synchronously or asynchrously depending on the "wait" parameter passed to
6178 * that function.
6179 *
6180 * @param task
6181 * @return
6182 */
6183HRESULT Medium::taskDeleteHandler(Medium::DeleteTask &task)
6184{
6185 NOREF(task);
6186 HRESULT rc = S_OK;
6187
6188 try
6189 {
6190 /* The lock is also used as a signal from the task initiator (which
6191 * releases it only after RTThreadCreate()) that we can start the job */
6192 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
6193
6194 PVBOXHDD hdd;
6195 int vrc = VDCreate(m->vdDiskIfaces, &hdd);
6196 ComAssertRCThrow(vrc, E_FAIL);
6197
6198 Utf8Str format(m->strFormat);
6199 Utf8Str location(m->strLocationFull);
6200
6201 /* unlock before the potentially lengthy operation */
6202 Assert(m->state == MediumState_Deleting);
6203 thisLock.release();
6204
6205 try
6206 {
6207 vrc = VDOpen(hdd,
6208 format.c_str(),
6209 location.c_str(),
6210 VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_INFO,
6211 m->vdDiskIfaces);
6212 if (RT_SUCCESS(vrc))
6213 vrc = VDClose(hdd, true /* fDelete */);
6214
6215 if (RT_FAILURE(vrc))
6216 throw setError(VBOX_E_FILE_ERROR,
6217 tr("Could not delete the medium storage unit '%s'%s"),
6218 location.raw(), vdError(vrc).raw());
6219
6220 }
6221 catch (HRESULT aRC) { rc = aRC; }
6222
6223 VDDestroy(hdd);
6224 }
6225 catch (HRESULT aRC) { rc = aRC; }
6226
6227 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
6228
6229 /* go to the NotCreated state even on failure since the storage
6230 * may have been already partially deleted and cannot be used any
6231 * more. One will be able to manually re-open the storage if really
6232 * needed to re-register it. */
6233 m->state = MediumState_NotCreated;
6234
6235 /* Reset UUID to prevent Create* from reusing it again */
6236 unconst(m->id).clear();
6237
6238 return rc;
6239}
6240
6241/**
6242 * Implementation code for the "reset" task.
6243 *
6244 * This always gets started asynchronously from Medium::Reset().
6245 *
6246 * @param task
6247 * @return
6248 */
6249HRESULT Medium::taskResetHandler(Medium::ResetTask &task)
6250{
6251 HRESULT rc = S_OK;
6252
6253 uint64_t size = 0, logicalSize = 0;
6254 MediumVariant_T variant = MediumVariant_Standard;
6255
6256 try
6257 {
6258 /* The lock is also used as a signal from the task initiator (which
6259 * releases it only after RTThreadCreate()) that we can start the job */
6260 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
6261
6262 /// @todo Below we use a pair of delete/create operations to reset
6263 /// the diff contents but the most efficient way will of course be
6264 /// to add a VDResetDiff() API call
6265
6266 PVBOXHDD hdd;
6267 int vrc = VDCreate(m->vdDiskIfaces, &hdd);
6268 ComAssertRCThrow(vrc, E_FAIL);
6269
6270 Guid id = m->id;
6271 Utf8Str format(m->strFormat);
6272 Utf8Str location(m->strLocationFull);
6273
6274 Medium *pParent = m->pParent;
6275 Guid parentId = pParent->m->id;
6276 Utf8Str parentFormat(pParent->m->strFormat);
6277 Utf8Str parentLocation(pParent->m->strLocationFull);
6278
6279 Assert(m->state == MediumState_LockedWrite);
6280
6281 /* unlock before the potentially lengthy operation */
6282 thisLock.release();
6283
6284 try
6285 {
6286 /* Open all media in the target chain but the last. */
6287 MediumLockList::Base::const_iterator targetListBegin =
6288 task.mpMediumLockList->GetBegin();
6289 MediumLockList::Base::const_iterator targetListEnd =
6290 task.mpMediumLockList->GetEnd();
6291 for (MediumLockList::Base::const_iterator it = targetListBegin;
6292 it != targetListEnd;
6293 ++it)
6294 {
6295 const MediumLock &mediumLock = *it;
6296 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
6297
6298 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
6299
6300 /* sanity check, "this" is checked above */
6301 Assert( pMedium == this
6302 || pMedium->m->state == MediumState_LockedRead);
6303
6304 /* Open all media in appropriate mode. */
6305 vrc = VDOpen(hdd,
6306 pMedium->m->strFormat.c_str(),
6307 pMedium->m->strLocationFull.c_str(),
6308 VD_OPEN_FLAGS_READONLY,
6309 pMedium->m->vdDiskIfaces);
6310 if (RT_FAILURE(vrc))
6311 throw setError(VBOX_E_FILE_ERROR,
6312 tr("Could not open the medium storage unit '%s'%s"),
6313 pMedium->m->strLocationFull.raw(),
6314 vdError(vrc).raw());
6315
6316 /* Done when we hit the media which should be reset */
6317 if (pMedium == this)
6318 break;
6319 }
6320
6321 /* first, delete the storage unit */
6322 vrc = VDClose(hdd, true /* fDelete */);
6323 if (RT_FAILURE(vrc))
6324 throw setError(VBOX_E_FILE_ERROR,
6325 tr("Could not delete the medium storage unit '%s'%s"),
6326 location.raw(), vdError(vrc).raw());
6327
6328 /* next, create it again */
6329 vrc = VDOpen(hdd,
6330 parentFormat.c_str(),
6331 parentLocation.c_str(),
6332 VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_INFO,
6333 m->vdDiskIfaces);
6334 if (RT_FAILURE(vrc))
6335 throw setError(VBOX_E_FILE_ERROR,
6336 tr("Could not open the medium storage unit '%s'%s"),
6337 parentLocation.raw(), vdError(vrc).raw());
6338
6339 vrc = VDCreateDiff(hdd,
6340 format.c_str(),
6341 location.c_str(),
6342 /// @todo use the same medium variant as before
6343 VD_IMAGE_FLAGS_NONE,
6344 NULL,
6345 id.raw(),
6346 parentId.raw(),
6347 VD_OPEN_FLAGS_NORMAL,
6348 m->vdDiskIfaces,
6349 task.mVDOperationIfaces);
6350 if (RT_FAILURE(vrc))
6351 throw setError(VBOX_E_FILE_ERROR,
6352 tr("Could not create the differencing medium storage unit '%s'%s"),
6353 location.raw(), vdError(vrc).raw());
6354
6355 size = VDGetFileSize(hdd, VD_LAST_IMAGE);
6356 logicalSize = VDGetSize(hdd, VD_LAST_IMAGE) / _1M;
6357 unsigned uImageFlags;
6358 vrc = VDGetImageFlags(hdd, 0, &uImageFlags);
6359 if (RT_SUCCESS(vrc))
6360 variant = (MediumVariant_T)uImageFlags;
6361 }
6362 catch (HRESULT aRC) { rc = aRC; }
6363
6364 VDDestroy(hdd);
6365 }
6366 catch (HRESULT aRC) { rc = aRC; }
6367
6368 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
6369
6370 m->size = size;
6371 m->logicalSize = logicalSize;
6372 m->variant = variant;
6373
6374 if (task.isAsync())
6375 {
6376 /* unlock ourselves when done */
6377 HRESULT rc2 = UnlockWrite(NULL);
6378 AssertComRC(rc2);
6379 }
6380
6381 /* Note that in sync mode, it's the caller's responsibility to
6382 * unlock the medium. */
6383
6384 return rc;
6385}
6386
6387/**
6388 * Implementation code for the "compact" task.
6389 *
6390 * @param task
6391 * @return
6392 */
6393HRESULT Medium::taskCompactHandler(Medium::CompactTask &task)
6394{
6395 HRESULT rc = S_OK;
6396
6397 /* Lock all in {parent,child} order. The lock is also used as a
6398 * signal from the task initiator (which releases it only after
6399 * RTThreadCreate()) that we can start the job. */
6400 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
6401
6402 try
6403 {
6404 PVBOXHDD hdd;
6405 int vrc = VDCreate(m->vdDiskIfaces, &hdd);
6406 ComAssertRCThrow(vrc, E_FAIL);
6407
6408 try
6409 {
6410 /* Open all media in the chain. */
6411 MediumLockList::Base::const_iterator mediumListBegin =
6412 task.mpMediumLockList->GetBegin();
6413 MediumLockList::Base::const_iterator mediumListEnd =
6414 task.mpMediumLockList->GetEnd();
6415 MediumLockList::Base::const_iterator mediumListLast =
6416 mediumListEnd;
6417 mediumListLast--;
6418 for (MediumLockList::Base::const_iterator it = mediumListBegin;
6419 it != mediumListEnd;
6420 ++it)
6421 {
6422 const MediumLock &mediumLock = *it;
6423 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
6424 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
6425
6426 /* sanity check */
6427 if (it == mediumListLast)
6428 Assert(pMedium->m->state == MediumState_LockedWrite);
6429 else
6430 Assert(pMedium->m->state == MediumState_LockedRead);
6431
6432 /* Open all media but last in read-only mode. Do not handle
6433 * shareable media, as compaction and sharing are mutually
6434 * exclusive. */
6435 vrc = VDOpen(hdd,
6436 pMedium->m->strFormat.c_str(),
6437 pMedium->m->strLocationFull.c_str(),
6438 (it == mediumListLast) ? VD_OPEN_FLAGS_NORMAL : VD_OPEN_FLAGS_READONLY,
6439 pMedium->m->vdDiskIfaces);
6440 if (RT_FAILURE(vrc))
6441 throw setError(VBOX_E_FILE_ERROR,
6442 tr("Could not open the medium storage unit '%s'%s"),
6443 pMedium->m->strLocationFull.raw(),
6444 vdError(vrc).raw());
6445 }
6446
6447 Assert(m->state == MediumState_LockedWrite);
6448
6449 Utf8Str location(m->strLocationFull);
6450
6451 /* unlock before the potentially lengthy operation */
6452 thisLock.release();
6453
6454 vrc = VDCompact(hdd, VD_LAST_IMAGE, task.mVDOperationIfaces);
6455 if (RT_FAILURE(vrc))
6456 {
6457 if (vrc == VERR_NOT_SUPPORTED)
6458 throw setError(VBOX_E_NOT_SUPPORTED,
6459 tr("Compacting is not yet supported for medium '%s'"),
6460 location.raw());
6461 else if (vrc == VERR_NOT_IMPLEMENTED)
6462 throw setError(E_NOTIMPL,
6463 tr("Compacting is not implemented, medium '%s'"),
6464 location.raw());
6465 else
6466 throw setError(VBOX_E_FILE_ERROR,
6467 tr("Could not compact medium '%s'%s"),
6468 location.raw(),
6469 vdError(vrc).raw());
6470 }
6471 }
6472 catch (HRESULT aRC) { rc = aRC; }
6473
6474 VDDestroy(hdd);
6475 }
6476 catch (HRESULT aRC) { rc = aRC; }
6477
6478 /* Everything is explicitly unlocked when the task exits,
6479 * as the task destruction also destroys the media chain. */
6480
6481 return rc;
6482}
6483
6484/* vi: set tabstop=4 shiftwidth=4 expandtab: */
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