VirtualBox

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

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

Main: use VBox error codes in IMedium

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 211.3 KB
Line 
1/* $Id: MediumImpl.cpp 31239 2010-07-30 11:58:45Z 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 if
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 /* check the type */
3621 unsigned uImageFlags;
3622 vrc = VDGetImageFlags(hdd, 0, &uImageFlags);
3623 ComAssertRCThrow(vrc, E_FAIL);
3624 m->variant = (MediumVariant_T)uImageFlags;
3625
3626 if (uImageFlags & VD_IMAGE_FLAGS_DIFF)
3627 {
3628 RTUUID parentId;
3629 vrc = VDGetParentUuid(hdd, 0, &parentId);
3630 ComAssertRCThrow(vrc, E_FAIL);
3631
3632 if (isImport)
3633 {
3634 /* the parent must be known to us. Note that we freely
3635 * call locking methods of mVirtualBox and parent, as all
3636 * relevant locks must be already held. There may be no
3637 * concurrent access to the just opened medium on other
3638 * threads yet (and init() will fail if this method reports
3639 * MediumState_Inaccessible) */
3640
3641 Guid id = parentId;
3642 ComObjPtr<Medium> pParent;
3643 rc = m->pVirtualBox->findHardDisk(&id, NULL,
3644 false /* aSetError */,
3645 &pParent);
3646 if (FAILED(rc))
3647 {
3648 lastAccessError = Utf8StrFmt(
3649 tr("Parent medium with UUID {%RTuuid} of the medium '%s' is not found in the media registry ('%s')"),
3650 &parentId, location.c_str(),
3651 m->pVirtualBox->settingsFilePath().c_str());
3652 throw S_OK;
3653 }
3654
3655 /* we set mParent & children() */
3656 AutoWriteLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
3657
3658 Assert(m->pParent.isNull());
3659 m->pParent = pParent;
3660 m->pParent->m->llChildren.push_back(this);
3661 }
3662 else
3663 {
3664 /* we access mParent */
3665 AutoReadLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
3666
3667 /* check that parent UUIDs match. Note that there's no need
3668 * for the parent's AutoCaller (our lifetime is bound to
3669 * it) */
3670
3671 if (m->pParent.isNull())
3672 {
3673 lastAccessError = Utf8StrFmt(
3674 tr("Medium type of '%s' is differencing but it is not associated with any parent medium in the media registry ('%s')"),
3675 location.c_str(),
3676 m->pVirtualBox->settingsFilePath().c_str());
3677 throw S_OK;
3678 }
3679
3680 AutoReadLock parentLock(m->pParent COMMA_LOCKVAL_SRC_POS);
3681 if ( m->pParent->getState() != MediumState_Inaccessible
3682 && m->pParent->getId() != parentId)
3683 {
3684 lastAccessError = Utf8StrFmt(
3685 tr("Parent UUID {%RTuuid} of the medium '%s' does not match UUID {%RTuuid} of its parent medium stored in the media registry ('%s')"),
3686 &parentId, location.c_str(),
3687 m->pParent->getId().raw(),
3688 m->pVirtualBox->settingsFilePath().c_str());
3689 throw S_OK;
3690 }
3691
3692 /// @todo NEWMEDIA what to do if the parent is not
3693 /// accessible while the diff is? Probably nothing. The
3694 /// real code will detect the mismatch anyway.
3695 }
3696 }
3697
3698 mediumSize = VDGetFileSize(hdd, 0);
3699 mediumLogicalSize = VDGetSize(hdd, 0) / _1M;
3700
3701 success = true;
3702 }
3703 catch (HRESULT aRC)
3704 {
3705 rc = aRC;
3706 }
3707
3708 VDDestroy(hdd);
3709
3710 }
3711 catch (HRESULT aRC)
3712 {
3713 rc = aRC;
3714 }
3715
3716 alock.enter();
3717
3718 if (isImport)
3719 unconst(m->id) = mediumId;
3720
3721 if (success)
3722 {
3723 m->size = mediumSize;
3724 m->logicalSize = mediumLogicalSize;
3725 m->strLastAccessError.setNull();
3726 }
3727 else
3728 {
3729 m->strLastAccessError = lastAccessError;
3730 LogWarningFunc(("'%s' is not accessible (error='%s', rc=%Rhrc, vrc=%Rrc)\n",
3731 location.c_str(), m->strLastAccessError.c_str(),
3732 rc, vrc));
3733 }
3734
3735 /* inform other callers if there are any */
3736 RTSemEventMultiSignal(m->queryInfoSem);
3737 m->queryInfoRunning = false;
3738
3739 /* Set the proper state according to the result of the check */
3740 if (success)
3741 m->preLockState = MediumState_Created;
3742 else
3743 m->preLockState = MediumState_Inaccessible;
3744
3745 if (uOpenFlags & (VD_OPEN_FLAGS_READONLY || VD_OPEN_FLAGS_SHAREABLE))
3746 rc = UnlockRead(NULL);
3747 else
3748 rc = UnlockWrite(NULL);
3749 if (FAILED(rc)) return rc;
3750
3751 return rc;
3752}
3753
3754/**
3755 * Sets the extended error info according to the current media state.
3756 *
3757 * @note Must be called from under this object's write or read lock.
3758 */
3759HRESULT Medium::setStateError()
3760{
3761 HRESULT rc = E_FAIL;
3762
3763 switch (m->state)
3764 {
3765 case MediumState_NotCreated:
3766 {
3767 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
3768 tr("Storage for the medium '%s' is not created"),
3769 m->strLocationFull.raw());
3770 break;
3771 }
3772 case MediumState_Created:
3773 {
3774 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
3775 tr("Storage for the medium '%s' is already created"),
3776 m->strLocationFull.raw());
3777 break;
3778 }
3779 case MediumState_LockedRead:
3780 {
3781 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
3782 tr("Medium '%s' is locked for reading by another task"),
3783 m->strLocationFull.raw());
3784 break;
3785 }
3786 case MediumState_LockedWrite:
3787 {
3788 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
3789 tr("Medium '%s' is locked for writing by another task"),
3790 m->strLocationFull.raw());
3791 break;
3792 }
3793 case MediumState_Inaccessible:
3794 {
3795 /* be in sync with Console::powerUpThread() */
3796 if (!m->strLastAccessError.isEmpty())
3797 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
3798 tr("Medium '%s' is not accessible. %s"),
3799 m->strLocationFull.raw(), m->strLastAccessError.c_str());
3800 else
3801 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
3802 tr("Medium '%s' is not accessible"),
3803 m->strLocationFull.raw());
3804 break;
3805 }
3806 case MediumState_Creating:
3807 {
3808 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
3809 tr("Storage for the medium '%s' is being created"),
3810 m->strLocationFull.raw());
3811 break;
3812 }
3813 case MediumState_Deleting:
3814 {
3815 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
3816 tr("Storage for the medium '%s' is being deleted"),
3817 m->strLocationFull.raw());
3818 break;
3819 }
3820 default:
3821 {
3822 AssertFailed();
3823 break;
3824 }
3825 }
3826
3827 return rc;
3828}
3829
3830/**
3831 * Implementation for the public Medium::Close() with the exception of calling
3832 * VirtualBox::saveSettings(), in case someone wants to call this for several
3833 * media.
3834 *
3835 * After this returns with success, uninit() has been called on the medium, and
3836 * the object is no longer usable ("not ready" state).
3837 *
3838 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
3839 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
3840 * This only works in "wait" mode; otherwise saveSettings gets called automatically by the thread that was created,
3841 * and this parameter is ignored.
3842 * @param autoCaller AutoCaller instance which must have been created on the caller's stack for this medium. This gets released here
3843 * upon which the Medium instance gets uninitialized.
3844 * @return
3845 */
3846HRESULT Medium::close(bool *pfNeedsSaveSettings, AutoCaller &autoCaller)
3847{
3848 // we're accessing parent/child and backrefs, so lock the tree first, then ourselves
3849 AutoMultiWriteLock2 multilock(&m->pVirtualBox->getMediaTreeLockHandle(),
3850 this->lockHandle()
3851 COMMA_LOCKVAL_SRC_POS);
3852
3853 bool wasCreated = true;
3854
3855 switch (m->state)
3856 {
3857 case MediumState_NotCreated:
3858 wasCreated = false;
3859 break;
3860 case MediumState_Created:
3861 case MediumState_Inaccessible:
3862 break;
3863 default:
3864 return setStateError();
3865 }
3866
3867 if (m->backRefs.size() != 0)
3868 return setError(VBOX_E_OBJECT_IN_USE,
3869 tr("Medium '%s' is attached to %d virtual machines"),
3870 m->strLocationFull.raw(), m->backRefs.size());
3871
3872 // perform extra media-dependent close checks
3873 HRESULT rc = canClose();
3874 if (FAILED(rc)) return rc;
3875
3876 if (wasCreated)
3877 {
3878 // remove from the list of known media before performing actual
3879 // uninitialization (to keep the media registry consistent on
3880 // failure to do so)
3881 rc = unregisterWithVirtualBox(pfNeedsSaveSettings);
3882 if (FAILED(rc)) return rc;
3883 }
3884
3885 // leave the AutoCaller, as otherwise uninit() will simply hang
3886 autoCaller.release();
3887
3888 // Keep the locks held until after uninit, as otherwise the consistency
3889 // of the medium tree cannot be guaranteed.
3890 uninit();
3891
3892 return rc;
3893}
3894
3895/**
3896 * Deletes the medium storage unit.
3897 *
3898 * If @a aProgress is not NULL but the object it points to is @c null then a new
3899 * progress object will be created and assigned to @a *aProgress on success,
3900 * otherwise the existing progress object is used. If Progress is NULL, then no
3901 * progress object is created/used at all.
3902 *
3903 * When @a aWait is @c false, this method will create a thread to perform the
3904 * delete operation asynchronously and will return immediately. Otherwise, it
3905 * will perform the operation on the calling thread and will not return to the
3906 * caller until the operation is completed. Note that @a aProgress cannot be
3907 * NULL when @a aWait is @c false (this method will assert in this case).
3908 *
3909 * @param aProgress Where to find/store a Progress object to track operation
3910 * completion.
3911 * @param aWait @c true if this method should block instead of creating
3912 * an asynchronous thread.
3913 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
3914 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
3915 * This only works in "wait" mode; otherwise saveSettings gets called automatically by the thread that was created,
3916 * and this parameter is ignored.
3917 *
3918 * @note Locks mVirtualBox and this object for writing. Locks medium tree for
3919 * writing.
3920 */
3921HRESULT Medium::deleteStorage(ComObjPtr<Progress> *aProgress,
3922 bool aWait,
3923 bool *pfNeedsSaveSettings)
3924{
3925 AssertReturn(aProgress != NULL || aWait == true, E_FAIL);
3926
3927 AutoCaller autoCaller(this);
3928 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3929
3930 HRESULT rc = S_OK;
3931 ComObjPtr<Progress> pProgress;
3932 Medium::Task *pTask = NULL;
3933
3934 try
3935 {
3936 /* we're accessing the media tree, and canClose() needs it too */
3937 AutoMultiWriteLock2 multilock(&m->pVirtualBox->getMediaTreeLockHandle(),
3938 this->lockHandle()
3939 COMMA_LOCKVAL_SRC_POS);
3940 LogFlowThisFunc(("aWait=%RTbool locationFull=%s\n", aWait, getLocationFull().c_str() ));
3941
3942 if ( !(m->formatObj->capabilities() & ( MediumFormatCapabilities_CreateDynamic
3943 | MediumFormatCapabilities_CreateFixed)))
3944 throw setError(VBOX_E_NOT_SUPPORTED,
3945 tr("Medium format '%s' does not support storage deletion"),
3946 m->strFormat.raw());
3947
3948 /* Note that we are fine with Inaccessible state too: a) for symmetry
3949 * with create calls and b) because it doesn't really harm to try, if
3950 * it is really inaccessible, the delete operation will fail anyway.
3951 * Accepting Inaccessible state is especially important because all
3952 * registered media are initially Inaccessible upon VBoxSVC startup
3953 * until COMGETTER(RefreshState) is called. Accept Deleting state
3954 * because some callers need to put the medium in this state early
3955 * to prevent races. */
3956 switch (m->state)
3957 {
3958 case MediumState_Created:
3959 case MediumState_Deleting:
3960 case MediumState_Inaccessible:
3961 break;
3962 default:
3963 throw setStateError();
3964 }
3965
3966 if (m->backRefs.size() != 0)
3967 {
3968 Utf8Str strMachines;
3969 for (BackRefList::const_iterator it = m->backRefs.begin();
3970 it != m->backRefs.end();
3971 ++it)
3972 {
3973 const BackRef &b = *it;
3974 if (strMachines.length())
3975 strMachines.append(", ");
3976 strMachines.append(b.machineId.toString().c_str());
3977 }
3978#ifdef DEBUG
3979 dumpBackRefs();
3980#endif
3981 throw setError(VBOX_E_OBJECT_IN_USE,
3982 tr("Cannot delete storage: medium '%s' is still attached to the following %d virtual machine(s): %s"),
3983 m->strLocationFull.c_str(),
3984 m->backRefs.size(),
3985 strMachines.c_str());
3986 }
3987
3988 rc = canClose();
3989 if (FAILED(rc))
3990 throw rc;
3991
3992 /* go to Deleting state, so that the medium is not actually locked */
3993 if (m->state != MediumState_Deleting)
3994 {
3995 rc = markForDeletion();
3996 if (FAILED(rc))
3997 throw rc;
3998 }
3999
4000 /* Build the medium lock list. */
4001 MediumLockList *pMediumLockList(new MediumLockList());
4002 rc = createMediumLockList(true /* fFailIfInaccessible */,
4003 true /* fMediumLockWrite */,
4004 NULL,
4005 *pMediumLockList);
4006 if (FAILED(rc))
4007 {
4008 delete pMediumLockList;
4009 throw rc;
4010 }
4011
4012 rc = pMediumLockList->Lock();
4013 if (FAILED(rc))
4014 {
4015 delete pMediumLockList;
4016 throw setError(rc,
4017 tr("Failed to lock media when deleting '%s'"),
4018 getLocationFull().raw());
4019 }
4020
4021 /* try to remove from the list of known media before performing
4022 * actual deletion (we favor the consistency of the media registry
4023 * which would have been broken if unregisterWithVirtualBox() failed
4024 * after we successfully deleted the storage) */
4025 rc = unregisterWithVirtualBox(pfNeedsSaveSettings);
4026 if (FAILED(rc))
4027 throw rc;
4028 // no longer need lock
4029 multilock.release();
4030
4031 if (aProgress != NULL)
4032 {
4033 /* use the existing progress object... */
4034 pProgress = *aProgress;
4035
4036 /* ...but create a new one if it is null */
4037 if (pProgress.isNull())
4038 {
4039 pProgress.createObject();
4040 rc = pProgress->init(m->pVirtualBox,
4041 static_cast<IMedium*>(this),
4042 BstrFmt(tr("Deleting medium storage unit '%s'"), m->strLocationFull.raw()),
4043 FALSE /* aCancelable */);
4044 if (FAILED(rc))
4045 throw rc;
4046 }
4047 }
4048
4049 /* setup task object to carry out the operation sync/async */
4050 pTask = new Medium::DeleteTask(this, pProgress, pMediumLockList);
4051 rc = pTask->rc();
4052 AssertComRC(rc);
4053 if (FAILED(rc))
4054 throw rc;
4055 }
4056 catch (HRESULT aRC) { rc = aRC; }
4057
4058 if (SUCCEEDED(rc))
4059 {
4060 if (aWait)
4061 rc = runNow(pTask, NULL /* pfNeedsSaveSettings*/);
4062 else
4063 rc = startThread(pTask);
4064
4065 if (SUCCEEDED(rc) && aProgress != NULL)
4066 *aProgress = pProgress;
4067
4068 }
4069 else
4070 {
4071 if (pTask)
4072 delete pTask;
4073
4074 /* Undo deleting state if necessary. */
4075 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4076 unmarkForDeletion();
4077 }
4078
4079 return rc;
4080}
4081
4082/**
4083 * Mark a medium for deletion.
4084 *
4085 * @note Caller must hold the write lock on this medium!
4086 */
4087HRESULT Medium::markForDeletion()
4088{
4089 ComAssertRet(this->lockHandle()->isWriteLockOnCurrentThread(), E_FAIL);
4090 switch (m->state)
4091 {
4092 case MediumState_Created:
4093 case MediumState_Inaccessible:
4094 m->preLockState = m->state;
4095 m->state = MediumState_Deleting;
4096 return S_OK;
4097 default:
4098 return setStateError();
4099 }
4100}
4101
4102/**
4103 * Removes the "mark for deletion".
4104 *
4105 * @note Caller must hold the write lock on this medium!
4106 */
4107HRESULT Medium::unmarkForDeletion()
4108{
4109 ComAssertRet(this->lockHandle()->isWriteLockOnCurrentThread(), E_FAIL);
4110 switch (m->state)
4111 {
4112 case MediumState_Deleting:
4113 m->state = m->preLockState;
4114 return S_OK;
4115 default:
4116 return setStateError();
4117 }
4118}
4119
4120/**
4121 * Mark a medium for deletion which is in locked state.
4122 *
4123 * @note Caller must hold the write lock on this medium!
4124 */
4125HRESULT Medium::markLockedForDeletion()
4126{
4127 ComAssertRet(this->lockHandle()->isWriteLockOnCurrentThread(), E_FAIL);
4128 if ( ( m->state == MediumState_LockedRead
4129 || m->state == MediumState_LockedWrite)
4130 && m->preLockState == MediumState_Created)
4131 {
4132 m->preLockState = MediumState_Deleting;
4133 return S_OK;
4134 }
4135 else
4136 return setStateError();
4137}
4138
4139/**
4140 * Removes the "mark for deletion" for a medium in locked state.
4141 *
4142 * @note Caller must hold the write lock on this medium!
4143 */
4144HRESULT Medium::unmarkLockedForDeletion()
4145{
4146 ComAssertRet(this->lockHandle()->isWriteLockOnCurrentThread(), E_FAIL);
4147 if ( ( m->state == MediumState_LockedRead
4148 || m->state == MediumState_LockedWrite)
4149 && m->preLockState == MediumState_Deleting)
4150 {
4151 m->preLockState = MediumState_Created;
4152 return S_OK;
4153 }
4154 else
4155 return setStateError();
4156}
4157
4158/**
4159 * Creates a new differencing storage unit using the format of the given target
4160 * medium and the location. Note that @c aTarget must be NotCreated.
4161 *
4162 * The @a aMediumLockList parameter contains the associated medium lock list,
4163 * which must be in locked state. If @a aWait is @c true then the caller is
4164 * responsible for unlocking.
4165 *
4166 * If @a aProgress is not NULL but the object it points to is @c null then a
4167 * new progress object will be created and assigned to @a *aProgress on
4168 * success, otherwise the existing progress object is used. If @a aProgress is
4169 * NULL, then no progress object is created/used at all.
4170 *
4171 * When @a aWait is @c false, this method will create a thread to perform the
4172 * create operation asynchronously and will return immediately. Otherwise, it
4173 * will perform the operation on the calling thread and will not return to the
4174 * caller until the operation is completed. Note that @a aProgress cannot be
4175 * NULL when @a aWait is @c false (this method will assert in this case).
4176 *
4177 * @param aTarget Target medium.
4178 * @param aVariant Precise medium variant to create.
4179 * @param aMediumLockList List of media which should be locked.
4180 * @param aProgress Where to find/store a Progress object to track
4181 * operation completion.
4182 * @param aWait @c true if this method should block instead of
4183 * creating an asynchronous thread.
4184 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been
4185 * initialized to false and that will be set to true
4186 * by this function if the caller should invoke
4187 * VirtualBox::saveSettings() because the global
4188 * settings have changed. This only works in "wait"
4189 * mode; otherwise saveSettings is called
4190 * automatically by the thread that was created,
4191 * and this parameter is ignored.
4192 *
4193 * @note Locks this object and @a aTarget for writing.
4194 */
4195HRESULT Medium::createDiffStorage(ComObjPtr<Medium> &aTarget,
4196 MediumVariant_T aVariant,
4197 MediumLockList *aMediumLockList,
4198 ComObjPtr<Progress> *aProgress,
4199 bool aWait,
4200 bool *pfNeedsSaveSettings)
4201{
4202 AssertReturn(!aTarget.isNull(), E_FAIL);
4203 AssertReturn(aMediumLockList, E_FAIL);
4204 AssertReturn(aProgress != NULL || aWait == true, E_FAIL);
4205
4206 AutoCaller autoCaller(this);
4207 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4208
4209 AutoCaller targetCaller(aTarget);
4210 if (FAILED(targetCaller.rc())) return targetCaller.rc();
4211
4212 HRESULT rc = S_OK;
4213 ComObjPtr<Progress> pProgress;
4214 Medium::Task *pTask = NULL;
4215
4216 try
4217 {
4218 AutoMultiWriteLock2 alock(this, aTarget COMMA_LOCKVAL_SRC_POS);
4219
4220 ComAssertThrow( m->type != MediumType_Writethrough
4221 && m->type != MediumType_Shareable, E_FAIL);
4222 ComAssertThrow(m->state == MediumState_LockedRead, E_FAIL);
4223
4224 if (aTarget->m->state != MediumState_NotCreated)
4225 throw aTarget->setStateError();
4226
4227 /* Check that the medium is not attached to the current state of
4228 * any VM referring to it. */
4229 for (BackRefList::const_iterator it = m->backRefs.begin();
4230 it != m->backRefs.end();
4231 ++it)
4232 {
4233 if (it->fInCurState)
4234 {
4235 /* Note: when a VM snapshot is being taken, all normal media
4236 * attached to the VM in the current state will be, as an
4237 * exception, also associated with the snapshot which is about
4238 * to create (see SnapshotMachine::init()) before deassociating
4239 * them from the current state (which takes place only on
4240 * success in Machine::fixupHardDisks()), so that the size of
4241 * snapshotIds will be 1 in this case. The extra condition is
4242 * used to filter out this legal situation. */
4243 if (it->llSnapshotIds.size() == 0)
4244 throw setError(VBOX_E_INVALID_OBJECT_STATE,
4245 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"),
4246 m->strLocationFull.raw(), it->machineId.raw());
4247
4248 Assert(it->llSnapshotIds.size() == 1);
4249 }
4250 }
4251
4252 if (aProgress != NULL)
4253 {
4254 /* use the existing progress object... */
4255 pProgress = *aProgress;
4256
4257 /* ...but create a new one if it is null */
4258 if (pProgress.isNull())
4259 {
4260 pProgress.createObject();
4261 rc = pProgress->init(m->pVirtualBox,
4262 static_cast<IMedium*>(this),
4263 BstrFmt(tr("Creating differencing medium storage unit '%s'"), aTarget->m->strLocationFull.raw()),
4264 TRUE /* aCancelable */);
4265 if (FAILED(rc))
4266 throw rc;
4267 }
4268 }
4269
4270 /* setup task object to carry out the operation sync/async */
4271 pTask = new Medium::CreateDiffTask(this, pProgress, aTarget, aVariant,
4272 aMediumLockList,
4273 aWait /* fKeepMediumLockList */);
4274 rc = pTask->rc();
4275 AssertComRC(rc);
4276 if (FAILED(rc))
4277 throw rc;
4278
4279 /* register a task (it will deregister itself when done) */
4280 ++m->numCreateDiffTasks;
4281 Assert(m->numCreateDiffTasks != 0); /* overflow? */
4282
4283 aTarget->m->state = MediumState_Creating;
4284 }
4285 catch (HRESULT aRC) { rc = aRC; }
4286
4287 if (SUCCEEDED(rc))
4288 {
4289 if (aWait)
4290 rc = runNow(pTask, pfNeedsSaveSettings);
4291 else
4292 rc = startThread(pTask);
4293
4294 if (SUCCEEDED(rc) && aProgress != NULL)
4295 *aProgress = pProgress;
4296 }
4297 else if (pTask != NULL)
4298 delete pTask;
4299
4300 return rc;
4301}
4302
4303/**
4304 * Prepares this (source) medium, target medium and all intermediate media
4305 * for the merge operation.
4306 *
4307 * This method is to be called prior to calling the #mergeTo() to perform
4308 * necessary consistency checks and place involved media to appropriate
4309 * states. If #mergeTo() is not called or fails, the state modifications
4310 * performed by this method must be undone by #cancelMergeTo().
4311 *
4312 * See #mergeTo() for more information about merging.
4313 *
4314 * @param pTarget Target medium.
4315 * @param aMachineId Allowed machine attachment. NULL means do not check.
4316 * @param aSnapshotId Allowed snapshot attachment. NULL or empty UUID means
4317 * do not check.
4318 * @param fLockMedia Flag whether to lock the medium lock list or not.
4319 * If set to false and the medium lock list locking fails
4320 * later you must call #cancelMergeTo().
4321 * @param fMergeForward Resulting merge direction (out).
4322 * @param pParentForTarget New parent for target medium after merge (out).
4323 * @param aChildrenToReparent List of children of the source which will have
4324 * to be reparented to the target after merge (out).
4325 * @param aMediumLockList Medium locking information (out).
4326 *
4327 * @note Locks medium tree for reading. Locks this object, aTarget and all
4328 * intermediate media for writing.
4329 */
4330HRESULT Medium::prepareMergeTo(const ComObjPtr<Medium> &pTarget,
4331 const Guid *aMachineId,
4332 const Guid *aSnapshotId,
4333 bool fLockMedia,
4334 bool &fMergeForward,
4335 ComObjPtr<Medium> &pParentForTarget,
4336 MediaList &aChildrenToReparent,
4337 MediumLockList * &aMediumLockList)
4338{
4339 AssertReturn(pTarget != NULL, E_FAIL);
4340 AssertReturn(pTarget != this, E_FAIL);
4341
4342 AutoCaller autoCaller(this);
4343 AssertComRCReturnRC(autoCaller.rc());
4344
4345 AutoCaller targetCaller(pTarget);
4346 AssertComRCReturnRC(targetCaller.rc());
4347
4348 HRESULT rc = S_OK;
4349 fMergeForward = false;
4350 pParentForTarget.setNull();
4351 aChildrenToReparent.clear();
4352 Assert(aMediumLockList == NULL);
4353 aMediumLockList = NULL;
4354
4355 try
4356 {
4357 // locking: we need the tree lock first because we access parent pointers
4358 AutoReadLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
4359
4360 /* more sanity checking and figuring out the merge direction */
4361 ComObjPtr<Medium> pMedium = getParent();
4362 while (!pMedium.isNull() && pMedium != pTarget)
4363 pMedium = pMedium->getParent();
4364 if (pMedium == pTarget)
4365 fMergeForward = false;
4366 else
4367 {
4368 pMedium = pTarget->getParent();
4369 while (!pMedium.isNull() && pMedium != this)
4370 pMedium = pMedium->getParent();
4371 if (pMedium == this)
4372 fMergeForward = true;
4373 else
4374 {
4375 Utf8Str tgtLoc;
4376 {
4377 AutoReadLock alock(pTarget COMMA_LOCKVAL_SRC_POS);
4378 tgtLoc = pTarget->getLocationFull();
4379 }
4380
4381 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4382 throw setError(VBOX_E_INVALID_OBJECT_STATE,
4383 tr("Media '%s' and '%s' are unrelated"),
4384 m->strLocationFull.raw(), tgtLoc.raw());
4385 }
4386 }
4387
4388 /* Build the lock list. */
4389 aMediumLockList = new MediumLockList();
4390 if (fMergeForward)
4391 rc = pTarget->createMediumLockList(true /* fFailIfInaccessible */,
4392 true /* fMediumLockWrite */,
4393 NULL,
4394 *aMediumLockList);
4395 else
4396 rc = createMediumLockList(true /* fFailIfInaccessible */,
4397 false /* fMediumLockWrite */,
4398 NULL,
4399 *aMediumLockList);
4400 if (FAILED(rc))
4401 throw rc;
4402
4403 /* Sanity checking, must be after lock list creation as it depends on
4404 * valid medium states. The medium objects must be accessible. Only
4405 * do this if immediate locking is requested, otherwise it fails when
4406 * we construct a medium lock list for an already running VM. Snapshot
4407 * deletion uses this to simplify its life. */
4408 if (fLockMedia)
4409 {
4410 {
4411 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4412 if (m->state != MediumState_Created)
4413 throw setStateError();
4414 }
4415 {
4416 AutoReadLock alock(pTarget COMMA_LOCKVAL_SRC_POS);
4417 if (pTarget->m->state != MediumState_Created)
4418 throw pTarget->setStateError();
4419 }
4420 }
4421
4422 /* check medium attachment and other sanity conditions */
4423 if (fMergeForward)
4424 {
4425 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4426 if (getChildren().size() > 1)
4427 {
4428 throw setError(VBOX_E_INVALID_OBJECT_STATE,
4429 tr("Medium '%s' involved in the merge operation has more than one child medium (%d)"),
4430 m->strLocationFull.raw(), getChildren().size());
4431 }
4432 /* One backreference is only allowed if the machine ID is not empty
4433 * and it matches the machine the medium is attached to (including
4434 * the snapshot ID if not empty). */
4435 if ( m->backRefs.size() != 0
4436 && ( !aMachineId
4437 || m->backRefs.size() != 1
4438 || aMachineId->isEmpty()
4439 || *getFirstMachineBackrefId() != *aMachineId
4440 || ( (!aSnapshotId || !aSnapshotId->isEmpty())
4441 && *getFirstMachineBackrefSnapshotId() != *aSnapshotId)))
4442 throw setError(VBOX_E_OBJECT_IN_USE,
4443 tr("Medium '%s' is attached to %d virtual machines"),
4444 m->strLocationFull.raw(), m->backRefs.size());
4445 if (m->type == MediumType_Immutable)
4446 throw setError(VBOX_E_INVALID_OBJECT_STATE,
4447 tr("Medium '%s' is immutable"),
4448 m->strLocationFull.raw());
4449 }
4450 else
4451 {
4452 AutoReadLock alock(pTarget COMMA_LOCKVAL_SRC_POS);
4453 if (pTarget->getChildren().size() > 1)
4454 {
4455 throw setError(VBOX_E_OBJECT_IN_USE,
4456 tr("Medium '%s' involved in the merge operation has more than one child medium (%d)"),
4457 pTarget->m->strLocationFull.raw(),
4458 pTarget->getChildren().size());
4459 }
4460 if (pTarget->m->type == MediumType_Immutable)
4461 throw setError(VBOX_E_INVALID_OBJECT_STATE,
4462 tr("Medium '%s' is immutable"),
4463 pTarget->m->strLocationFull.raw());
4464 }
4465 ComObjPtr<Medium> pLast(fMergeForward ? (Medium *)pTarget : this);
4466 ComObjPtr<Medium> pLastIntermediate = pLast->getParent();
4467 for (pLast = pLastIntermediate;
4468 !pLast.isNull() && pLast != pTarget && pLast != this;
4469 pLast = pLast->getParent())
4470 {
4471 AutoReadLock alock(pLast COMMA_LOCKVAL_SRC_POS);
4472 if (pLast->getChildren().size() > 1)
4473 {
4474 throw setError(VBOX_E_OBJECT_IN_USE,
4475 tr("Medium '%s' involved in the merge operation has more than one child medium (%d)"),
4476 pLast->m->strLocationFull.raw(),
4477 pLast->getChildren().size());
4478 }
4479 if (pLast->m->backRefs.size() != 0)
4480 throw setError(VBOX_E_OBJECT_IN_USE,
4481 tr("Medium '%s' is attached to %d virtual machines"),
4482 pLast->m->strLocationFull.raw(),
4483 pLast->m->backRefs.size());
4484
4485 }
4486
4487 /* Update medium states appropriately */
4488 if (m->state == MediumState_Created)
4489 {
4490 rc = markForDeletion();
4491 if (FAILED(rc))
4492 throw rc;
4493 }
4494 else
4495 {
4496 if (fLockMedia)
4497 throw setStateError();
4498 else if ( m->state == MediumState_LockedWrite
4499 || m->state == MediumState_LockedRead)
4500 {
4501 /* Either mark it for deletiion in locked state or allow
4502 * others to have done so. */
4503 if (m->preLockState == MediumState_Created)
4504 markLockedForDeletion();
4505 else if (m->preLockState != MediumState_Deleting)
4506 throw setStateError();
4507 }
4508 else
4509 throw setStateError();
4510 }
4511
4512 if (fMergeForward)
4513 {
4514 /* we will need parent to reparent target */
4515 pParentForTarget = m->pParent;
4516 }
4517 else
4518 {
4519 /* we will need to reparent children of the source */
4520 for (MediaList::const_iterator it = getChildren().begin();
4521 it != getChildren().end();
4522 ++it)
4523 {
4524 pMedium = *it;
4525 if (fLockMedia)
4526 {
4527 rc = pMedium->LockWrite(NULL);
4528 if (FAILED(rc))
4529 throw rc;
4530 }
4531
4532 aChildrenToReparent.push_back(pMedium);
4533 }
4534 }
4535 for (pLast = pLastIntermediate;
4536 !pLast.isNull() && pLast != pTarget && pLast != this;
4537 pLast = pLast->getParent())
4538 {
4539 AutoWriteLock alock(pLast COMMA_LOCKVAL_SRC_POS);
4540 if (pLast->m->state == MediumState_Created)
4541 {
4542 rc = pLast->markForDeletion();
4543 if (FAILED(rc))
4544 throw rc;
4545 }
4546 else
4547 throw pLast->setStateError();
4548 }
4549
4550 /* Tweak the lock list in the backward merge case, as the target
4551 * isn't marked to be locked for writing yet. */
4552 if (!fMergeForward)
4553 {
4554 MediumLockList::Base::iterator lockListBegin =
4555 aMediumLockList->GetBegin();
4556 MediumLockList::Base::iterator lockListEnd =
4557 aMediumLockList->GetEnd();
4558 lockListEnd--;
4559 for (MediumLockList::Base::iterator it = lockListBegin;
4560 it != lockListEnd;
4561 ++it)
4562 {
4563 MediumLock &mediumLock = *it;
4564 if (mediumLock.GetMedium() == pTarget)
4565 {
4566 HRESULT rc2 = mediumLock.UpdateLock(true);
4567 AssertComRC(rc2);
4568 break;
4569 }
4570 }
4571 }
4572
4573 if (fLockMedia)
4574 {
4575 rc = aMediumLockList->Lock();
4576 if (FAILED(rc))
4577 {
4578 AutoReadLock alock(pTarget COMMA_LOCKVAL_SRC_POS);
4579 throw setError(rc,
4580 tr("Failed to lock media when merging to '%s'"),
4581 pTarget->getLocationFull().raw());
4582 }
4583 }
4584 }
4585 catch (HRESULT aRC) { rc = aRC; }
4586
4587 if (FAILED(rc))
4588 {
4589 delete aMediumLockList;
4590 aMediumLockList = NULL;
4591 }
4592
4593 return rc;
4594}
4595
4596/**
4597 * Merges this medium to the specified medium which must be either its
4598 * direct ancestor or descendant.
4599 *
4600 * Given this medium is SOURCE and the specified medium is TARGET, we will
4601 * get two varians of the merge operation:
4602 *
4603 * forward merge
4604 * ------------------------->
4605 * [Extra] <- SOURCE <- Intermediate <- TARGET
4606 * Any Del Del LockWr
4607 *
4608 *
4609 * backward merge
4610 * <-------------------------
4611 * TARGET <- Intermediate <- SOURCE <- [Extra]
4612 * LockWr Del Del LockWr
4613 *
4614 * Each diagram shows the involved media on the media chain where
4615 * SOURCE and TARGET belong. Under each medium there is a state value which
4616 * the medium must have at a time of the mergeTo() call.
4617 *
4618 * The media in the square braces may be absent (e.g. when the forward
4619 * operation takes place and SOURCE is the base medium, or when the backward
4620 * merge operation takes place and TARGET is the last child in the chain) but if
4621 * they present they are involved too as shown.
4622 *
4623 * Neither the source medium nor intermediate media may be attached to
4624 * any VM directly or in the snapshot, otherwise this method will assert.
4625 *
4626 * The #prepareMergeTo() method must be called prior to this method to place all
4627 * involved to necessary states and perform other consistency checks.
4628 *
4629 * If @a aWait is @c true then this method will perform the operation on the
4630 * calling thread and will not return to the caller until the operation is
4631 * completed. When this method succeeds, all intermediate medium objects in
4632 * the chain will be uninitialized, the state of the target medium (and all
4633 * involved extra media) will be restored. @a aMediumLockList will not be
4634 * deleted, whether the operation is successful or not. The caller has to do
4635 * this if appropriate. Note that this (source) medium is not uninitialized
4636 * because of possible AutoCaller instances held by the caller of this method
4637 * on the current thread. It's therefore the responsibility of the caller to
4638 * call Medium::uninit() after releasing all callers.
4639 *
4640 * If @a aWait is @c false then this method will create a thread to perform the
4641 * operation asynchronously and will return immediately. If the operation
4642 * succeeds, the thread will uninitialize the source medium object and all
4643 * intermediate medium objects in the chain, reset the state of the target
4644 * medium (and all involved extra media) and delete @a aMediumLockList.
4645 * If the operation fails, the thread will only reset the states of all
4646 * involved media and delete @a aMediumLockList.
4647 *
4648 * When this method fails (regardless of the @a aWait mode), it is a caller's
4649 * responsiblity to undo state changes and delete @a aMediumLockList using
4650 * #cancelMergeTo().
4651 *
4652 * If @a aProgress is not NULL but the object it points to is @c null then a new
4653 * progress object will be created and assigned to @a *aProgress on success,
4654 * otherwise the existing progress object is used. If Progress is NULL, then no
4655 * progress object is created/used at all. Note that @a aProgress cannot be
4656 * NULL when @a aWait is @c false (this method will assert in this case).
4657 *
4658 * @param pTarget Target medium.
4659 * @param fMergeForward Merge direction.
4660 * @param pParentForTarget New parent for target medium after merge.
4661 * @param aChildrenToReparent List of children of the source which will have
4662 * to be reparented to the target after merge.
4663 * @param aMediumLockList Medium locking information.
4664 * @param aProgress Where to find/store a Progress object to track operation
4665 * completion.
4666 * @param aWait @c true if this method should block instead of creating
4667 * an asynchronous thread.
4668 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
4669 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
4670 * This only works in "wait" mode; otherwise saveSettings gets called automatically by the thread that was created,
4671 * and this parameter is ignored.
4672 *
4673 * @note Locks the tree lock for writing. Locks the media from the chain
4674 * for writing.
4675 */
4676HRESULT Medium::mergeTo(const ComObjPtr<Medium> &pTarget,
4677 bool fMergeForward,
4678 const ComObjPtr<Medium> &pParentForTarget,
4679 const MediaList &aChildrenToReparent,
4680 MediumLockList *aMediumLockList,
4681 ComObjPtr <Progress> *aProgress,
4682 bool aWait,
4683 bool *pfNeedsSaveSettings)
4684{
4685 AssertReturn(pTarget != NULL, E_FAIL);
4686 AssertReturn(pTarget != this, E_FAIL);
4687 AssertReturn(aMediumLockList != NULL, E_FAIL);
4688 AssertReturn(aProgress != NULL || aWait == true, E_FAIL);
4689
4690 AutoCaller autoCaller(this);
4691 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4692
4693 AutoCaller targetCaller(pTarget);
4694 AssertComRCReturnRC(targetCaller.rc());
4695
4696 HRESULT rc = S_OK;
4697 ComObjPtr <Progress> pProgress;
4698 Medium::Task *pTask = NULL;
4699
4700 try
4701 {
4702 if (aProgress != NULL)
4703 {
4704 /* use the existing progress object... */
4705 pProgress = *aProgress;
4706
4707 /* ...but create a new one if it is null */
4708 if (pProgress.isNull())
4709 {
4710 Utf8Str tgtName;
4711 {
4712 AutoReadLock alock(pTarget COMMA_LOCKVAL_SRC_POS);
4713 tgtName = pTarget->getName();
4714 }
4715
4716 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4717
4718 pProgress.createObject();
4719 rc = pProgress->init(m->pVirtualBox,
4720 static_cast<IMedium*>(this),
4721 BstrFmt(tr("Merging medium '%s' to '%s'"),
4722 getName().raw(),
4723 tgtName.raw()),
4724 TRUE /* aCancelable */);
4725 if (FAILED(rc))
4726 throw rc;
4727 }
4728 }
4729
4730 /* setup task object to carry out the operation sync/async */
4731 pTask = new Medium::MergeTask(this, pTarget, fMergeForward,
4732 pParentForTarget, aChildrenToReparent,
4733 pProgress, aMediumLockList,
4734 aWait /* fKeepMediumLockList */);
4735 rc = pTask->rc();
4736 AssertComRC(rc);
4737 if (FAILED(rc))
4738 throw rc;
4739 }
4740 catch (HRESULT aRC) { rc = aRC; }
4741
4742 if (SUCCEEDED(rc))
4743 {
4744 if (aWait)
4745 rc = runNow(pTask, pfNeedsSaveSettings);
4746 else
4747 rc = startThread(pTask);
4748
4749 if (SUCCEEDED(rc) && aProgress != NULL)
4750 *aProgress = pProgress;
4751 }
4752 else if (pTask != NULL)
4753 delete pTask;
4754
4755 return rc;
4756}
4757
4758/**
4759 * Undoes what #prepareMergeTo() did. Must be called if #mergeTo() is not
4760 * called or fails. Frees memory occupied by @a aMediumLockList and unlocks
4761 * the medium objects in @a aChildrenToReparent.
4762 *
4763 * @param aChildrenToReparent List of children of the source which will have
4764 * to be reparented to the target after merge.
4765 * @param aMediumLockList Medium locking information.
4766 *
4767 * @note Locks the media from the chain for writing.
4768 */
4769void Medium::cancelMergeTo(const MediaList &aChildrenToReparent,
4770 MediumLockList *aMediumLockList)
4771{
4772 AutoCaller autoCaller(this);
4773 AssertComRCReturnVoid(autoCaller.rc());
4774
4775 AssertReturnVoid(aMediumLockList != NULL);
4776
4777 /* Revert media marked for deletion to previous state. */
4778 HRESULT rc;
4779 MediumLockList::Base::const_iterator mediumListBegin =
4780 aMediumLockList->GetBegin();
4781 MediumLockList::Base::const_iterator mediumListEnd =
4782 aMediumLockList->GetEnd();
4783 for (MediumLockList::Base::const_iterator it = mediumListBegin;
4784 it != mediumListEnd;
4785 ++it)
4786 {
4787 const MediumLock &mediumLock = *it;
4788 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
4789 AutoWriteLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
4790
4791 if (pMedium->m->state == MediumState_Deleting)
4792 {
4793 rc = pMedium->unmarkForDeletion();
4794 AssertComRC(rc);
4795 }
4796 }
4797
4798 /* the destructor will do the work */
4799 delete aMediumLockList;
4800
4801 /* unlock the children which had to be reparented */
4802 for (MediaList::const_iterator it = aChildrenToReparent.begin();
4803 it != aChildrenToReparent.end();
4804 ++it)
4805 {
4806 const ComObjPtr<Medium> &pMedium = *it;
4807
4808 AutoWriteLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
4809 pMedium->UnlockWrite(NULL);
4810 }
4811}
4812
4813/**
4814 * Checks that the format ID is valid and sets it on success.
4815 *
4816 * Note that this method will caller-reference the format object on success!
4817 * This reference must be released somewhere to let the MediumFormat object be
4818 * uninitialized.
4819 *
4820 * @note Must be called from under this object's write lock.
4821 */
4822HRESULT Medium::setFormat(CBSTR aFormat)
4823{
4824 /* get the format object first */
4825 {
4826 AutoReadLock propsLock(m->pVirtualBox->systemProperties() COMMA_LOCKVAL_SRC_POS);
4827
4828 unconst(m->formatObj)
4829 = m->pVirtualBox->systemProperties()->mediumFormat(aFormat);
4830 if (m->formatObj.isNull())
4831 return setError(E_INVALIDARG,
4832 tr("Invalid medium storage format '%ls'"),
4833 aFormat);
4834
4835 /* reference the format permanently to prevent its unexpected
4836 * uninitialization */
4837 HRESULT rc = m->formatObj->addCaller();
4838 AssertComRCReturnRC(rc);
4839
4840 /* get properties (preinsert them as keys in the map). Note that the
4841 * map doesn't grow over the object life time since the set of
4842 * properties is meant to be constant. */
4843
4844 Assert(m->properties.empty());
4845
4846 for (MediumFormat::PropertyList::const_iterator it =
4847 m->formatObj->properties().begin();
4848 it != m->formatObj->properties().end();
4849 ++it)
4850 {
4851 m->properties.insert(std::make_pair(it->name, Bstr::Null));
4852 }
4853 }
4854
4855 unconst(m->strFormat) = aFormat;
4856
4857 return S_OK;
4858}
4859
4860/**
4861 * Performs extra checks if the medium can be closed and returns S_OK in
4862 * this case. Otherwise, returns a respective error message. Called by
4863 * Close() under the medium tree lock and the medium lock.
4864 *
4865 * @note Also reused by Medium::Reset().
4866 *
4867 * @note Caller must hold the media tree write lock!
4868 */
4869HRESULT Medium::canClose()
4870{
4871 Assert(m->pVirtualBox->getMediaTreeLockHandle().isWriteLockOnCurrentThread());
4872
4873 if (getChildren().size() != 0)
4874 return setError(VBOX_E_OBJECT_IN_USE,
4875 tr("Cannot close medium '%s' because it has %d child media"),
4876 m->strLocationFull.raw(), getChildren().size());
4877
4878 return S_OK;
4879}
4880
4881/**
4882 * Unregisters this medium with mVirtualBox. Called by close() under the medium tree lock.
4883 *
4884 * This calls either VirtualBox::unregisterImage or VirtualBox::unregisterHardDisk depending
4885 * on the device type of this medium.
4886 *
4887 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
4888 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
4889 *
4890 * @note Caller must have locked the media tree lock for writing!
4891 */
4892HRESULT Medium::unregisterWithVirtualBox(bool *pfNeedsSaveSettings)
4893{
4894 /* Note that we need to de-associate ourselves from the parent to let
4895 * unregisterHardDisk() properly save the registry */
4896
4897 /* we modify mParent and access children */
4898 Assert(m->pVirtualBox->getMediaTreeLockHandle().isWriteLockOnCurrentThread());
4899
4900 Medium *pParentBackup = m->pParent;
4901 AssertReturn(getChildren().size() == 0, E_FAIL);
4902 if (m->pParent)
4903 deparent();
4904
4905 HRESULT rc = E_FAIL;
4906 switch (m->devType)
4907 {
4908 case DeviceType_DVD:
4909 rc = m->pVirtualBox->unregisterImage(this, DeviceType_DVD, pfNeedsSaveSettings);
4910 break;
4911
4912 case DeviceType_Floppy:
4913 rc = m->pVirtualBox->unregisterImage(this, DeviceType_Floppy, pfNeedsSaveSettings);
4914 break;
4915
4916 case DeviceType_HardDisk:
4917 rc = m->pVirtualBox->unregisterHardDisk(this, pfNeedsSaveSettings);
4918 break;
4919
4920 default:
4921 break;
4922 }
4923
4924 if (FAILED(rc))
4925 {
4926 if (pParentBackup)
4927 {
4928 // re-associate with the parent as we are still relatives in the registry
4929 m->pParent = pParentBackup;
4930 m->pParent->m->llChildren.push_back(this);
4931 }
4932 }
4933
4934 return rc;
4935}
4936
4937/**
4938 * Returns the last error message collected by the vdErrorCall callback and
4939 * resets it.
4940 *
4941 * The error message is returned prepended with a dot and a space, like this:
4942 * <code>
4943 * ". <error_text> (%Rrc)"
4944 * </code>
4945 * to make it easily appendable to a more general error message. The @c %Rrc
4946 * format string is given @a aVRC as an argument.
4947 *
4948 * If there is no last error message collected by vdErrorCall or if it is a
4949 * null or empty string, then this function returns the following text:
4950 * <code>
4951 * " (%Rrc)"
4952 * </code>
4953 *
4954 * @note Doesn't do any object locking; it is assumed that the caller makes sure
4955 * the callback isn't called by more than one thread at a time.
4956 *
4957 * @param aVRC VBox error code to use when no error message is provided.
4958 */
4959Utf8Str Medium::vdError(int aVRC)
4960{
4961 Utf8Str error;
4962
4963 if (m->vdError.isEmpty())
4964 error = Utf8StrFmt(" (%Rrc)", aVRC);
4965 else
4966 error = Utf8StrFmt(".\n%s", m->vdError.raw());
4967
4968 m->vdError.setNull();
4969
4970 return error;
4971}
4972
4973/**
4974 * Error message callback.
4975 *
4976 * Puts the reported error message to the m->vdError field.
4977 *
4978 * @note Doesn't do any object locking; it is assumed that the caller makes sure
4979 * the callback isn't called by more than one thread at a time.
4980 *
4981 * @param pvUser The opaque data passed on container creation.
4982 * @param rc The VBox error code.
4983 * @param RT_SRC_POS_DECL Use RT_SRC_POS.
4984 * @param pszFormat Error message format string.
4985 * @param va Error message arguments.
4986 */
4987/*static*/
4988DECLCALLBACK(void) Medium::vdErrorCall(void *pvUser, int rc, RT_SRC_POS_DECL,
4989 const char *pszFormat, va_list va)
4990{
4991 NOREF(pszFile); NOREF(iLine); NOREF(pszFunction); /* RT_SRC_POS_DECL */
4992
4993 Medium *that = static_cast<Medium*>(pvUser);
4994 AssertReturnVoid(that != NULL);
4995
4996 if (that->m->vdError.isEmpty())
4997 that->m->vdError =
4998 Utf8StrFmt("%s (%Rrc)", Utf8StrFmtVA(pszFormat, va).raw(), rc);
4999 else
5000 that->m->vdError =
5001 Utf8StrFmt("%s.\n%s (%Rrc)", that->m->vdError.raw(),
5002 Utf8StrFmtVA(pszFormat, va).raw(), rc);
5003}
5004
5005/* static */
5006DECLCALLBACK(bool) Medium::vdConfigAreKeysValid(void *pvUser,
5007 const char * /* pszzValid */)
5008{
5009 Medium *that = static_cast<Medium*>(pvUser);
5010 AssertReturn(that != NULL, false);
5011
5012 /* we always return true since the only keys we have are those found in
5013 * VDBACKENDINFO */
5014 return true;
5015}
5016
5017/* static */
5018DECLCALLBACK(int) Medium::vdConfigQuerySize(void *pvUser, const char *pszName,
5019 size_t *pcbValue)
5020{
5021 AssertReturn(VALID_PTR(pcbValue), VERR_INVALID_POINTER);
5022
5023 Medium *that = static_cast<Medium*>(pvUser);
5024 AssertReturn(that != NULL, VERR_GENERAL_FAILURE);
5025
5026 Data::PropertyMap::const_iterator it =
5027 that->m->properties.find(Bstr(pszName));
5028 if (it == that->m->properties.end())
5029 return VERR_CFGM_VALUE_NOT_FOUND;
5030
5031 /* we interpret null values as "no value" in Medium */
5032 if (it->second.isEmpty())
5033 return VERR_CFGM_VALUE_NOT_FOUND;
5034
5035 *pcbValue = it->second.length() + 1 /* include terminator */;
5036
5037 return VINF_SUCCESS;
5038}
5039
5040/* static */
5041DECLCALLBACK(int) Medium::vdConfigQuery(void *pvUser, const char *pszName,
5042 char *pszValue, size_t cchValue)
5043{
5044 AssertReturn(VALID_PTR(pszValue), VERR_INVALID_POINTER);
5045
5046 Medium *that = static_cast<Medium*>(pvUser);
5047 AssertReturn(that != NULL, VERR_GENERAL_FAILURE);
5048
5049 Data::PropertyMap::const_iterator it =
5050 that->m->properties.find(Bstr(pszName));
5051 if (it == that->m->properties.end())
5052 return VERR_CFGM_VALUE_NOT_FOUND;
5053
5054 Utf8Str value = it->second;
5055 if (value.length() >= cchValue)
5056 return VERR_CFGM_NOT_ENOUGH_SPACE;
5057
5058 /* we interpret null values as "no value" in Medium */
5059 if (it->second.isEmpty())
5060 return VERR_CFGM_VALUE_NOT_FOUND;
5061
5062 memcpy(pszValue, value.c_str(), value.length() + 1);
5063
5064 return VINF_SUCCESS;
5065}
5066
5067DECLCALLBACK(int) Medium::vdTcpSocketCreate(uint32_t fFlags, PVDSOCKET pSock)
5068{
5069 PVDSOCKETINT pSocketInt = NULL;
5070
5071 if ((fFlags & VD_INTERFACETCPNET_CONNECT_EXTENDED_SELECT) != 0)
5072 return VERR_NOT_SUPPORTED;
5073
5074 pSocketInt = (PVDSOCKETINT)RTMemAllocZ(sizeof(VDSOCKETINT));
5075 if (!pSocketInt)
5076 return VERR_NO_MEMORY;
5077
5078 pSocketInt->hSocket = NIL_RTSOCKET;
5079 *pSock = pSocketInt;
5080 return VINF_SUCCESS;
5081}
5082
5083DECLCALLBACK(int) Medium::vdTcpSocketDestroy(VDSOCKET Sock)
5084{
5085 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
5086
5087 if (pSocketInt->hSocket != NIL_RTSOCKET)
5088 RTTcpClientClose(pSocketInt->hSocket);
5089
5090 RTMemFree(pSocketInt);
5091
5092 return VINF_SUCCESS;
5093}
5094
5095DECLCALLBACK(int) Medium::vdTcpClientConnect(VDSOCKET Sock, const char *pszAddress, uint32_t uPort)
5096{
5097 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
5098
5099 return RTTcpClientConnect(pszAddress, uPort, &pSocketInt->hSocket);
5100}
5101
5102DECLCALLBACK(int) Medium::vdTcpClientClose(VDSOCKET Sock)
5103{
5104 int rc = VINF_SUCCESS;
5105 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
5106
5107 rc = RTTcpClientClose(pSocketInt->hSocket);
5108 pSocketInt->hSocket = NIL_RTSOCKET;
5109 return rc;
5110}
5111
5112DECLCALLBACK(bool) Medium::vdTcpIsClientConnected(VDSOCKET Sock)
5113{
5114 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
5115 return pSocketInt->hSocket != NIL_RTSOCKET;
5116}
5117
5118DECLCALLBACK(int) Medium::vdTcpSelectOne(VDSOCKET Sock, RTMSINTERVAL cMillies)
5119{
5120 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
5121 return RTTcpSelectOne(pSocketInt->hSocket, cMillies);
5122}
5123
5124DECLCALLBACK(int) Medium::vdTcpRead(VDSOCKET Sock, void *pvBuffer, size_t cbBuffer, size_t *pcbRead)
5125{
5126 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
5127 return RTTcpRead(pSocketInt->hSocket, pvBuffer, cbBuffer, pcbRead);
5128}
5129
5130DECLCALLBACK(int) Medium::vdTcpWrite(VDSOCKET Sock, const void *pvBuffer, size_t cbBuffer)
5131{
5132 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
5133 return RTTcpWrite(pSocketInt->hSocket, pvBuffer, cbBuffer);
5134}
5135
5136DECLCALLBACK(int) Medium::vdTcpSgWrite(VDSOCKET Sock, PCRTSGBUF pSgBuf)
5137{
5138 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
5139 return RTTcpSgWrite(pSocketInt->hSocket, pSgBuf);
5140}
5141
5142DECLCALLBACK(int) Medium::vdTcpFlush(VDSOCKET Sock)
5143{
5144 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
5145 return RTTcpFlush(pSocketInt->hSocket);
5146}
5147
5148DECLCALLBACK(int) Medium::vdTcpSetSendCoalescing(VDSOCKET Sock, bool fEnable)
5149{
5150 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
5151 return RTTcpSetSendCoalescing(pSocketInt->hSocket, fEnable);
5152}
5153
5154DECLCALLBACK(int) Medium::vdTcpGetLocalAddress(VDSOCKET Sock, PRTNETADDR pAddr)
5155{
5156 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
5157 return RTTcpGetLocalAddress(pSocketInt->hSocket, pAddr);
5158}
5159
5160DECLCALLBACK(int) Medium::vdTcpGetPeerAddress(VDSOCKET Sock, PRTNETADDR pAddr)
5161{
5162 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
5163 return RTTcpGetPeerAddress(pSocketInt->hSocket, pAddr);
5164}
5165
5166
5167/**
5168 * Starts a new thread driven by the appropriate Medium::Task::handler() method.
5169 *
5170 * @note When the task is executed by this method, IProgress::notifyComplete()
5171 * is automatically called for the progress object associated with this
5172 * task when the task is finished to signal the operation completion for
5173 * other threads asynchronously waiting for it.
5174 */
5175HRESULT Medium::startThread(Medium::Task *pTask)
5176{
5177#ifdef VBOX_WITH_MAIN_LOCK_VALIDATION
5178 /* Extreme paranoia: The calling thread should not hold the medium
5179 * tree lock or any medium lock. Since there is no separate lock class
5180 * for medium objects be even more strict: no other object locks. */
5181 Assert(!AutoLockHoldsLocksInClass(LOCKCLASS_LISTOFMEDIA));
5182 Assert(!AutoLockHoldsLocksInClass(getLockingClass()));
5183#endif
5184
5185 /// @todo use a more descriptive task name
5186 int vrc = RTThreadCreate(NULL, Medium::Task::fntMediumTask, pTask,
5187 0, RTTHREADTYPE_MAIN_HEAVY_WORKER, 0,
5188 "Medium::Task");
5189 if (RT_FAILURE(vrc))
5190 {
5191 delete pTask;
5192 return setError(E_FAIL, "Could not create Medium::Task thread (%Rrc)\n", vrc);
5193 }
5194
5195 return S_OK;
5196}
5197
5198/**
5199 * Fix the parent UUID of all children to point to this medium as their
5200 * parent.
5201 */
5202HRESULT Medium::fixParentUuidOfChildren(const MediaList &childrenToReparent)
5203{
5204 MediumLockList mediumLockList;
5205 HRESULT rc = createMediumLockList(true /* fFailIfInaccessible */,
5206 false /* fMediumLockWrite */,
5207 this,
5208 mediumLockList);
5209 AssertComRCReturnRC(rc);
5210
5211 try
5212 {
5213 PVBOXHDD hdd;
5214 int vrc = VDCreate(m->vdDiskIfaces, &hdd);
5215 ComAssertRCThrow(vrc, E_FAIL);
5216
5217 try
5218 {
5219 MediumLockList::Base::iterator lockListBegin =
5220 mediumLockList.GetBegin();
5221 MediumLockList::Base::iterator lockListEnd =
5222 mediumLockList.GetEnd();
5223 for (MediumLockList::Base::iterator it = lockListBegin;
5224 it != lockListEnd;
5225 ++it)
5226 {
5227 MediumLock &mediumLock = *it;
5228 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
5229 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
5230
5231 // open the medium
5232 vrc = VDOpen(hdd,
5233 pMedium->m->strFormat.c_str(),
5234 pMedium->m->strLocationFull.c_str(),
5235 VD_OPEN_FLAGS_READONLY,
5236 pMedium->m->vdDiskIfaces);
5237 if (RT_FAILURE(vrc))
5238 throw vrc;
5239 }
5240
5241 for (MediaList::const_iterator it = childrenToReparent.begin();
5242 it != childrenToReparent.end();
5243 ++it)
5244 {
5245 /* VD_OPEN_FLAGS_INFO since UUID is wrong yet */
5246 vrc = VDOpen(hdd,
5247 (*it)->m->strFormat.c_str(),
5248 (*it)->m->strLocationFull.c_str(),
5249 VD_OPEN_FLAGS_INFO,
5250 (*it)->m->vdDiskIfaces);
5251 if (RT_FAILURE(vrc))
5252 throw vrc;
5253
5254 vrc = VDSetParentUuid(hdd, VD_LAST_IMAGE, m->id);
5255 if (RT_FAILURE(vrc))
5256 throw vrc;
5257
5258 vrc = VDClose(hdd, false /* fDelete */);
5259 if (RT_FAILURE(vrc))
5260 throw vrc;
5261
5262 (*it)->UnlockWrite(NULL);
5263 }
5264 }
5265 catch (HRESULT aRC) { rc = aRC; }
5266 catch (int aVRC)
5267 {
5268 throw setError(E_FAIL,
5269 tr("Could not update medium UUID references to parent '%s' (%s)"),
5270 m->strLocationFull.raw(),
5271 vdError(aVRC).raw());
5272 }
5273
5274 VDDestroy(hdd);
5275 }
5276 catch (HRESULT aRC) { rc = aRC; }
5277
5278 return rc;
5279}
5280
5281/**
5282 * Runs Medium::Task::handler() on the current thread instead of creating
5283 * a new one.
5284 *
5285 * This call implies that it is made on another temporary thread created for
5286 * some asynchronous task. Avoid calling it from a normal thread since the task
5287 * operations are potentially lengthy and will block the calling thread in this
5288 * case.
5289 *
5290 * @note When the task is executed by this method, IProgress::notifyComplete()
5291 * is not called for the progress object associated with this task when
5292 * the task is finished. Instead, the result of the operation is returned
5293 * by this method directly and it's the caller's responsibility to
5294 * complete the progress object in this case.
5295 */
5296HRESULT Medium::runNow(Medium::Task *pTask,
5297 bool *pfNeedsSaveSettings)
5298{
5299#ifdef VBOX_WITH_MAIN_LOCK_VALIDATION
5300 /* Extreme paranoia: The calling thread should not hold the medium
5301 * tree lock or any medium lock. Since there is no separate lock class
5302 * for medium objects be even more strict: no other object locks. */
5303 Assert(!AutoLockHoldsLocksInClass(LOCKCLASS_LISTOFMEDIA));
5304 Assert(!AutoLockHoldsLocksInClass(getLockingClass()));
5305#endif
5306
5307 pTask->m_pfNeedsSaveSettings = pfNeedsSaveSettings;
5308
5309 /* NIL_RTTHREAD indicates synchronous call. */
5310 return (HRESULT)Medium::Task::fntMediumTask(NIL_RTTHREAD, pTask);
5311}
5312
5313/**
5314 * Implementation code for the "create base" task.
5315 *
5316 * This only gets started from Medium::CreateBaseStorage() and always runs
5317 * asynchronously. As a result, we always save the VirtualBox.xml file when
5318 * we're done here.
5319 *
5320 * @param task
5321 * @return
5322 */
5323HRESULT Medium::taskCreateBaseHandler(Medium::CreateBaseTask &task)
5324{
5325 HRESULT rc = S_OK;
5326
5327 /* these parameters we need after creation */
5328 uint64_t size = 0, logicalSize = 0;
5329 MediumVariant_T variant = MediumVariant_Standard;
5330 bool fGenerateUuid = false;
5331
5332 try
5333 {
5334 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
5335
5336 /* The object may request a specific UUID (through a special form of
5337 * the setLocation() argument). Otherwise we have to generate it */
5338 Guid id = m->id;
5339 fGenerateUuid = id.isEmpty();
5340 if (fGenerateUuid)
5341 {
5342 id.create();
5343 /* VirtualBox::registerHardDisk() will need UUID */
5344 unconst(m->id) = id;
5345 }
5346
5347 Utf8Str format(m->strFormat);
5348 Utf8Str location(m->strLocationFull);
5349 uint64_t capabilities = m->formatObj->capabilities();
5350 ComAssertThrow(capabilities & ( VD_CAP_CREATE_FIXED
5351 | VD_CAP_CREATE_DYNAMIC), E_FAIL);
5352 Assert(m->state == MediumState_Creating);
5353
5354 PVBOXHDD hdd;
5355 int vrc = VDCreate(m->vdDiskIfaces, &hdd);
5356 ComAssertRCThrow(vrc, E_FAIL);
5357
5358 /* unlock before the potentially lengthy operation */
5359 thisLock.release();
5360
5361 try
5362 {
5363 /* ensure the directory exists */
5364 rc = VirtualBox::ensureFilePathExists(location);
5365 if (FAILED(rc))
5366 throw rc;
5367
5368 PDMMEDIAGEOMETRY geo = { 0, 0, 0 }; /* auto-detect */
5369
5370 vrc = VDCreateBase(hdd,
5371 format.c_str(),
5372 location.c_str(),
5373 task.mSize * _1M,
5374 task.mVariant,
5375 NULL,
5376 &geo,
5377 &geo,
5378 id.raw(),
5379 VD_OPEN_FLAGS_NORMAL,
5380 NULL,
5381 task.mVDOperationIfaces);
5382 if (RT_FAILURE(vrc))
5383 throw setError(VBOX_E_FILE_ERROR,
5384 tr("Could not create the medium storage unit '%s'%s"),
5385 location.raw(), vdError(vrc).raw());
5386
5387 size = VDGetFileSize(hdd, 0);
5388 logicalSize = VDGetSize(hdd, 0) / _1M;
5389 unsigned uImageFlags;
5390 vrc = VDGetImageFlags(hdd, 0, &uImageFlags);
5391 if (RT_SUCCESS(vrc))
5392 variant = (MediumVariant_T)uImageFlags;
5393 }
5394 catch (HRESULT aRC) { rc = aRC; }
5395
5396 VDDestroy(hdd);
5397 }
5398 catch (HRESULT aRC) { rc = aRC; }
5399
5400 if (SUCCEEDED(rc))
5401 {
5402 /* register with mVirtualBox as the last step and move to
5403 * Created state only on success (leaving an orphan file is
5404 * better than breaking media registry consistency) */
5405 bool fNeedsSaveSettings = false;
5406 AutoWriteLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
5407 rc = m->pVirtualBox->registerHardDisk(this, &fNeedsSaveSettings);
5408 treeLock.release();
5409
5410 if (fNeedsSaveSettings)
5411 {
5412 AutoWriteLock vboxlock(m->pVirtualBox COMMA_LOCKVAL_SRC_POS);
5413 m->pVirtualBox->saveSettings();
5414 }
5415 }
5416
5417 // reenter the lock before changing state
5418 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
5419
5420 if (SUCCEEDED(rc))
5421 {
5422 m->state = MediumState_Created;
5423
5424 m->size = size;
5425 m->logicalSize = logicalSize;
5426 m->variant = variant;
5427 }
5428 else
5429 {
5430 /* back to NotCreated on failure */
5431 m->state = MediumState_NotCreated;
5432
5433 /* reset UUID to prevent it from being reused next time */
5434 if (fGenerateUuid)
5435 unconst(m->id).clear();
5436 }
5437
5438 return rc;
5439}
5440
5441/**
5442 * Implementation code for the "create diff" task.
5443 *
5444 * This task always gets started from Medium::createDiffStorage() and can run
5445 * synchronously or asynchronously depending on the "wait" parameter passed to
5446 * that function. If we run synchronously, the caller expects the bool
5447 * *pfNeedsSaveSettings to be set before returning; otherwise (in asynchronous
5448 * mode), we save the settings ourselves.
5449 *
5450 * @param task
5451 * @return
5452 */
5453HRESULT Medium::taskCreateDiffHandler(Medium::CreateDiffTask &task)
5454{
5455 HRESULT rc = S_OK;
5456
5457 bool fNeedsSaveSettings = false;
5458
5459 const ComObjPtr<Medium> &pTarget = task.mTarget;
5460
5461 uint64_t size = 0, logicalSize = 0;
5462 MediumVariant_T variant = MediumVariant_Standard;
5463 bool fGenerateUuid = false;
5464
5465 try
5466 {
5467 /* Lock both in {parent,child} order. */
5468 AutoMultiWriteLock2 mediaLock(this, pTarget COMMA_LOCKVAL_SRC_POS);
5469
5470 /* The object may request a specific UUID (through a special form of
5471 * the setLocation() argument). Otherwise we have to generate it */
5472 Guid targetId = pTarget->m->id;
5473 fGenerateUuid = targetId.isEmpty();
5474 if (fGenerateUuid)
5475 {
5476 targetId.create();
5477 /* VirtualBox::registerHardDisk() will need UUID */
5478 unconst(pTarget->m->id) = targetId;
5479 }
5480
5481 Guid id = m->id;
5482
5483 Utf8Str targetFormat(pTarget->m->strFormat);
5484 Utf8Str targetLocation(pTarget->m->strLocationFull);
5485 uint64_t capabilities = m->formatObj->capabilities();
5486 ComAssertThrow(capabilities & VD_CAP_CREATE_DYNAMIC, E_FAIL);
5487
5488 Assert(pTarget->m->state == MediumState_Creating);
5489 Assert(m->state == MediumState_LockedRead);
5490
5491 PVBOXHDD hdd;
5492 int vrc = VDCreate(m->vdDiskIfaces, &hdd);
5493 ComAssertRCThrow(vrc, E_FAIL);
5494
5495 /* the two media are now protected by their non-default states;
5496 * unlock the media before the potentially lengthy operation */
5497 mediaLock.release();
5498
5499 try
5500 {
5501 /* Open all media in the target chain but the last. */
5502 MediumLockList::Base::const_iterator targetListBegin =
5503 task.mpMediumLockList->GetBegin();
5504 MediumLockList::Base::const_iterator targetListEnd =
5505 task.mpMediumLockList->GetEnd();
5506 for (MediumLockList::Base::const_iterator it = targetListBegin;
5507 it != targetListEnd;
5508 ++it)
5509 {
5510 const MediumLock &mediumLock = *it;
5511 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
5512
5513 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
5514
5515 /* Skip over the target diff medium */
5516 if (pMedium->m->state == MediumState_Creating)
5517 continue;
5518
5519 /* sanity check */
5520 Assert(pMedium->m->state == MediumState_LockedRead);
5521
5522 /* Open all media in appropriate mode. */
5523 vrc = VDOpen(hdd,
5524 pMedium->m->strFormat.c_str(),
5525 pMedium->m->strLocationFull.c_str(),
5526 VD_OPEN_FLAGS_READONLY,
5527 pMedium->m->vdDiskIfaces);
5528 if (RT_FAILURE(vrc))
5529 throw setError(VBOX_E_FILE_ERROR,
5530 tr("Could not open the medium storage unit '%s'%s"),
5531 pMedium->m->strLocationFull.raw(),
5532 vdError(vrc).raw());
5533 }
5534
5535 /* ensure the target directory exists */
5536 rc = VirtualBox::ensureFilePathExists(targetLocation);
5537 if (FAILED(rc))
5538 throw rc;
5539
5540 vrc = VDCreateDiff(hdd,
5541 targetFormat.c_str(),
5542 targetLocation.c_str(),
5543 task.mVariant | VD_IMAGE_FLAGS_DIFF,
5544 NULL,
5545 targetId.raw(),
5546 id.raw(),
5547 VD_OPEN_FLAGS_NORMAL,
5548 pTarget->m->vdDiskIfaces,
5549 task.mVDOperationIfaces);
5550 if (RT_FAILURE(vrc))
5551 throw setError(VBOX_E_FILE_ERROR,
5552 tr("Could not create the differencing medium storage unit '%s'%s"),
5553 targetLocation.raw(), vdError(vrc).raw());
5554
5555 size = VDGetFileSize(hdd, VD_LAST_IMAGE);
5556 logicalSize = VDGetSize(hdd, VD_LAST_IMAGE) / _1M;
5557 unsigned uImageFlags;
5558 vrc = VDGetImageFlags(hdd, 0, &uImageFlags);
5559 if (RT_SUCCESS(vrc))
5560 variant = (MediumVariant_T)uImageFlags;
5561 }
5562 catch (HRESULT aRC) { rc = aRC; }
5563
5564 VDDestroy(hdd);
5565 }
5566 catch (HRESULT aRC) { rc = aRC; }
5567
5568 if (SUCCEEDED(rc))
5569 {
5570 AutoWriteLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
5571
5572 Assert(pTarget->m->pParent.isNull());
5573
5574 /* associate the child with the parent */
5575 pTarget->m->pParent = this;
5576 m->llChildren.push_back(pTarget);
5577
5578 /** @todo r=klaus neither target nor base() are locked,
5579 * potential race! */
5580 /* diffs for immutable media are auto-reset by default */
5581 pTarget->m->autoReset = (getBase()->m->type == MediumType_Immutable);
5582
5583 /* register with mVirtualBox as the last step and move to
5584 * Created state only on success (leaving an orphan file is
5585 * better than breaking media registry consistency) */
5586 rc = m->pVirtualBox->registerHardDisk(pTarget, &fNeedsSaveSettings);
5587
5588 if (FAILED(rc))
5589 /* break the parent association on failure to register */
5590 deparent();
5591 }
5592
5593 AutoMultiWriteLock2 mediaLock(this, pTarget COMMA_LOCKVAL_SRC_POS);
5594
5595 if (SUCCEEDED(rc))
5596 {
5597 pTarget->m->state = MediumState_Created;
5598
5599 pTarget->m->size = size;
5600 pTarget->m->logicalSize = logicalSize;
5601 pTarget->m->variant = variant;
5602 }
5603 else
5604 {
5605 /* back to NotCreated on failure */
5606 pTarget->m->state = MediumState_NotCreated;
5607
5608 pTarget->m->autoReset = false;
5609
5610 /* reset UUID to prevent it from being reused next time */
5611 if (fGenerateUuid)
5612 unconst(pTarget->m->id).clear();
5613 }
5614
5615 // deregister the task registered in createDiffStorage()
5616 Assert(m->numCreateDiffTasks != 0);
5617 --m->numCreateDiffTasks;
5618
5619 if (task.isAsync())
5620 {
5621 if (fNeedsSaveSettings)
5622 {
5623 // save the global settings; for that we should hold only the VirtualBox lock
5624 mediaLock.release();
5625 AutoWriteLock vboxlock(m->pVirtualBox COMMA_LOCKVAL_SRC_POS);
5626 m->pVirtualBox->saveSettings();
5627 }
5628 }
5629 else
5630 // synchronous mode: report save settings result to caller
5631 if (task.m_pfNeedsSaveSettings)
5632 *task.m_pfNeedsSaveSettings = fNeedsSaveSettings;
5633
5634 /* Note that in sync mode, it's the caller's responsibility to
5635 * unlock the medium. */
5636
5637 return rc;
5638}
5639
5640/**
5641 * Implementation code for the "merge" task.
5642 *
5643 * This task always gets started from Medium::mergeTo() and can run
5644 * synchronously or asynchrously depending on the "wait" parameter passed to
5645 * that function. If we run synchronously, the caller expects the bool
5646 * *pfNeedsSaveSettings to be set before returning; otherwise (in asynchronous
5647 * mode), we save the settings ourselves.
5648 *
5649 * @param task
5650 * @return
5651 */
5652HRESULT Medium::taskMergeHandler(Medium::MergeTask &task)
5653{
5654 HRESULT rc = S_OK;
5655
5656 const ComObjPtr<Medium> &pTarget = task.mTarget;
5657
5658 try
5659 {
5660 PVBOXHDD hdd;
5661 int vrc = VDCreate(m->vdDiskIfaces, &hdd);
5662 ComAssertRCThrow(vrc, E_FAIL);
5663
5664 try
5665 {
5666 // Similar code appears in SessionMachine::onlineMergeMedium, so
5667 // if you make any changes below check whether they are applicable
5668 // in that context as well.
5669
5670 unsigned uTargetIdx = VD_LAST_IMAGE;
5671 unsigned uSourceIdx = VD_LAST_IMAGE;
5672 /* Open all media in the chain. */
5673 MediumLockList::Base::iterator lockListBegin =
5674 task.mpMediumLockList->GetBegin();
5675 MediumLockList::Base::iterator lockListEnd =
5676 task.mpMediumLockList->GetEnd();
5677 unsigned i = 0;
5678 for (MediumLockList::Base::iterator it = lockListBegin;
5679 it != lockListEnd;
5680 ++it)
5681 {
5682 MediumLock &mediumLock = *it;
5683 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
5684
5685 if (pMedium == this)
5686 uSourceIdx = i;
5687 else if (pMedium == pTarget)
5688 uTargetIdx = i;
5689
5690 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
5691
5692 /*
5693 * complex sanity (sane complexity)
5694 *
5695 * The current medium must be in the Deleting (medium is merged)
5696 * or LockedRead (parent medium) state if it is not the target.
5697 * If it is the target it must be in the LockedWrite state.
5698 */
5699 Assert( ( pMedium != pTarget
5700 && ( pMedium->m->state == MediumState_Deleting
5701 || pMedium->m->state == MediumState_LockedRead))
5702 || ( pMedium == pTarget
5703 && pMedium->m->state == MediumState_LockedWrite));
5704
5705 /*
5706 * Medium must be the target, in the LockedRead state
5707 * or Deleting state where it is not allowed to be attached
5708 * to a virtual machine.
5709 */
5710 Assert( pMedium == pTarget
5711 || pMedium->m->state == MediumState_LockedRead
5712 || ( pMedium->m->backRefs.size() == 0
5713 && pMedium->m->state == MediumState_Deleting));
5714 /* The source medium must be in Deleting state. */
5715 Assert( pMedium != this
5716 || pMedium->m->state == MediumState_Deleting);
5717
5718 unsigned uOpenFlags = VD_OPEN_FLAGS_NORMAL;
5719
5720 if ( pMedium->m->state == MediumState_LockedRead
5721 || pMedium->m->state == MediumState_Deleting)
5722 uOpenFlags = VD_OPEN_FLAGS_READONLY;
5723 if (pMedium->m->type == MediumType_Shareable)
5724 uOpenFlags |= VD_OPEN_FLAGS_SHAREABLE;
5725
5726 /* Open the medium */
5727 vrc = VDOpen(hdd,
5728 pMedium->m->strFormat.c_str(),
5729 pMedium->m->strLocationFull.c_str(),
5730 uOpenFlags,
5731 pMedium->m->vdDiskIfaces);
5732 if (RT_FAILURE(vrc))
5733 throw vrc;
5734
5735 i++;
5736 }
5737
5738 ComAssertThrow( uSourceIdx != VD_LAST_IMAGE
5739 && uTargetIdx != VD_LAST_IMAGE, E_FAIL);
5740
5741 vrc = VDMerge(hdd, uSourceIdx, uTargetIdx,
5742 task.mVDOperationIfaces);
5743 if (RT_FAILURE(vrc))
5744 throw vrc;
5745
5746 /* update parent UUIDs */
5747 if (!task.mfMergeForward)
5748 {
5749 /* we need to update UUIDs of all source's children
5750 * which cannot be part of the container at once so
5751 * add each one in there individually */
5752 if (task.mChildrenToReparent.size() > 0)
5753 {
5754 for (MediaList::const_iterator it = task.mChildrenToReparent.begin();
5755 it != task.mChildrenToReparent.end();
5756 ++it)
5757 {
5758 /* VD_OPEN_FLAGS_INFO since UUID is wrong yet */
5759 vrc = VDOpen(hdd,
5760 (*it)->m->strFormat.c_str(),
5761 (*it)->m->strLocationFull.c_str(),
5762 VD_OPEN_FLAGS_INFO,
5763 (*it)->m->vdDiskIfaces);
5764 if (RT_FAILURE(vrc))
5765 throw vrc;
5766
5767 vrc = VDSetParentUuid(hdd, VD_LAST_IMAGE,
5768 pTarget->m->id);
5769 if (RT_FAILURE(vrc))
5770 throw vrc;
5771
5772 vrc = VDClose(hdd, false /* fDelete */);
5773 if (RT_FAILURE(vrc))
5774 throw vrc;
5775
5776 (*it)->UnlockWrite(NULL);
5777 }
5778 }
5779 }
5780 }
5781 catch (HRESULT aRC) { rc = aRC; }
5782 catch (int aVRC)
5783 {
5784 throw setError(VBOX_E_FILE_ERROR,
5785 tr("Could not merge the medium '%s' to '%s'%s"),
5786 m->strLocationFull.raw(),
5787 pTarget->m->strLocationFull.raw(),
5788 vdError(aVRC).raw());
5789 }
5790
5791 VDDestroy(hdd);
5792 }
5793 catch (HRESULT aRC) { rc = aRC; }
5794
5795 HRESULT rc2;
5796
5797 if (SUCCEEDED(rc))
5798 {
5799 /* all media but the target were successfully deleted by
5800 * VDMerge; reparent the last one and uninitialize deleted media. */
5801
5802 AutoWriteLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
5803
5804 if (task.mfMergeForward)
5805 {
5806 /* first, unregister the target since it may become a base
5807 * medium which needs re-registration */
5808 rc2 = m->pVirtualBox->unregisterHardDisk(pTarget, NULL /*&fNeedsSaveSettings*/);
5809 AssertComRC(rc2);
5810
5811 /* then, reparent it and disconnect the deleted branch at
5812 * both ends (chain->parent() is source's parent) */
5813 pTarget->deparent();
5814 pTarget->m->pParent = task.mParentForTarget;
5815 if (pTarget->m->pParent)
5816 {
5817 pTarget->m->pParent->m->llChildren.push_back(pTarget);
5818 deparent();
5819 }
5820
5821 /* then, register again */
5822 rc2 = m->pVirtualBox->registerHardDisk(pTarget, NULL /*&fNeedsSaveSettings*/);
5823 AssertComRC(rc2);
5824 }
5825 else
5826 {
5827 Assert(pTarget->getChildren().size() == 1);
5828 Medium *targetChild = pTarget->getChildren().front();
5829
5830 /* disconnect the deleted branch at the elder end */
5831 targetChild->deparent();
5832
5833 /* reparent source's children and disconnect the deleted
5834 * branch at the younger end */
5835 if (task.mChildrenToReparent.size() > 0)
5836 {
5837 /* obey {parent,child} lock order */
5838 AutoWriteLock sourceLock(this COMMA_LOCKVAL_SRC_POS);
5839
5840 for (MediaList::const_iterator it = task.mChildrenToReparent.begin();
5841 it != task.mChildrenToReparent.end();
5842 it++)
5843 {
5844 Medium *pMedium = *it;
5845 AutoWriteLock childLock(pMedium COMMA_LOCKVAL_SRC_POS);
5846
5847 pMedium->deparent(); // removes pMedium from source
5848 pMedium->setParent(pTarget);
5849 }
5850 }
5851 }
5852
5853 /* unregister and uninitialize all media removed by the merge */
5854 MediumLockList::Base::iterator lockListBegin =
5855 task.mpMediumLockList->GetBegin();
5856 MediumLockList::Base::iterator lockListEnd =
5857 task.mpMediumLockList->GetEnd();
5858 for (MediumLockList::Base::iterator it = lockListBegin;
5859 it != lockListEnd;
5860 )
5861 {
5862 MediumLock &mediumLock = *it;
5863 /* Create a real copy of the medium pointer, as the medium
5864 * lock deletion below would invalidate the referenced object. */
5865 const ComObjPtr<Medium> pMedium = mediumLock.GetMedium();
5866
5867 /* The target and all media not merged (readonly) are skipped */
5868 if ( pMedium == pTarget
5869 || pMedium->m->state == MediumState_LockedRead)
5870 {
5871 ++it;
5872 continue;
5873 }
5874
5875 rc2 = pMedium->m->pVirtualBox->unregisterHardDisk(pMedium,
5876 NULL /*pfNeedsSaveSettings*/);
5877 AssertComRC(rc2);
5878
5879 /* now, uninitialize the deleted medium (note that
5880 * due to the Deleting state, uninit() will not touch
5881 * the parent-child relationship so we need to
5882 * uninitialize each disk individually) */
5883
5884 /* note that the operation initiator medium (which is
5885 * normally also the source medium) is a special case
5886 * -- there is one more caller added by Task to it which
5887 * we must release. Also, if we are in sync mode, the
5888 * caller may still hold an AutoCaller instance for it
5889 * and therefore we cannot uninit() it (it's therefore
5890 * the caller's responsibility) */
5891 if (pMedium == this)
5892 {
5893 Assert(getChildren().size() == 0);
5894 Assert(m->backRefs.size() == 0);
5895 task.mMediumCaller.release();
5896 }
5897
5898 /* Delete the medium lock list entry, which also releases the
5899 * caller added by MergeChain before uninit() and updates the
5900 * iterator to point to the right place. */
5901 rc2 = task.mpMediumLockList->RemoveByIterator(it);
5902 AssertComRC(rc2);
5903
5904 if (task.isAsync() || pMedium != this)
5905 pMedium->uninit();
5906 }
5907 }
5908
5909 if (task.isAsync())
5910 {
5911 // in asynchronous mode, save settings now
5912 // for that we should hold only the VirtualBox lock
5913 AutoWriteLock vboxlock(m->pVirtualBox COMMA_LOCKVAL_SRC_POS);
5914 m->pVirtualBox->saveSettings();
5915 }
5916 else
5917 // synchronous mode: report save settings result to caller
5918 if (task.m_pfNeedsSaveSettings)
5919 *task.m_pfNeedsSaveSettings = true;
5920
5921 if (FAILED(rc))
5922 {
5923 /* Here we come if either VDMerge() failed (in which case we
5924 * assume that it tried to do everything to make a further
5925 * retry possible -- e.g. not deleted intermediate media
5926 * and so on) or VirtualBox::saveSettings() failed (where we
5927 * should have the original tree but with intermediate storage
5928 * units deleted by VDMerge()). We have to only restore states
5929 * (through the MergeChain dtor) unless we are run synchronously
5930 * in which case it's the responsibility of the caller as stated
5931 * in the mergeTo() docs. The latter also implies that we
5932 * don't own the merge chain, so release it in this case. */
5933 if (task.isAsync())
5934 {
5935 Assert(task.mChildrenToReparent.size() == 0);
5936 cancelMergeTo(task.mChildrenToReparent, task.mpMediumLockList);
5937 }
5938 }
5939
5940 return rc;
5941}
5942
5943/**
5944 * Implementation code for the "clone" task.
5945 *
5946 * This only gets started from Medium::CloneTo() and always runs asynchronously.
5947 * As a result, we always save the VirtualBox.xml file when we're done here.
5948 *
5949 * @param task
5950 * @return
5951 */
5952HRESULT Medium::taskCloneHandler(Medium::CloneTask &task)
5953{
5954 HRESULT rc = S_OK;
5955
5956 const ComObjPtr<Medium> &pTarget = task.mTarget;
5957 const ComObjPtr<Medium> &pParent = task.mParent;
5958
5959 bool fCreatingTarget = false;
5960
5961 uint64_t size = 0, logicalSize = 0;
5962 MediumVariant_T variant = MediumVariant_Standard;
5963 bool fGenerateUuid = false;
5964
5965 try
5966 {
5967 /* Lock all in {parent,child} order. The lock is also used as a
5968 * signal from the task initiator (which releases it only after
5969 * RTThreadCreate()) that we can start the job. */
5970 AutoMultiWriteLock3 thisLock(this, pTarget, pParent COMMA_LOCKVAL_SRC_POS);
5971
5972 fCreatingTarget = pTarget->m->state == MediumState_Creating;
5973
5974 /* The object may request a specific UUID (through a special form of
5975 * the setLocation() argument). Otherwise we have to generate it */
5976 Guid targetId = pTarget->m->id;
5977 fGenerateUuid = targetId.isEmpty();
5978 if (fGenerateUuid)
5979 {
5980 targetId.create();
5981 /* VirtualBox::registerHardDisk() will need UUID */
5982 unconst(pTarget->m->id) = targetId;
5983 }
5984
5985 PVBOXHDD hdd;
5986 int vrc = VDCreate(m->vdDiskIfaces, &hdd);
5987 ComAssertRCThrow(vrc, E_FAIL);
5988
5989 try
5990 {
5991 /* Open all media in the source chain. */
5992 MediumLockList::Base::const_iterator sourceListBegin =
5993 task.mpSourceMediumLockList->GetBegin();
5994 MediumLockList::Base::const_iterator sourceListEnd =
5995 task.mpSourceMediumLockList->GetEnd();
5996 for (MediumLockList::Base::const_iterator it = sourceListBegin;
5997 it != sourceListEnd;
5998 ++it)
5999 {
6000 const MediumLock &mediumLock = *it;
6001 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
6002 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
6003
6004 /* sanity check */
6005 Assert(pMedium->m->state == MediumState_LockedRead);
6006
6007 /** Open all media in read-only mode. */
6008 vrc = VDOpen(hdd,
6009 pMedium->m->strFormat.c_str(),
6010 pMedium->m->strLocationFull.c_str(),
6011 VD_OPEN_FLAGS_READONLY,
6012 pMedium->m->vdDiskIfaces);
6013 if (RT_FAILURE(vrc))
6014 throw setError(VBOX_E_FILE_ERROR,
6015 tr("Could not open the medium storage unit '%s'%s"),
6016 pMedium->m->strLocationFull.raw(),
6017 vdError(vrc).raw());
6018 }
6019
6020 Utf8Str targetFormat(pTarget->m->strFormat);
6021 Utf8Str targetLocation(pTarget->m->strLocationFull);
6022
6023 Assert( pTarget->m->state == MediumState_Creating
6024 || pTarget->m->state == MediumState_LockedWrite);
6025 Assert(m->state == MediumState_LockedRead);
6026 Assert(pParent.isNull() || pParent->m->state == MediumState_LockedRead);
6027
6028 /* unlock before the potentially lengthy operation */
6029 thisLock.release();
6030
6031 /* ensure the target directory exists */
6032 rc = VirtualBox::ensureFilePathExists(targetLocation);
6033 if (FAILED(rc))
6034 throw rc;
6035
6036 PVBOXHDD targetHdd;
6037 vrc = VDCreate(m->vdDiskIfaces, &targetHdd);
6038 ComAssertRCThrow(vrc, E_FAIL);
6039
6040 try
6041 {
6042 /* Open all media in the target chain. */
6043 MediumLockList::Base::const_iterator targetListBegin =
6044 task.mpTargetMediumLockList->GetBegin();
6045 MediumLockList::Base::const_iterator targetListEnd =
6046 task.mpTargetMediumLockList->GetEnd();
6047 for (MediumLockList::Base::const_iterator it = targetListBegin;
6048 it != targetListEnd;
6049 ++it)
6050 {
6051 const MediumLock &mediumLock = *it;
6052 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
6053
6054 /* If the target medium is not created yet there's no
6055 * reason to open it. */
6056 if (pMedium == pTarget && fCreatingTarget)
6057 continue;
6058
6059 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
6060
6061 /* sanity check */
6062 Assert( pMedium->m->state == MediumState_LockedRead
6063 || pMedium->m->state == MediumState_LockedWrite);
6064
6065 unsigned uOpenFlags = VD_OPEN_FLAGS_NORMAL;
6066 if (pMedium->m->state != MediumState_LockedWrite)
6067 uOpenFlags = VD_OPEN_FLAGS_READONLY;
6068 if (pMedium->m->type == MediumType_Shareable)
6069 uOpenFlags |= VD_OPEN_FLAGS_SHAREABLE;
6070
6071 /* Open all media in appropriate mode. */
6072 vrc = VDOpen(targetHdd,
6073 pMedium->m->strFormat.c_str(),
6074 pMedium->m->strLocationFull.c_str(),
6075 uOpenFlags,
6076 pMedium->m->vdDiskIfaces);
6077 if (RT_FAILURE(vrc))
6078 throw setError(VBOX_E_FILE_ERROR,
6079 tr("Could not open the medium storage unit '%s'%s"),
6080 pMedium->m->strLocationFull.raw(),
6081 vdError(vrc).raw());
6082 }
6083
6084 /** @todo r=klaus target isn't locked, race getting the state */
6085 vrc = VDCopy(hdd,
6086 VD_LAST_IMAGE,
6087 targetHdd,
6088 targetFormat.c_str(),
6089 (fCreatingTarget) ? targetLocation.raw() : (char *)NULL,
6090 false,
6091 0,
6092 task.mVariant,
6093 targetId.raw(),
6094 NULL,
6095 pTarget->m->vdDiskIfaces,
6096 task.mVDOperationIfaces);
6097 if (RT_FAILURE(vrc))
6098 throw setError(VBOX_E_FILE_ERROR,
6099 tr("Could not create the clone medium '%s'%s"),
6100 targetLocation.raw(), vdError(vrc).raw());
6101
6102 size = VDGetFileSize(targetHdd, VD_LAST_IMAGE);
6103 logicalSize = VDGetSize(targetHdd, VD_LAST_IMAGE) / _1M;
6104 unsigned uImageFlags;
6105 vrc = VDGetImageFlags(targetHdd, 0, &uImageFlags);
6106 if (RT_SUCCESS(vrc))
6107 variant = (MediumVariant_T)uImageFlags;
6108 }
6109 catch (HRESULT aRC) { rc = aRC; }
6110
6111 VDDestroy(targetHdd);
6112 }
6113 catch (HRESULT aRC) { rc = aRC; }
6114
6115 VDDestroy(hdd);
6116 }
6117 catch (HRESULT aRC) { rc = aRC; }
6118
6119 /* Only do the parent changes for newly created media. */
6120 if (SUCCEEDED(rc) && fCreatingTarget)
6121 {
6122 /* we set mParent & children() */
6123 AutoWriteLock alock2(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
6124
6125 Assert(pTarget->m->pParent.isNull());
6126
6127 if (pParent)
6128 {
6129 /* associate the clone with the parent and deassociate
6130 * from VirtualBox */
6131 pTarget->m->pParent = pParent;
6132 pParent->m->llChildren.push_back(pTarget);
6133
6134 /* register with mVirtualBox as the last step and move to
6135 * Created state only on success (leaving an orphan file is
6136 * better than breaking media registry consistency) */
6137 rc = pParent->m->pVirtualBox->registerHardDisk(pTarget, NULL /* pfNeedsSaveSettings */);
6138
6139 if (FAILED(rc))
6140 /* break parent association on failure to register */
6141 pTarget->deparent(); // removes target from parent
6142 }
6143 else
6144 {
6145 /* just register */
6146 rc = m->pVirtualBox->registerHardDisk(pTarget, NULL /* pfNeedsSaveSettings */);
6147 }
6148 }
6149
6150 if (fCreatingTarget)
6151 {
6152 AutoWriteLock mLock(pTarget COMMA_LOCKVAL_SRC_POS);
6153
6154 if (SUCCEEDED(rc))
6155 {
6156 pTarget->m->state = MediumState_Created;
6157
6158 pTarget->m->size = size;
6159 pTarget->m->logicalSize = logicalSize;
6160 pTarget->m->variant = variant;
6161 }
6162 else
6163 {
6164 /* back to NotCreated on failure */
6165 pTarget->m->state = MediumState_NotCreated;
6166
6167 /* reset UUID to prevent it from being reused next time */
6168 if (fGenerateUuid)
6169 unconst(pTarget->m->id).clear();
6170 }
6171 }
6172
6173 // now, at the end of this task (always asynchronous), save the settings
6174 {
6175 AutoWriteLock vboxlock(m->pVirtualBox COMMA_LOCKVAL_SRC_POS);
6176 m->pVirtualBox->saveSettings();
6177 }
6178
6179 /* Everything is explicitly unlocked when the task exits,
6180 * as the task destruction also destroys the source chain. */
6181
6182 /* Make sure the source chain is released early. It could happen
6183 * that we get a deadlock in Appliance::Import when Medium::Close
6184 * is called & the source chain is released at the same time. */
6185 task.mpSourceMediumLockList->Clear();
6186
6187 return rc;
6188}
6189
6190/**
6191 * Implementation code for the "delete" task.
6192 *
6193 * This task always gets started from Medium::deleteStorage() and can run
6194 * synchronously or asynchrously depending on the "wait" parameter passed to
6195 * that function.
6196 *
6197 * @param task
6198 * @return
6199 */
6200HRESULT Medium::taskDeleteHandler(Medium::DeleteTask &task)
6201{
6202 NOREF(task);
6203 HRESULT rc = S_OK;
6204
6205 try
6206 {
6207 /* The lock is also used as a signal from the task initiator (which
6208 * releases it only after RTThreadCreate()) that we can start the job */
6209 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
6210
6211 PVBOXHDD hdd;
6212 int vrc = VDCreate(m->vdDiskIfaces, &hdd);
6213 ComAssertRCThrow(vrc, E_FAIL);
6214
6215 Utf8Str format(m->strFormat);
6216 Utf8Str location(m->strLocationFull);
6217
6218 /* unlock before the potentially lengthy operation */
6219 Assert(m->state == MediumState_Deleting);
6220 thisLock.release();
6221
6222 try
6223 {
6224 vrc = VDOpen(hdd,
6225 format.c_str(),
6226 location.c_str(),
6227 VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_INFO,
6228 m->vdDiskIfaces);
6229 if (RT_SUCCESS(vrc))
6230 vrc = VDClose(hdd, true /* fDelete */);
6231
6232 if (RT_FAILURE(vrc))
6233 throw setError(VBOX_E_FILE_ERROR,
6234 tr("Could not delete the medium storage unit '%s'%s"),
6235 location.raw(), vdError(vrc).raw());
6236
6237 }
6238 catch (HRESULT aRC) { rc = aRC; }
6239
6240 VDDestroy(hdd);
6241 }
6242 catch (HRESULT aRC) { rc = aRC; }
6243
6244 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
6245
6246 /* go to the NotCreated state even on failure since the storage
6247 * may have been already partially deleted and cannot be used any
6248 * more. One will be able to manually re-open the storage if really
6249 * needed to re-register it. */
6250 m->state = MediumState_NotCreated;
6251
6252 /* Reset UUID to prevent Create* from reusing it again */
6253 unconst(m->id).clear();
6254
6255 return rc;
6256}
6257
6258/**
6259 * Implementation code for the "reset" task.
6260 *
6261 * This always gets started asynchronously from Medium::Reset().
6262 *
6263 * @param task
6264 * @return
6265 */
6266HRESULT Medium::taskResetHandler(Medium::ResetTask &task)
6267{
6268 HRESULT rc = S_OK;
6269
6270 uint64_t size = 0, logicalSize = 0;
6271 MediumVariant_T variant = MediumVariant_Standard;
6272
6273 try
6274 {
6275 /* The lock is also used as a signal from the task initiator (which
6276 * releases it only after RTThreadCreate()) that we can start the job */
6277 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
6278
6279 /// @todo Below we use a pair of delete/create operations to reset
6280 /// the diff contents but the most efficient way will of course be
6281 /// to add a VDResetDiff() API call
6282
6283 PVBOXHDD hdd;
6284 int vrc = VDCreate(m->vdDiskIfaces, &hdd);
6285 ComAssertRCThrow(vrc, E_FAIL);
6286
6287 Guid id = m->id;
6288 Utf8Str format(m->strFormat);
6289 Utf8Str location(m->strLocationFull);
6290
6291 Medium *pParent = m->pParent;
6292 Guid parentId = pParent->m->id;
6293 Utf8Str parentFormat(pParent->m->strFormat);
6294 Utf8Str parentLocation(pParent->m->strLocationFull);
6295
6296 Assert(m->state == MediumState_LockedWrite);
6297
6298 /* unlock before the potentially lengthy operation */
6299 thisLock.release();
6300
6301 try
6302 {
6303 /* Open all media in the target chain but the last. */
6304 MediumLockList::Base::const_iterator targetListBegin =
6305 task.mpMediumLockList->GetBegin();
6306 MediumLockList::Base::const_iterator targetListEnd =
6307 task.mpMediumLockList->GetEnd();
6308 for (MediumLockList::Base::const_iterator it = targetListBegin;
6309 it != targetListEnd;
6310 ++it)
6311 {
6312 const MediumLock &mediumLock = *it;
6313 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
6314
6315 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
6316
6317 /* sanity check, "this" is checked above */
6318 Assert( pMedium == this
6319 || pMedium->m->state == MediumState_LockedRead);
6320
6321 /* Open all media in appropriate mode. */
6322 vrc = VDOpen(hdd,
6323 pMedium->m->strFormat.c_str(),
6324 pMedium->m->strLocationFull.c_str(),
6325 VD_OPEN_FLAGS_READONLY,
6326 pMedium->m->vdDiskIfaces);
6327 if (RT_FAILURE(vrc))
6328 throw setError(VBOX_E_FILE_ERROR,
6329 tr("Could not open the medium storage unit '%s'%s"),
6330 pMedium->m->strLocationFull.raw(),
6331 vdError(vrc).raw());
6332
6333 /* Done when we hit the media which should be reset */
6334 if (pMedium == this)
6335 break;
6336 }
6337
6338 /* first, delete the storage unit */
6339 vrc = VDClose(hdd, true /* fDelete */);
6340 if (RT_FAILURE(vrc))
6341 throw setError(VBOX_E_FILE_ERROR,
6342 tr("Could not delete the medium storage unit '%s'%s"),
6343 location.raw(), vdError(vrc).raw());
6344
6345 /* next, create it again */
6346 vrc = VDOpen(hdd,
6347 parentFormat.c_str(),
6348 parentLocation.c_str(),
6349 VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_INFO,
6350 m->vdDiskIfaces);
6351 if (RT_FAILURE(vrc))
6352 throw setError(VBOX_E_FILE_ERROR,
6353 tr("Could not open the medium storage unit '%s'%s"),
6354 parentLocation.raw(), vdError(vrc).raw());
6355
6356 vrc = VDCreateDiff(hdd,
6357 format.c_str(),
6358 location.c_str(),
6359 /// @todo use the same medium variant as before
6360 VD_IMAGE_FLAGS_NONE,
6361 NULL,
6362 id.raw(),
6363 parentId.raw(),
6364 VD_OPEN_FLAGS_NORMAL,
6365 m->vdDiskIfaces,
6366 task.mVDOperationIfaces);
6367 if (RT_FAILURE(vrc))
6368 throw setError(VBOX_E_FILE_ERROR,
6369 tr("Could not create the differencing medium storage unit '%s'%s"),
6370 location.raw(), vdError(vrc).raw());
6371
6372 size = VDGetFileSize(hdd, VD_LAST_IMAGE);
6373 logicalSize = VDGetSize(hdd, VD_LAST_IMAGE) / _1M;
6374 unsigned uImageFlags;
6375 vrc = VDGetImageFlags(hdd, 0, &uImageFlags);
6376 if (RT_SUCCESS(vrc))
6377 variant = (MediumVariant_T)uImageFlags;
6378 }
6379 catch (HRESULT aRC) { rc = aRC; }
6380
6381 VDDestroy(hdd);
6382 }
6383 catch (HRESULT aRC) { rc = aRC; }
6384
6385 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
6386
6387 m->size = size;
6388 m->logicalSize = logicalSize;
6389 m->variant = variant;
6390
6391 if (task.isAsync())
6392 {
6393 /* unlock ourselves when done */
6394 HRESULT rc2 = UnlockWrite(NULL);
6395 AssertComRC(rc2);
6396 }
6397
6398 /* Note that in sync mode, it's the caller's responsibility to
6399 * unlock the medium. */
6400
6401 return rc;
6402}
6403
6404/**
6405 * Implementation code for the "compact" task.
6406 *
6407 * @param task
6408 * @return
6409 */
6410HRESULT Medium::taskCompactHandler(Medium::CompactTask &task)
6411{
6412 HRESULT rc = S_OK;
6413
6414 /* Lock all in {parent,child} order. The lock is also used as a
6415 * signal from the task initiator (which releases it only after
6416 * RTThreadCreate()) that we can start the job. */
6417 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
6418
6419 try
6420 {
6421 PVBOXHDD hdd;
6422 int vrc = VDCreate(m->vdDiskIfaces, &hdd);
6423 ComAssertRCThrow(vrc, E_FAIL);
6424
6425 try
6426 {
6427 /* Open all media in the chain. */
6428 MediumLockList::Base::const_iterator mediumListBegin =
6429 task.mpMediumLockList->GetBegin();
6430 MediumLockList::Base::const_iterator mediumListEnd =
6431 task.mpMediumLockList->GetEnd();
6432 MediumLockList::Base::const_iterator mediumListLast =
6433 mediumListEnd;
6434 mediumListLast--;
6435 for (MediumLockList::Base::const_iterator it = mediumListBegin;
6436 it != mediumListEnd;
6437 ++it)
6438 {
6439 const MediumLock &mediumLock = *it;
6440 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
6441 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
6442
6443 /* sanity check */
6444 if (it == mediumListLast)
6445 Assert(pMedium->m->state == MediumState_LockedWrite);
6446 else
6447 Assert(pMedium->m->state == MediumState_LockedRead);
6448
6449 /* Open all media but last in read-only mode. Do not handle
6450 * shareable media, as compaction and sharing are mutually
6451 * exclusive. */
6452 vrc = VDOpen(hdd,
6453 pMedium->m->strFormat.c_str(),
6454 pMedium->m->strLocationFull.c_str(),
6455 (it == mediumListLast) ? VD_OPEN_FLAGS_NORMAL : VD_OPEN_FLAGS_READONLY,
6456 pMedium->m->vdDiskIfaces);
6457 if (RT_FAILURE(vrc))
6458 throw setError(VBOX_E_FILE_ERROR,
6459 tr("Could not open the medium storage unit '%s'%s"),
6460 pMedium->m->strLocationFull.raw(),
6461 vdError(vrc).raw());
6462 }
6463
6464 Assert(m->state == MediumState_LockedWrite);
6465
6466 Utf8Str location(m->strLocationFull);
6467
6468 /* unlock before the potentially lengthy operation */
6469 thisLock.release();
6470
6471 vrc = VDCompact(hdd, VD_LAST_IMAGE, task.mVDOperationIfaces);
6472 if (RT_FAILURE(vrc))
6473 {
6474 if (vrc == VERR_NOT_SUPPORTED)
6475 throw setError(VBOX_E_NOT_SUPPORTED,
6476 tr("Compacting is not yet supported for medium '%s'"),
6477 location.raw());
6478 else if (vrc == VERR_NOT_IMPLEMENTED)
6479 throw setError(E_NOTIMPL,
6480 tr("Compacting is not implemented, medium '%s'"),
6481 location.raw());
6482 else
6483 throw setError(VBOX_E_FILE_ERROR,
6484 tr("Could not compact medium '%s'%s"),
6485 location.raw(),
6486 vdError(vrc).raw());
6487 }
6488 }
6489 catch (HRESULT aRC) { rc = aRC; }
6490
6491 VDDestroy(hdd);
6492 }
6493 catch (HRESULT aRC) { rc = aRC; }
6494
6495 /* Everything is explicitly unlocked when the task exits,
6496 * as the task destruction also destroys the media chain. */
6497
6498 return rc;
6499}
6500
6501/* 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