VirtualBox

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

Last change on this file since 31258 was 31258, checked in by vboxsync, 15 years ago

Main/Medium+Storage/VBoxHDD: fix incorrect handling of diff media in VirtualBox::OpenHardDisk

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

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