VirtualBox

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

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

Main: storage controller/attachment cleanup

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 211.7 KB
Line 
1/* $Id: MediumImpl.cpp 31308 2010-08-02 14:55:22Z 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 which returns true if this medium represents a host drive.
2607 * @return
2608 */
2609bool Medium::isHostDrive() const
2610{
2611 return m->hostDrive;
2612}
2613
2614/**
2615 * Internal method to return the medium's location. Must have caller + locking!
2616 * @return
2617 */
2618const Utf8Str& Medium::getLocation() const
2619{
2620 return m->strLocation;
2621}
2622
2623/**
2624 * Internal method to return the medium's full location. Must have caller + locking!
2625 * @return
2626 */
2627const Utf8Str& Medium::getLocationFull() const
2628{
2629 return m->strLocationFull;
2630}
2631
2632/**
2633 * Internal method to return the medium's format string. Must have caller + locking!
2634 * @return
2635 */
2636const Utf8Str& Medium::getFormat() const
2637{
2638 return m->strFormat;
2639}
2640
2641/**
2642 * Internal method to return the medium's format object. Must have caller + locking!
2643 * @return
2644 */
2645const ComObjPtr<MediumFormat> & Medium::getMediumFormat() const
2646{
2647 return m->formatObj;
2648}
2649
2650/**
2651 * Internal method to return the medium's size. Must have caller + locking!
2652 * @return
2653 */
2654uint64_t Medium::getSize() const
2655{
2656 return m->size;
2657}
2658
2659/**
2660 * Adds the given machine and optionally the snapshot to the list of the objects
2661 * this medium is attached to.
2662 *
2663 * @param aMachineId Machine ID.
2664 * @param aSnapshotId Snapshot ID; when non-empty, adds a snapshot attachment.
2665 */
2666HRESULT Medium::addBackReference(const Guid &aMachineId,
2667 const Guid &aSnapshotId /*= Guid::Empty*/)
2668{
2669 AssertReturn(!aMachineId.isEmpty(), E_FAIL);
2670
2671 LogFlowThisFunc(("ENTER, aMachineId: {%RTuuid}, aSnapshotId: {%RTuuid}\n", aMachineId.raw(), aSnapshotId.raw()));
2672
2673 AutoCaller autoCaller(this);
2674 AssertComRCReturnRC(autoCaller.rc());
2675
2676 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2677
2678 switch (m->state)
2679 {
2680 case MediumState_Created:
2681 case MediumState_Inaccessible:
2682 case MediumState_LockedRead:
2683 case MediumState_LockedWrite:
2684 break;
2685
2686 default:
2687 return setStateError();
2688 }
2689
2690 if (m->numCreateDiffTasks > 0)
2691 return setError(VBOX_E_OBJECT_IN_USE,
2692 tr("Cannot attach medium '%s' {%RTuuid}: %u differencing child media are being created"),
2693 m->strLocationFull.raw(),
2694 m->id.raw(),
2695 m->numCreateDiffTasks);
2696
2697 BackRefList::iterator it = std::find_if(m->backRefs.begin(),
2698 m->backRefs.end(),
2699 BackRef::EqualsTo(aMachineId));
2700 if (it == m->backRefs.end())
2701 {
2702 BackRef ref(aMachineId, aSnapshotId);
2703 m->backRefs.push_back(ref);
2704
2705 return S_OK;
2706 }
2707
2708 // if the caller has not supplied a snapshot ID, then we're attaching
2709 // to a machine a medium which represents the machine's current state,
2710 // so set the flag
2711 if (aSnapshotId.isEmpty())
2712 {
2713 /* sanity: no duplicate attachments */
2714 AssertReturn(!it->fInCurState, E_FAIL);
2715 it->fInCurState = true;
2716
2717 return S_OK;
2718 }
2719
2720 // otherwise: a snapshot medium is being attached
2721
2722 /* sanity: no duplicate attachments */
2723 for (BackRef::GuidList::const_iterator jt = it->llSnapshotIds.begin();
2724 jt != it->llSnapshotIds.end();
2725 ++jt)
2726 {
2727 const Guid &idOldSnapshot = *jt;
2728
2729 if (idOldSnapshot == aSnapshotId)
2730 {
2731#ifdef DEBUG
2732 dumpBackRefs();
2733#endif
2734 return setError(VBOX_E_OBJECT_IN_USE,
2735 tr("Cannot attach medium '%s' {%RTuuid} from snapshot '%RTuuid': medium is already in use by this snapshot!"),
2736 m->strLocationFull.raw(),
2737 m->id.raw(),
2738 aSnapshotId.raw(),
2739 idOldSnapshot.raw());
2740 }
2741 }
2742
2743 it->llSnapshotIds.push_back(aSnapshotId);
2744 it->fInCurState = false;
2745
2746 LogFlowThisFuncLeave();
2747
2748 return S_OK;
2749}
2750
2751/**
2752 * Removes the given machine and optionally the snapshot from the list of the
2753 * objects this medium is attached to.
2754 *
2755 * @param aMachineId Machine ID.
2756 * @param aSnapshotId Snapshot ID; when non-empty, removes the snapshot
2757 * attachment.
2758 */
2759HRESULT Medium::removeBackReference(const Guid &aMachineId,
2760 const Guid &aSnapshotId /*= Guid::Empty*/)
2761{
2762 AssertReturn(!aMachineId.isEmpty(), E_FAIL);
2763
2764 AutoCaller autoCaller(this);
2765 AssertComRCReturnRC(autoCaller.rc());
2766
2767 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2768
2769 BackRefList::iterator it =
2770 std::find_if(m->backRefs.begin(), m->backRefs.end(),
2771 BackRef::EqualsTo(aMachineId));
2772 AssertReturn(it != m->backRefs.end(), E_FAIL);
2773
2774 if (aSnapshotId.isEmpty())
2775 {
2776 /* remove the current state attachment */
2777 it->fInCurState = false;
2778 }
2779 else
2780 {
2781 /* remove the snapshot attachment */
2782 BackRef::GuidList::iterator jt =
2783 std::find(it->llSnapshotIds.begin(), it->llSnapshotIds.end(), aSnapshotId);
2784
2785 AssertReturn(jt != it->llSnapshotIds.end(), E_FAIL);
2786 it->llSnapshotIds.erase(jt);
2787 }
2788
2789 /* if the backref becomes empty, remove it */
2790 if (it->fInCurState == false && it->llSnapshotIds.size() == 0)
2791 m->backRefs.erase(it);
2792
2793 return S_OK;
2794}
2795
2796/**
2797 * Internal method to return the medium's list of backrefs. Must have caller + locking!
2798 * @return
2799 */
2800const Guid* Medium::getFirstMachineBackrefId() const
2801{
2802 if (!m->backRefs.size())
2803 return NULL;
2804
2805 return &m->backRefs.front().machineId;
2806}
2807
2808const Guid* Medium::getFirstMachineBackrefSnapshotId() const
2809{
2810 if (!m->backRefs.size())
2811 return NULL;
2812
2813 const BackRef &ref = m->backRefs.front();
2814 if (!ref.llSnapshotIds.size())
2815 return NULL;
2816
2817 return &ref.llSnapshotIds.front();
2818}
2819
2820#ifdef DEBUG
2821/**
2822 * Debugging helper that gets called after VirtualBox initialization that writes all
2823 * machine backreferences to the debug log.
2824 */
2825void Medium::dumpBackRefs()
2826{
2827 AutoCaller autoCaller(this);
2828 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2829
2830 LogFlowThisFunc(("Dumping backrefs for medium '%s':\n", m->strLocationFull.raw()));
2831
2832 for (BackRefList::iterator it2 = m->backRefs.begin();
2833 it2 != m->backRefs.end();
2834 ++it2)
2835 {
2836 const BackRef &ref = *it2;
2837 LogFlowThisFunc((" Backref from machine {%RTuuid} (fInCurState: %d)\n", ref.machineId.raw(), ref.fInCurState));
2838
2839 for (BackRef::GuidList::const_iterator jt2 = it2->llSnapshotIds.begin();
2840 jt2 != it2->llSnapshotIds.end();
2841 ++jt2)
2842 {
2843 const Guid &id = *jt2;
2844 LogFlowThisFunc((" Backref from snapshot {%RTuuid}\n", id.raw()));
2845 }
2846 }
2847}
2848#endif
2849
2850/**
2851 * Checks if the given change of \a aOldPath to \a aNewPath affects the location
2852 * of this media and updates it if necessary to reflect the new location.
2853 *
2854 * @param aOldPath Old path (full).
2855 * @param aNewPath New path (full).
2856 *
2857 * @note Locks this object for writing.
2858 */
2859HRESULT Medium::updatePath(const char *aOldPath, const char *aNewPath)
2860{
2861 AssertReturn(aOldPath, E_FAIL);
2862 AssertReturn(aNewPath, E_FAIL);
2863
2864 AutoCaller autoCaller(this);
2865 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2866
2867 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2868
2869 LogFlowThisFunc(("locationFull.before='%s'\n", m->strLocationFull.raw()));
2870
2871 const char *pcszMediumPath = m->strLocationFull.c_str();
2872
2873 if (RTPathStartsWith(pcszMediumPath, aOldPath))
2874 {
2875 Utf8Str newPath = Utf8StrFmt("%s%s",
2876 aNewPath,
2877 pcszMediumPath + strlen(aOldPath));
2878 unconst(m->strLocationFull) = newPath;
2879
2880 Utf8Str path;
2881 m->pVirtualBox->copyPathRelativeToConfig(newPath, path);
2882 unconst(m->strLocation) = path;
2883
2884 LogFlowThisFunc(("locationFull.after='%s'\n", m->strLocationFull.raw()));
2885 }
2886
2887 return S_OK;
2888}
2889
2890/**
2891 * Checks if the given change of \a aOldPath to \a aNewPath affects the location
2892 * of this medium or any its child and updates the paths if necessary to
2893 * reflect the new location.
2894 *
2895 * @param aOldPath Old path (full).
2896 * @param aNewPath New path (full).
2897 *
2898 * @note Locks the medium tree for reading, this object and all children for writing.
2899 */
2900void Medium::updatePaths(const char *aOldPath, const char *aNewPath)
2901{
2902 AssertReturnVoid(aOldPath);
2903 AssertReturnVoid(aNewPath);
2904
2905 AutoCaller autoCaller(this);
2906 AssertComRCReturnVoid(autoCaller.rc());
2907
2908 /* we access children() */
2909 AutoReadLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
2910
2911 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
2912
2913 updatePath(aOldPath, aNewPath);
2914
2915 /* update paths of all children */
2916 for (MediaList::const_iterator it = getChildren().begin();
2917 it != getChildren().end();
2918 ++it)
2919 {
2920 (*it)->updatePaths(aOldPath, aNewPath);
2921 }
2922}
2923
2924/**
2925 * Returns the base medium of the media chain this medium is part of.
2926 *
2927 * The base medium is found by walking up the parent-child relationship axis.
2928 * If the medium doesn't have a parent (i.e. it's a base medium), it
2929 * returns itself in response to this method.
2930 *
2931 * @param aLevel Where to store the number of ancestors of this medium
2932 * (zero for the base), may be @c NULL.
2933 *
2934 * @note Locks medium tree for reading.
2935 */
2936ComObjPtr<Medium> Medium::getBase(uint32_t *aLevel /*= NULL*/)
2937{
2938 ComObjPtr<Medium> pBase;
2939 uint32_t level;
2940
2941 AutoCaller autoCaller(this);
2942 AssertReturn(autoCaller.isOk(), pBase);
2943
2944 /* we access mParent */
2945 AutoReadLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
2946
2947 pBase = this;
2948 level = 0;
2949
2950 if (m->pParent)
2951 {
2952 for (;;)
2953 {
2954 AutoCaller baseCaller(pBase);
2955 AssertReturn(baseCaller.isOk(), pBase);
2956
2957 if (pBase->m->pParent.isNull())
2958 break;
2959
2960 pBase = pBase->m->pParent;
2961 ++level;
2962 }
2963 }
2964
2965 if (aLevel != NULL)
2966 *aLevel = level;
2967
2968 return pBase;
2969}
2970
2971/**
2972 * Returns @c true if this medium cannot be modified because it has
2973 * dependants (children) or is part of the snapshot. Related to the medium
2974 * type and posterity, not to the current media state.
2975 *
2976 * @note Locks this object and medium tree for reading.
2977 */
2978bool Medium::isReadOnly()
2979{
2980 AutoCaller autoCaller(this);
2981 AssertComRCReturn(autoCaller.rc(), false);
2982
2983 /* we access children */
2984 AutoReadLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
2985
2986 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
2987
2988 switch (m->type)
2989 {
2990 case MediumType_Normal:
2991 {
2992 if (getChildren().size() != 0)
2993 return true;
2994
2995 for (BackRefList::const_iterator it = m->backRefs.begin();
2996 it != m->backRefs.end(); ++it)
2997 if (it->llSnapshotIds.size() != 0)
2998 return true;
2999
3000 return false;
3001 }
3002 case MediumType_Immutable:
3003 return true;
3004 case MediumType_Writethrough:
3005 case MediumType_Shareable:
3006 return false;
3007 default:
3008 break;
3009 }
3010
3011 AssertFailedReturn(false);
3012}
3013
3014/**
3015 * Saves medium data by appending a new child node to the given
3016 * parent XML settings node.
3017 *
3018 * @param data Settings struct to be updated.
3019 *
3020 * @note Locks this object, medium tree and children for reading.
3021 */
3022HRESULT Medium::saveSettings(settings::Medium &data)
3023{
3024 AutoCaller autoCaller(this);
3025 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3026
3027 /* we access mParent */
3028 AutoReadLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
3029
3030 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3031
3032 data.uuid = m->id;
3033 data.strLocation = m->strLocation;
3034 data.strFormat = m->strFormat;
3035
3036 /* optional, only for diffs, default is false */
3037 if (m->pParent)
3038 data.fAutoReset = m->autoReset;
3039 else
3040 data.fAutoReset = false;
3041
3042 /* optional */
3043 data.strDescription = m->strDescription;
3044
3045 /* optional properties */
3046 data.properties.clear();
3047 for (Data::PropertyMap::const_iterator it = m->properties.begin();
3048 it != m->properties.end();
3049 ++it)
3050 {
3051 /* only save properties that have non-default values */
3052 if (!it->second.isEmpty())
3053 {
3054 Utf8Str name = it->first;
3055 Utf8Str value = it->second;
3056 data.properties[name] = value;
3057 }
3058 }
3059
3060 /* only for base media */
3061 if (m->pParent.isNull())
3062 data.hdType = m->type;
3063
3064 /* save all children */
3065 for (MediaList::const_iterator it = getChildren().begin();
3066 it != getChildren().end();
3067 ++it)
3068 {
3069 settings::Medium med;
3070 HRESULT rc = (*it)->saveSettings(med);
3071 AssertComRCReturnRC(rc);
3072 data.llChildren.push_back(med);
3073 }
3074
3075 return S_OK;
3076}
3077
3078/**
3079 * Compares the location of this medium to the given location.
3080 *
3081 * The comparison takes the location details into account. For example, if the
3082 * location is a file in the host's filesystem, a case insensitive comparison
3083 * will be performed for case insensitive filesystems.
3084 *
3085 * @param aLocation Location to compare to (as is).
3086 * @param aResult Where to store the result of comparison: 0 if locations
3087 * are equal, 1 if this object's location is greater than
3088 * the specified location, and -1 otherwise.
3089 */
3090HRESULT Medium::compareLocationTo(const char *aLocation, int &aResult)
3091{
3092 AutoCaller autoCaller(this);
3093 AssertComRCReturnRC(autoCaller.rc());
3094
3095 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3096
3097 Utf8Str locationFull(m->strLocationFull);
3098
3099 /// @todo NEWMEDIA delegate the comparison to the backend?
3100
3101 if (m->formatObj->capabilities() & MediumFormatCapabilities_File)
3102 {
3103 Utf8Str location(aLocation);
3104
3105 /* For locations represented by files, append the default path if
3106 * only the name is given, and then get the full path. */
3107 if (!RTPathHavePath(aLocation))
3108 {
3109 location = Utf8StrFmt("%s%c%s",
3110 m->pVirtualBox->getDefaultHardDiskFolder().raw(),
3111 RTPATH_DELIMITER,
3112 aLocation);
3113 }
3114
3115 int vrc = m->pVirtualBox->calculateFullPath(location, location);
3116 if (RT_FAILURE(vrc))
3117 return setError(VBOX_E_FILE_ERROR,
3118 tr("Invalid medium storage file location '%s' (%Rrc)"),
3119 location.raw(),
3120 vrc);
3121
3122 aResult = RTPathCompare(locationFull.c_str(), location.c_str());
3123 }
3124 else
3125 aResult = locationFull.compare(aLocation);
3126
3127 return S_OK;
3128}
3129
3130/**
3131 * Constructs a medium lock list for this medium. The lock is not taken.
3132 *
3133 * @note Locks the medium tree for reading.
3134 *
3135 * @param fFailIfInaccessible If true, this fails with an error if a medium is inaccessible. If false,
3136 * inaccessible media are silently skipped and not locked (i.e. their state remains "Inaccessible");
3137 * this is necessary for a VM's removable media VM startup for which we do not want to fail.
3138 * @param fMediumLockWrite Whether to associate a write lock with this medium.
3139 * @param pToBeParent Medium which will become the parent of this medium.
3140 * @param mediumLockList Where to store the resulting list.
3141 */
3142HRESULT Medium::createMediumLockList(bool fFailIfInaccessible,
3143 bool fMediumLockWrite,
3144 Medium *pToBeParent,
3145 MediumLockList &mediumLockList)
3146{
3147 AutoCaller autoCaller(this);
3148 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3149
3150 HRESULT rc = S_OK;
3151
3152 /* we access parent medium objects */
3153 AutoReadLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
3154
3155 /* paranoid sanity checking if the medium has a to-be parent medium */
3156 if (pToBeParent)
3157 {
3158 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
3159 ComAssertRet(getParent().isNull(), E_FAIL);
3160 ComAssertRet(getChildren().size() == 0, E_FAIL);
3161 }
3162
3163 ErrorInfoKeeper eik;
3164 MultiResult mrc(S_OK);
3165
3166 ComObjPtr<Medium> pMedium = this;
3167 while (!pMedium.isNull())
3168 {
3169 // need write lock for RefreshState if medium is inaccessible
3170 AutoWriteLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
3171
3172 /* Accessibility check must be first, otherwise locking interferes
3173 * with getting the medium state. Lock lists are not created for
3174 * fun, and thus getting the medium status is no luxury. */
3175 MediumState_T mediumState = pMedium->getState();
3176 if (mediumState == MediumState_Inaccessible)
3177 {
3178 rc = pMedium->RefreshState(&mediumState);
3179 if (FAILED(rc)) return rc;
3180
3181 if (mediumState == MediumState_Inaccessible)
3182 {
3183 // ignore inaccessible ISO media and silently return S_OK,
3184 // otherwise VM startup (esp. restore) may fail without good reason
3185 if (!fFailIfInaccessible)
3186 return S_OK;
3187
3188 // otherwise report an error
3189 Bstr error;
3190 rc = pMedium->COMGETTER(LastAccessError)(error.asOutParam());
3191 if (FAILED(rc)) return rc;
3192
3193 /* collect multiple errors */
3194 eik.restore();
3195 Assert(!error.isEmpty());
3196 mrc = setError(E_FAIL,
3197 "%ls",
3198 error.raw());
3199 // error message will be something like
3200 // "Could not open the medium ... VD: error VERR_FILE_NOT_FOUND opening image file ... (VERR_FILE_NOT_FOUND).
3201 eik.fetch();
3202 }
3203 }
3204
3205 if (pMedium == this)
3206 mediumLockList.Prepend(pMedium, fMediumLockWrite);
3207 else
3208 mediumLockList.Prepend(pMedium, false);
3209
3210 pMedium = pMedium->getParent();
3211 if (pMedium.isNull() && pToBeParent)
3212 {
3213 pMedium = pToBeParent;
3214 pToBeParent = NULL;
3215 }
3216 }
3217
3218 return mrc;
3219}
3220
3221/**
3222 * Returns a preferred format for differencing media.
3223 */
3224Bstr Medium::preferredDiffFormat()
3225{
3226 Utf8Str strFormat;
3227
3228 AutoCaller autoCaller(this);
3229 AssertComRCReturn(autoCaller.rc(), strFormat);
3230
3231 /* m->strFormat is const, no need to lock */
3232 strFormat = m->strFormat;
3233
3234 /* check that our own format supports diffs */
3235 if (!(m->formatObj->capabilities() & MediumFormatCapabilities_Differencing))
3236 {
3237 /* use the default format if not */
3238 AutoReadLock propsLock(m->pVirtualBox->getSystemProperties() COMMA_LOCKVAL_SRC_POS);
3239 strFormat = m->pVirtualBox->getDefaultHardDiskFormat();
3240 }
3241
3242 return strFormat;
3243}
3244
3245/**
3246 * Returns the medium device type. Must have caller + locking!
3247 * @return
3248 */
3249DeviceType_T Medium::getDeviceType() const
3250{
3251 return m->devType;
3252}
3253
3254/**
3255 * Returns the medium type. Must have caller + locking!
3256 * @return
3257 */
3258MediumType_T Medium::getType() const
3259{
3260 return m->type;
3261}
3262
3263// private methods
3264////////////////////////////////////////////////////////////////////////////////
3265
3266/**
3267 * Returns a short version of the location attribute.
3268 *
3269 * @note Must be called from under this object's read or write lock.
3270 */
3271Utf8Str Medium::getName()
3272{
3273 Utf8Str name = RTPathFilename(m->strLocationFull.c_str());
3274 return name;
3275}
3276
3277/**
3278 * Sets the value of m->strLocation and calculates the value of m->strLocationFull.
3279 *
3280 * Treats non-FS-path locations specially, and prepends the default medium
3281 * folder if the given location string does not contain any path information
3282 * at all.
3283 *
3284 * Also, if the specified location is a file path that ends with '/' then the
3285 * file name part will be generated by this method automatically in the format
3286 * '{<uuid>}.<ext>' where <uuid> is a fresh UUID that this method will generate
3287 * and assign to this medium, and <ext> is the default extension for this
3288 * medium's storage format. Note that this procedure requires the media state to
3289 * be NotCreated and will return a failure otherwise.
3290 *
3291 * @param aLocation Location of the storage unit. If the location is a FS-path,
3292 * then it can be relative to the VirtualBox home directory.
3293 * @param aFormat Optional fallback format if it is an import and the format
3294 * cannot be determined.
3295 *
3296 * @note Must be called from under this object's write lock.
3297 */
3298HRESULT Medium::setLocation(const Utf8Str &aLocation, const Utf8Str &aFormat)
3299{
3300 AssertReturn(!aLocation.isEmpty(), E_FAIL);
3301
3302 AutoCaller autoCaller(this);
3303 AssertComRCReturnRC(autoCaller.rc());
3304
3305 /* formatObj may be null only when initializing from an existing path and
3306 * no format is known yet */
3307 AssertReturn( (!m->strFormat.isEmpty() && !m->formatObj.isNull())
3308 || ( autoCaller.state() == InInit
3309 && m->state != MediumState_NotCreated
3310 && m->id.isEmpty()
3311 && m->strFormat.isEmpty()
3312 && m->formatObj.isNull()),
3313 E_FAIL);
3314
3315 /* are we dealing with a new medium constructed using the existing
3316 * location? */
3317 bool isImport = m->strFormat.isEmpty();
3318
3319 if ( isImport
3320 || ( (m->formatObj->capabilities() & MediumFormatCapabilities_File)
3321 && !m->hostDrive))
3322 {
3323 Guid id;
3324
3325 Utf8Str location(aLocation);
3326
3327 if (m->state == MediumState_NotCreated)
3328 {
3329 /* must be a file (formatObj must be already known) */
3330 Assert(m->formatObj->capabilities() & MediumFormatCapabilities_File);
3331
3332 if (RTPathFilename(location.c_str()) == NULL)
3333 {
3334 /* no file name is given (either an empty string or ends with a
3335 * slash), generate a new UUID + file name if the state allows
3336 * this */
3337
3338 ComAssertMsgRet(!m->formatObj->fileExtensions().empty(),
3339 ("Must be at least one extension if it is MediumFormatCapabilities_File\n"),
3340 E_FAIL);
3341
3342 Bstr ext = m->formatObj->fileExtensions().front();
3343 ComAssertMsgRet(!ext.isEmpty(),
3344 ("Default extension must not be empty\n"),
3345 E_FAIL);
3346
3347 id.create();
3348
3349 location = Utf8StrFmt("%s{%RTuuid}.%ls",
3350 location.raw(), id.raw(), ext.raw());
3351 }
3352 }
3353
3354 /* append the default folder if no path is given */
3355 if (!RTPathHavePath(location.c_str()))
3356 location = Utf8StrFmt("%s%c%s",
3357 m->pVirtualBox->getDefaultHardDiskFolder().raw(),
3358 RTPATH_DELIMITER,
3359 location.raw());
3360
3361 /* get the full file name */
3362 Utf8Str locationFull;
3363 int vrc = m->pVirtualBox->calculateFullPath(location, locationFull);
3364 if (RT_FAILURE(vrc))
3365 return setError(VBOX_E_FILE_ERROR,
3366 tr("Invalid medium storage file location '%s' (%Rrc)"),
3367 location.raw(), vrc);
3368
3369 /* detect the backend from the storage unit if importing */
3370 if (isImport)
3371 {
3372 char *backendName = NULL;
3373
3374 /* is it a file? */
3375 {
3376 RTFILE file;
3377 vrc = RTFileOpen(&file, locationFull.c_str(), RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_NONE);
3378 if (RT_SUCCESS(vrc))
3379 RTFileClose(file);
3380 }
3381 if (RT_SUCCESS(vrc))
3382 {
3383 vrc = VDGetFormat(NULL, locationFull.c_str(), &backendName);
3384 }
3385 else if (vrc != VERR_FILE_NOT_FOUND && vrc != VERR_PATH_NOT_FOUND)
3386 {
3387 /* assume it's not a file, restore the original location */
3388 location = locationFull = aLocation;
3389 vrc = VDGetFormat(NULL, locationFull.c_str(), &backendName);
3390 }
3391
3392 if (RT_FAILURE(vrc))
3393 {
3394 if (vrc == VERR_FILE_NOT_FOUND || vrc == VERR_PATH_NOT_FOUND)
3395 return setError(VBOX_E_FILE_ERROR,
3396 tr("Could not find file for the medium '%s' (%Rrc)"),
3397 locationFull.raw(), vrc);
3398 else if (aFormat.isEmpty())
3399 return setError(VBOX_E_IPRT_ERROR,
3400 tr("Could not get the storage format of the medium '%s' (%Rrc)"),
3401 locationFull.raw(), vrc);
3402 else
3403 {
3404 HRESULT rc = setFormat(Bstr(aFormat));
3405 /* setFormat() must not fail since we've just used the backend so
3406 * the format object must be there */
3407 AssertComRCReturnRC(rc);
3408 }
3409 }
3410 else
3411 {
3412 ComAssertRet(backendName != NULL && *backendName != '\0', E_FAIL);
3413
3414 HRESULT rc = setFormat(Bstr(backendName));
3415 RTStrFree(backendName);
3416
3417 /* setFormat() must not fail since we've just used the backend so
3418 * the format object must be there */
3419 AssertComRCReturnRC(rc);
3420 }
3421 }
3422
3423 /* is it still a file? */
3424 if (m->formatObj->capabilities() & MediumFormatCapabilities_File)
3425 {
3426 m->strLocation = location;
3427 m->strLocationFull = locationFull;
3428
3429 if (m->state == MediumState_NotCreated)
3430 {
3431 /* assign a new UUID (this UUID will be used when calling
3432 * VDCreateBase/VDCreateDiff as a wanted UUID). Note that we
3433 * also do that if we didn't generate it to make sure it is
3434 * either generated by us or reset to null */
3435 unconst(m->id) = id;
3436 }
3437 }
3438 else
3439 {
3440 m->strLocation = locationFull;
3441 m->strLocationFull = locationFull;
3442 }
3443 }
3444 else
3445 {
3446 m->strLocation = aLocation;
3447 m->strLocationFull = aLocation;
3448 }
3449
3450 return S_OK;
3451}
3452
3453/**
3454 * Queries information from the medium.
3455 *
3456 * As a result of this call, the accessibility state and data members such as
3457 * size and description will be updated with the current information.
3458 *
3459 * @note This method may block during a system I/O call that checks storage
3460 * accessibility.
3461 *
3462 * @note Locks medium tree for reading and writing (for new diff media checked
3463 * for the first time). Locks mParent for reading. Locks this object for
3464 * writing.
3465 */
3466HRESULT Medium::queryInfo()
3467{
3468 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
3469
3470 if ( m->state != MediumState_Created
3471 && m->state != MediumState_Inaccessible
3472 && m->state != MediumState_LockedRead)
3473 return E_FAIL;
3474
3475 HRESULT rc = S_OK;
3476
3477 int vrc = VINF_SUCCESS;
3478
3479 /* check if a blocking queryInfo() call is in progress on some other thread,
3480 * and wait for it to finish if so instead of querying data ourselves */
3481 if (m->queryInfoRunning)
3482 {
3483 Assert( m->state == MediumState_LockedRead
3484 || m->state == MediumState_LockedWrite);
3485
3486 alock.leave();
3487 vrc = RTSemEventMultiWait(m->queryInfoSem, RT_INDEFINITE_WAIT);
3488 alock.enter();
3489
3490 AssertRC(vrc);
3491
3492 return S_OK;
3493 }
3494
3495 bool success = false;
3496 Utf8Str lastAccessError;
3497
3498 /* are we dealing with a new medium constructed using the existing
3499 * location? */
3500 bool isImport = m->id.isEmpty();
3501 unsigned uOpenFlags = VD_OPEN_FLAGS_INFO;
3502
3503 /* Note that we don't use VD_OPEN_FLAGS_READONLY when opening new
3504 * media because that would prevent necessary modifications
3505 * when opening media of some third-party formats for the first
3506 * time in VirtualBox (such as VMDK for which VDOpen() needs to
3507 * generate an UUID if it is missing) */
3508 if ( (m->hddOpenMode == OpenReadOnly)
3509 || !isImport
3510 )
3511 uOpenFlags |= VD_OPEN_FLAGS_READONLY;
3512
3513 /* Open shareable medium with the appropriate flags */
3514 if (m->type == MediumType_Shareable)
3515 uOpenFlags |= VD_OPEN_FLAGS_SHAREABLE;
3516
3517 /* Lock the medium, which makes the behavior much more consistent */
3518 if (uOpenFlags & (VD_OPEN_FLAGS_READONLY || VD_OPEN_FLAGS_SHAREABLE))
3519 rc = LockRead(NULL);
3520 else
3521 rc = LockWrite(NULL);
3522 if (FAILED(rc)) return rc;
3523
3524 /* Copies of the input state fields which are not read-only,
3525 * as we're dropping the lock. CAUTION: be extremely careful what
3526 * you do with the contents of this medium object, as you will
3527 * create races if there are concurrent changes. */
3528 Utf8Str format(m->strFormat);
3529 Utf8Str location(m->strLocationFull);
3530 ComObjPtr<MediumFormat> formatObj = m->formatObj;
3531
3532 /* "Output" values which can't be set because the lock isn't held
3533 * at the time the values are determined. */
3534 Guid mediumId = m->id;
3535 uint64_t mediumSize = 0;
3536 uint64_t mediumLogicalSize = 0;
3537
3538 /* leave the lock before a lengthy operation */
3539 vrc = RTSemEventMultiReset(m->queryInfoSem);
3540 AssertRCReturn(vrc, E_FAIL);
3541 m->queryInfoRunning = true;
3542 alock.leave();
3543
3544 try
3545 {
3546 /* skip accessibility checks for host drives */
3547 if (m->hostDrive)
3548 {
3549 success = true;
3550 throw S_OK;
3551 }
3552
3553 PVBOXHDD hdd;
3554 vrc = VDCreate(m->vdDiskIfaces, &hdd);
3555 ComAssertRCThrow(vrc, E_FAIL);
3556
3557 try
3558 {
3559 /** @todo This kind of opening of media is assuming that diff
3560 * media can be opened as base media. Should be documented that
3561 * it must work for all medium format backends. */
3562 vrc = VDOpen(hdd,
3563 format.c_str(),
3564 location.c_str(),
3565 uOpenFlags,
3566 m->vdDiskIfaces);
3567 if (RT_FAILURE(vrc))
3568 {
3569 lastAccessError = Utf8StrFmt(tr("Could not open the medium '%s'%s"),
3570 location.c_str(), vdError(vrc).c_str());
3571 throw S_OK;
3572 }
3573
3574 if (formatObj->capabilities() & MediumFormatCapabilities_Uuid)
3575 {
3576 /* Modify the UUIDs if necessary. The associated fields are
3577 * not modified by other code, so no need to copy. */
3578 if (m->setImageId)
3579 {
3580 vrc = VDSetUuid(hdd, 0, m->imageId);
3581 ComAssertRCThrow(vrc, E_FAIL);
3582 }
3583 if (m->setParentId)
3584 {
3585 vrc = VDSetParentUuid(hdd, 0, m->parentId);
3586 ComAssertRCThrow(vrc, E_FAIL);
3587 }
3588 /* zap the information, these are no long-term members */
3589 m->setImageId = false;
3590 unconst(m->imageId).clear();
3591 m->setParentId = false;
3592 unconst(m->parentId).clear();
3593
3594 /* check the UUID */
3595 RTUUID uuid;
3596 vrc = VDGetUuid(hdd, 0, &uuid);
3597 ComAssertRCThrow(vrc, E_FAIL);
3598
3599 if (isImport)
3600 {
3601 mediumId = uuid;
3602
3603 if (mediumId.isEmpty() && (m->hddOpenMode == OpenReadOnly))
3604 // only when importing a VDMK that has no UUID, create one in memory
3605 mediumId.create();
3606 }
3607 else
3608 {
3609 Assert(!mediumId.isEmpty());
3610
3611 if (mediumId != uuid)
3612 {
3613 lastAccessError = Utf8StrFmt(
3614 tr("UUID {%RTuuid} of the medium '%s' does not match the value {%RTuuid} stored in the media registry ('%s')"),
3615 &uuid,
3616 location.c_str(),
3617 mediumId.raw(),
3618 m->pVirtualBox->settingsFilePath().c_str());
3619 throw S_OK;
3620 }
3621 }
3622 }
3623 else
3624 {
3625 /* the backend does not support storing UUIDs within the
3626 * underlying storage so use what we store in XML */
3627
3628 /* generate an UUID for an imported UUID-less medium */
3629 if (isImport)
3630 {
3631 if (m->setImageId)
3632 mediumId = m->imageId;
3633 else
3634 mediumId.create();
3635 }
3636 }
3637
3638 /* get the medium variant */
3639 unsigned uImageFlags;
3640 vrc = VDGetImageFlags(hdd, 0, &uImageFlags);
3641 ComAssertRCThrow(vrc, E_FAIL);
3642 m->variant = (MediumVariant_T)uImageFlags;
3643
3644 /* check/get the parent uuid and update corresponding state */
3645 if (uImageFlags & VD_IMAGE_FLAGS_DIFF)
3646 {
3647 RTUUID parentId;
3648 vrc = VDGetParentUuid(hdd, 0, &parentId);
3649 ComAssertRCThrow(vrc, E_FAIL);
3650
3651 if (isImport)
3652 {
3653 /* the parent must be known to us. Note that we freely
3654 * call locking methods of mVirtualBox and parent, as all
3655 * relevant locks must be already held. There may be no
3656 * concurrent access to the just opened medium on other
3657 * threads yet (and init() will fail if this method reports
3658 * MediumState_Inaccessible) */
3659
3660 Guid id = parentId;
3661 ComObjPtr<Medium> pParent;
3662 rc = m->pVirtualBox->findHardDisk(&id, NULL,
3663 false /* aSetError */,
3664 &pParent);
3665 if (FAILED(rc))
3666 {
3667 lastAccessError = Utf8StrFmt(
3668 tr("Parent medium with UUID {%RTuuid} of the medium '%s' is not found in the media registry ('%s')"),
3669 &parentId, location.c_str(),
3670 m->pVirtualBox->settingsFilePath().c_str());
3671 throw S_OK;
3672 }
3673
3674 /* we set mParent & children() */
3675 AutoWriteLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
3676
3677 Assert(m->pParent.isNull());
3678 m->pParent = pParent;
3679 m->pParent->m->llChildren.push_back(this);
3680 }
3681 else
3682 {
3683 /* we access mParent */
3684 AutoReadLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
3685
3686 /* check that parent UUIDs match. Note that there's no need
3687 * for the parent's AutoCaller (our lifetime is bound to
3688 * it) */
3689
3690 if (m->pParent.isNull())
3691 {
3692 lastAccessError = Utf8StrFmt(
3693 tr("Medium type of '%s' is differencing but it is not associated with any parent medium in the media registry ('%s')"),
3694 location.c_str(),
3695 m->pVirtualBox->settingsFilePath().c_str());
3696 throw S_OK;
3697 }
3698
3699 AutoReadLock parentLock(m->pParent COMMA_LOCKVAL_SRC_POS);
3700 if ( m->pParent->getState() != MediumState_Inaccessible
3701 && m->pParent->getId() != parentId)
3702 {
3703 lastAccessError = Utf8StrFmt(
3704 tr("Parent UUID {%RTuuid} of the medium '%s' does not match UUID {%RTuuid} of its parent medium stored in the media registry ('%s')"),
3705 &parentId, location.c_str(),
3706 m->pParent->getId().raw(),
3707 m->pVirtualBox->settingsFilePath().c_str());
3708 throw S_OK;
3709 }
3710
3711 /// @todo NEWMEDIA what to do if the parent is not
3712 /// accessible while the diff is? Probably nothing. The
3713 /// real code will detect the mismatch anyway.
3714 }
3715 }
3716
3717 mediumSize = VDGetFileSize(hdd, 0);
3718 mediumLogicalSize = VDGetSize(hdd, 0) / _1M;
3719
3720 success = true;
3721 }
3722 catch (HRESULT aRC)
3723 {
3724 rc = aRC;
3725 }
3726
3727 VDDestroy(hdd);
3728
3729 }
3730 catch (HRESULT aRC)
3731 {
3732 rc = aRC;
3733 }
3734
3735 alock.enter();
3736
3737 if (isImport)
3738 unconst(m->id) = mediumId;
3739
3740 if (success)
3741 {
3742 m->size = mediumSize;
3743 m->logicalSize = mediumLogicalSize;
3744 m->strLastAccessError.setNull();
3745 }
3746 else
3747 {
3748 m->strLastAccessError = lastAccessError;
3749 LogWarningFunc(("'%s' is not accessible (error='%s', rc=%Rhrc, vrc=%Rrc)\n",
3750 location.c_str(), m->strLastAccessError.c_str(),
3751 rc, vrc));
3752 }
3753
3754 /* inform other callers if there are any */
3755 RTSemEventMultiSignal(m->queryInfoSem);
3756 m->queryInfoRunning = false;
3757
3758 /* Set the proper state according to the result of the check */
3759 if (success)
3760 m->preLockState = MediumState_Created;
3761 else
3762 m->preLockState = MediumState_Inaccessible;
3763
3764 if (uOpenFlags & (VD_OPEN_FLAGS_READONLY || VD_OPEN_FLAGS_SHAREABLE))
3765 rc = UnlockRead(NULL);
3766 else
3767 rc = UnlockWrite(NULL);
3768 if (FAILED(rc)) return rc;
3769
3770 return rc;
3771}
3772
3773/**
3774 * Sets the extended error info according to the current media state.
3775 *
3776 * @note Must be called from under this object's write or read lock.
3777 */
3778HRESULT Medium::setStateError()
3779{
3780 HRESULT rc = E_FAIL;
3781
3782 switch (m->state)
3783 {
3784 case MediumState_NotCreated:
3785 {
3786 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
3787 tr("Storage for the medium '%s' is not created"),
3788 m->strLocationFull.raw());
3789 break;
3790 }
3791 case MediumState_Created:
3792 {
3793 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
3794 tr("Storage for the medium '%s' is already created"),
3795 m->strLocationFull.raw());
3796 break;
3797 }
3798 case MediumState_LockedRead:
3799 {
3800 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
3801 tr("Medium '%s' is locked for reading by another task"),
3802 m->strLocationFull.raw());
3803 break;
3804 }
3805 case MediumState_LockedWrite:
3806 {
3807 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
3808 tr("Medium '%s' is locked for writing by another task"),
3809 m->strLocationFull.raw());
3810 break;
3811 }
3812 case MediumState_Inaccessible:
3813 {
3814 /* be in sync with Console::powerUpThread() */
3815 if (!m->strLastAccessError.isEmpty())
3816 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
3817 tr("Medium '%s' is not accessible. %s"),
3818 m->strLocationFull.raw(), m->strLastAccessError.c_str());
3819 else
3820 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
3821 tr("Medium '%s' is not accessible"),
3822 m->strLocationFull.raw());
3823 break;
3824 }
3825 case MediumState_Creating:
3826 {
3827 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
3828 tr("Storage for the medium '%s' is being created"),
3829 m->strLocationFull.raw());
3830 break;
3831 }
3832 case MediumState_Deleting:
3833 {
3834 rc = setError(VBOX_E_INVALID_OBJECT_STATE,
3835 tr("Storage for the medium '%s' is being deleted"),
3836 m->strLocationFull.raw());
3837 break;
3838 }
3839 default:
3840 {
3841 AssertFailed();
3842 break;
3843 }
3844 }
3845
3846 return rc;
3847}
3848
3849/**
3850 * Implementation for the public Medium::Close() with the exception of calling
3851 * VirtualBox::saveSettings(), in case someone wants to call this for several
3852 * media.
3853 *
3854 * After this returns with success, uninit() has been called on the medium, and
3855 * the object is no longer usable ("not ready" state).
3856 *
3857 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
3858 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
3859 * This only works in "wait" mode; otherwise saveSettings gets called automatically by the thread that was created,
3860 * and this parameter is ignored.
3861 * @param autoCaller AutoCaller instance which must have been created on the caller's stack for this medium. This gets released here
3862 * upon which the Medium instance gets uninitialized.
3863 * @return
3864 */
3865HRESULT Medium::close(bool *pfNeedsSaveSettings, AutoCaller &autoCaller)
3866{
3867 // we're accessing parent/child and backrefs, so lock the tree first, then ourselves
3868 AutoMultiWriteLock2 multilock(&m->pVirtualBox->getMediaTreeLockHandle(),
3869 this->lockHandle()
3870 COMMA_LOCKVAL_SRC_POS);
3871
3872 bool wasCreated = true;
3873
3874 switch (m->state)
3875 {
3876 case MediumState_NotCreated:
3877 wasCreated = false;
3878 break;
3879 case MediumState_Created:
3880 case MediumState_Inaccessible:
3881 break;
3882 default:
3883 return setStateError();
3884 }
3885
3886 if (m->backRefs.size() != 0)
3887 return setError(VBOX_E_OBJECT_IN_USE,
3888 tr("Medium '%s' is attached to %d virtual machines"),
3889 m->strLocationFull.raw(), m->backRefs.size());
3890
3891 // perform extra media-dependent close checks
3892 HRESULT rc = canClose();
3893 if (FAILED(rc)) return rc;
3894
3895 if (wasCreated)
3896 {
3897 // remove from the list of known media before performing actual
3898 // uninitialization (to keep the media registry consistent on
3899 // failure to do so)
3900 rc = unregisterWithVirtualBox(pfNeedsSaveSettings);
3901 if (FAILED(rc)) return rc;
3902 }
3903
3904 // leave the AutoCaller, as otherwise uninit() will simply hang
3905 autoCaller.release();
3906
3907 // Keep the locks held until after uninit, as otherwise the consistency
3908 // of the medium tree cannot be guaranteed.
3909 uninit();
3910
3911 return rc;
3912}
3913
3914/**
3915 * Deletes the medium storage unit.
3916 *
3917 * If @a aProgress is not NULL but the object it points to is @c null then a new
3918 * progress object will be created and assigned to @a *aProgress on success,
3919 * otherwise the existing progress object is used. If Progress is NULL, then no
3920 * progress object is created/used at all.
3921 *
3922 * When @a aWait is @c false, this method will create a thread to perform the
3923 * delete operation asynchronously and will return immediately. Otherwise, it
3924 * will perform the operation on the calling thread and will not return to the
3925 * caller until the operation is completed. Note that @a aProgress cannot be
3926 * NULL when @a aWait is @c false (this method will assert in this case).
3927 *
3928 * @param aProgress Where to find/store a Progress object to track operation
3929 * completion.
3930 * @param aWait @c true if this method should block instead of creating
3931 * an asynchronous thread.
3932 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
3933 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
3934 * This only works in "wait" mode; otherwise saveSettings gets called automatically by the thread that was created,
3935 * and this parameter is ignored.
3936 *
3937 * @note Locks mVirtualBox and this object for writing. Locks medium tree for
3938 * writing.
3939 */
3940HRESULT Medium::deleteStorage(ComObjPtr<Progress> *aProgress,
3941 bool aWait,
3942 bool *pfNeedsSaveSettings)
3943{
3944 AssertReturn(aProgress != NULL || aWait == true, E_FAIL);
3945
3946 AutoCaller autoCaller(this);
3947 if (FAILED(autoCaller.rc())) return autoCaller.rc();
3948
3949 HRESULT rc = S_OK;
3950 ComObjPtr<Progress> pProgress;
3951 Medium::Task *pTask = NULL;
3952
3953 try
3954 {
3955 /* we're accessing the media tree, and canClose() needs it too */
3956 AutoMultiWriteLock2 multilock(&m->pVirtualBox->getMediaTreeLockHandle(),
3957 this->lockHandle()
3958 COMMA_LOCKVAL_SRC_POS);
3959 LogFlowThisFunc(("aWait=%RTbool locationFull=%s\n", aWait, getLocationFull().c_str() ));
3960
3961 if ( !(m->formatObj->capabilities() & ( MediumFormatCapabilities_CreateDynamic
3962 | MediumFormatCapabilities_CreateFixed)))
3963 throw setError(VBOX_E_NOT_SUPPORTED,
3964 tr("Medium format '%s' does not support storage deletion"),
3965 m->strFormat.raw());
3966
3967 /* Note that we are fine with Inaccessible state too: a) for symmetry
3968 * with create calls and b) because it doesn't really harm to try, if
3969 * it is really inaccessible, the delete operation will fail anyway.
3970 * Accepting Inaccessible state is especially important because all
3971 * registered media are initially Inaccessible upon VBoxSVC startup
3972 * until COMGETTER(RefreshState) is called. Accept Deleting state
3973 * because some callers need to put the medium in this state early
3974 * to prevent races. */
3975 switch (m->state)
3976 {
3977 case MediumState_Created:
3978 case MediumState_Deleting:
3979 case MediumState_Inaccessible:
3980 break;
3981 default:
3982 throw setStateError();
3983 }
3984
3985 if (m->backRefs.size() != 0)
3986 {
3987 Utf8Str strMachines;
3988 for (BackRefList::const_iterator it = m->backRefs.begin();
3989 it != m->backRefs.end();
3990 ++it)
3991 {
3992 const BackRef &b = *it;
3993 if (strMachines.length())
3994 strMachines.append(", ");
3995 strMachines.append(b.machineId.toString().c_str());
3996 }
3997#ifdef DEBUG
3998 dumpBackRefs();
3999#endif
4000 throw setError(VBOX_E_OBJECT_IN_USE,
4001 tr("Cannot delete storage: medium '%s' is still attached to the following %d virtual machine(s): %s"),
4002 m->strLocationFull.c_str(),
4003 m->backRefs.size(),
4004 strMachines.c_str());
4005 }
4006
4007 rc = canClose();
4008 if (FAILED(rc))
4009 throw rc;
4010
4011 /* go to Deleting state, so that the medium is not actually locked */
4012 if (m->state != MediumState_Deleting)
4013 {
4014 rc = markForDeletion();
4015 if (FAILED(rc))
4016 throw rc;
4017 }
4018
4019 /* Build the medium lock list. */
4020 MediumLockList *pMediumLockList(new MediumLockList());
4021 rc = createMediumLockList(true /* fFailIfInaccessible */,
4022 true /* fMediumLockWrite */,
4023 NULL,
4024 *pMediumLockList);
4025 if (FAILED(rc))
4026 {
4027 delete pMediumLockList;
4028 throw rc;
4029 }
4030
4031 rc = pMediumLockList->Lock();
4032 if (FAILED(rc))
4033 {
4034 delete pMediumLockList;
4035 throw setError(rc,
4036 tr("Failed to lock media when deleting '%s'"),
4037 getLocationFull().raw());
4038 }
4039
4040 /* try to remove from the list of known media before performing
4041 * actual deletion (we favor the consistency of the media registry
4042 * which would have been broken if unregisterWithVirtualBox() failed
4043 * after we successfully deleted the storage) */
4044 rc = unregisterWithVirtualBox(pfNeedsSaveSettings);
4045 if (FAILED(rc))
4046 throw rc;
4047 // no longer need lock
4048 multilock.release();
4049
4050 if (aProgress != NULL)
4051 {
4052 /* use the existing progress object... */
4053 pProgress = *aProgress;
4054
4055 /* ...but create a new one if it is null */
4056 if (pProgress.isNull())
4057 {
4058 pProgress.createObject();
4059 rc = pProgress->init(m->pVirtualBox,
4060 static_cast<IMedium*>(this),
4061 BstrFmt(tr("Deleting medium storage unit '%s'"), m->strLocationFull.raw()),
4062 FALSE /* aCancelable */);
4063 if (FAILED(rc))
4064 throw rc;
4065 }
4066 }
4067
4068 /* setup task object to carry out the operation sync/async */
4069 pTask = new Medium::DeleteTask(this, pProgress, pMediumLockList);
4070 rc = pTask->rc();
4071 AssertComRC(rc);
4072 if (FAILED(rc))
4073 throw rc;
4074 }
4075 catch (HRESULT aRC) { rc = aRC; }
4076
4077 if (SUCCEEDED(rc))
4078 {
4079 if (aWait)
4080 rc = runNow(pTask, NULL /* pfNeedsSaveSettings*/);
4081 else
4082 rc = startThread(pTask);
4083
4084 if (SUCCEEDED(rc) && aProgress != NULL)
4085 *aProgress = pProgress;
4086
4087 }
4088 else
4089 {
4090 if (pTask)
4091 delete pTask;
4092
4093 /* Undo deleting state if necessary. */
4094 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
4095 unmarkForDeletion();
4096 }
4097
4098 return rc;
4099}
4100
4101/**
4102 * Mark a medium for deletion.
4103 *
4104 * @note Caller must hold the write lock on this medium!
4105 */
4106HRESULT Medium::markForDeletion()
4107{
4108 ComAssertRet(this->lockHandle()->isWriteLockOnCurrentThread(), E_FAIL);
4109 switch (m->state)
4110 {
4111 case MediumState_Created:
4112 case MediumState_Inaccessible:
4113 m->preLockState = m->state;
4114 m->state = MediumState_Deleting;
4115 return S_OK;
4116 default:
4117 return setStateError();
4118 }
4119}
4120
4121/**
4122 * Removes the "mark for deletion".
4123 *
4124 * @note Caller must hold the write lock on this medium!
4125 */
4126HRESULT Medium::unmarkForDeletion()
4127{
4128 ComAssertRet(this->lockHandle()->isWriteLockOnCurrentThread(), E_FAIL);
4129 switch (m->state)
4130 {
4131 case MediumState_Deleting:
4132 m->state = m->preLockState;
4133 return S_OK;
4134 default:
4135 return setStateError();
4136 }
4137}
4138
4139/**
4140 * Mark a medium for deletion which is in locked state.
4141 *
4142 * @note Caller must hold the write lock on this medium!
4143 */
4144HRESULT Medium::markLockedForDeletion()
4145{
4146 ComAssertRet(this->lockHandle()->isWriteLockOnCurrentThread(), E_FAIL);
4147 if ( ( m->state == MediumState_LockedRead
4148 || m->state == MediumState_LockedWrite)
4149 && m->preLockState == MediumState_Created)
4150 {
4151 m->preLockState = MediumState_Deleting;
4152 return S_OK;
4153 }
4154 else
4155 return setStateError();
4156}
4157
4158/**
4159 * Removes the "mark for deletion" for a medium in locked state.
4160 *
4161 * @note Caller must hold the write lock on this medium!
4162 */
4163HRESULT Medium::unmarkLockedForDeletion()
4164{
4165 ComAssertRet(this->lockHandle()->isWriteLockOnCurrentThread(), E_FAIL);
4166 if ( ( m->state == MediumState_LockedRead
4167 || m->state == MediumState_LockedWrite)
4168 && m->preLockState == MediumState_Deleting)
4169 {
4170 m->preLockState = MediumState_Created;
4171 return S_OK;
4172 }
4173 else
4174 return setStateError();
4175}
4176
4177/**
4178 * Creates a new differencing storage unit using the format of the given target
4179 * medium and the location. Note that @c aTarget must be NotCreated.
4180 *
4181 * The @a aMediumLockList parameter contains the associated medium lock list,
4182 * which must be in locked state. If @a aWait is @c true then the caller is
4183 * responsible for unlocking.
4184 *
4185 * If @a aProgress is not NULL but the object it points to is @c null then a
4186 * new progress object will be created and assigned to @a *aProgress on
4187 * success, otherwise the existing progress object is used. If @a aProgress is
4188 * NULL, then no progress object is created/used at all.
4189 *
4190 * When @a aWait is @c false, this method will create a thread to perform the
4191 * create operation asynchronously and will return immediately. Otherwise, it
4192 * will perform the operation on the calling thread and will not return to the
4193 * caller until the operation is completed. Note that @a aProgress cannot be
4194 * NULL when @a aWait is @c false (this method will assert in this case).
4195 *
4196 * @param aTarget Target medium.
4197 * @param aVariant Precise medium variant to create.
4198 * @param aMediumLockList List of media which should be locked.
4199 * @param aProgress Where to find/store a Progress object to track
4200 * operation completion.
4201 * @param aWait @c true if this method should block instead of
4202 * creating an asynchronous thread.
4203 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been
4204 * initialized to false and that will be set to true
4205 * by this function if the caller should invoke
4206 * VirtualBox::saveSettings() because the global
4207 * settings have changed. This only works in "wait"
4208 * mode; otherwise saveSettings is called
4209 * automatically by the thread that was created,
4210 * and this parameter is ignored.
4211 *
4212 * @note Locks this object and @a aTarget for writing.
4213 */
4214HRESULT Medium::createDiffStorage(ComObjPtr<Medium> &aTarget,
4215 MediumVariant_T aVariant,
4216 MediumLockList *aMediumLockList,
4217 ComObjPtr<Progress> *aProgress,
4218 bool aWait,
4219 bool *pfNeedsSaveSettings)
4220{
4221 AssertReturn(!aTarget.isNull(), E_FAIL);
4222 AssertReturn(aMediumLockList, E_FAIL);
4223 AssertReturn(aProgress != NULL || aWait == true, E_FAIL);
4224
4225 AutoCaller autoCaller(this);
4226 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4227
4228 AutoCaller targetCaller(aTarget);
4229 if (FAILED(targetCaller.rc())) return targetCaller.rc();
4230
4231 HRESULT rc = S_OK;
4232 ComObjPtr<Progress> pProgress;
4233 Medium::Task *pTask = NULL;
4234
4235 try
4236 {
4237 AutoMultiWriteLock2 alock(this, aTarget COMMA_LOCKVAL_SRC_POS);
4238
4239 ComAssertThrow( m->type != MediumType_Writethrough
4240 && m->type != MediumType_Shareable, E_FAIL);
4241 ComAssertThrow(m->state == MediumState_LockedRead, E_FAIL);
4242
4243 if (aTarget->m->state != MediumState_NotCreated)
4244 throw aTarget->setStateError();
4245
4246 /* Check that the medium is not attached to the current state of
4247 * any VM referring to it. */
4248 for (BackRefList::const_iterator it = m->backRefs.begin();
4249 it != m->backRefs.end();
4250 ++it)
4251 {
4252 if (it->fInCurState)
4253 {
4254 /* Note: when a VM snapshot is being taken, all normal media
4255 * attached to the VM in the current state will be, as an
4256 * exception, also associated with the snapshot which is about
4257 * to create (see SnapshotMachine::init()) before deassociating
4258 * them from the current state (which takes place only on
4259 * success in Machine::fixupHardDisks()), so that the size of
4260 * snapshotIds will be 1 in this case. The extra condition is
4261 * used to filter out this legal situation. */
4262 if (it->llSnapshotIds.size() == 0)
4263 throw setError(VBOX_E_INVALID_OBJECT_STATE,
4264 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"),
4265 m->strLocationFull.raw(), it->machineId.raw());
4266
4267 Assert(it->llSnapshotIds.size() == 1);
4268 }
4269 }
4270
4271 if (aProgress != NULL)
4272 {
4273 /* use the existing progress object... */
4274 pProgress = *aProgress;
4275
4276 /* ...but create a new one if it is null */
4277 if (pProgress.isNull())
4278 {
4279 pProgress.createObject();
4280 rc = pProgress->init(m->pVirtualBox,
4281 static_cast<IMedium*>(this),
4282 BstrFmt(tr("Creating differencing medium storage unit '%s'"), aTarget->m->strLocationFull.raw()),
4283 TRUE /* aCancelable */);
4284 if (FAILED(rc))
4285 throw rc;
4286 }
4287 }
4288
4289 /* setup task object to carry out the operation sync/async */
4290 pTask = new Medium::CreateDiffTask(this, pProgress, aTarget, aVariant,
4291 aMediumLockList,
4292 aWait /* fKeepMediumLockList */);
4293 rc = pTask->rc();
4294 AssertComRC(rc);
4295 if (FAILED(rc))
4296 throw rc;
4297
4298 /* register a task (it will deregister itself when done) */
4299 ++m->numCreateDiffTasks;
4300 Assert(m->numCreateDiffTasks != 0); /* overflow? */
4301
4302 aTarget->m->state = MediumState_Creating;
4303 }
4304 catch (HRESULT aRC) { rc = aRC; }
4305
4306 if (SUCCEEDED(rc))
4307 {
4308 if (aWait)
4309 rc = runNow(pTask, pfNeedsSaveSettings);
4310 else
4311 rc = startThread(pTask);
4312
4313 if (SUCCEEDED(rc) && aProgress != NULL)
4314 *aProgress = pProgress;
4315 }
4316 else if (pTask != NULL)
4317 delete pTask;
4318
4319 return rc;
4320}
4321
4322/**
4323 * Prepares this (source) medium, target medium and all intermediate media
4324 * for the merge operation.
4325 *
4326 * This method is to be called prior to calling the #mergeTo() to perform
4327 * necessary consistency checks and place involved media to appropriate
4328 * states. If #mergeTo() is not called or fails, the state modifications
4329 * performed by this method must be undone by #cancelMergeTo().
4330 *
4331 * See #mergeTo() for more information about merging.
4332 *
4333 * @param pTarget Target medium.
4334 * @param aMachineId Allowed machine attachment. NULL means do not check.
4335 * @param aSnapshotId Allowed snapshot attachment. NULL or empty UUID means
4336 * do not check.
4337 * @param fLockMedia Flag whether to lock the medium lock list or not.
4338 * If set to false and the medium lock list locking fails
4339 * later you must call #cancelMergeTo().
4340 * @param fMergeForward Resulting merge direction (out).
4341 * @param pParentForTarget New parent for target medium after merge (out).
4342 * @param aChildrenToReparent List of children of the source which will have
4343 * to be reparented to the target after merge (out).
4344 * @param aMediumLockList Medium locking information (out).
4345 *
4346 * @note Locks medium tree for reading. Locks this object, aTarget and all
4347 * intermediate media for writing.
4348 */
4349HRESULT Medium::prepareMergeTo(const ComObjPtr<Medium> &pTarget,
4350 const Guid *aMachineId,
4351 const Guid *aSnapshotId,
4352 bool fLockMedia,
4353 bool &fMergeForward,
4354 ComObjPtr<Medium> &pParentForTarget,
4355 MediaList &aChildrenToReparent,
4356 MediumLockList * &aMediumLockList)
4357{
4358 AssertReturn(pTarget != NULL, E_FAIL);
4359 AssertReturn(pTarget != this, E_FAIL);
4360
4361 AutoCaller autoCaller(this);
4362 AssertComRCReturnRC(autoCaller.rc());
4363
4364 AutoCaller targetCaller(pTarget);
4365 AssertComRCReturnRC(targetCaller.rc());
4366
4367 HRESULT rc = S_OK;
4368 fMergeForward = false;
4369 pParentForTarget.setNull();
4370 aChildrenToReparent.clear();
4371 Assert(aMediumLockList == NULL);
4372 aMediumLockList = NULL;
4373
4374 try
4375 {
4376 // locking: we need the tree lock first because we access parent pointers
4377 AutoReadLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
4378
4379 /* more sanity checking and figuring out the merge direction */
4380 ComObjPtr<Medium> pMedium = getParent();
4381 while (!pMedium.isNull() && pMedium != pTarget)
4382 pMedium = pMedium->getParent();
4383 if (pMedium == pTarget)
4384 fMergeForward = false;
4385 else
4386 {
4387 pMedium = pTarget->getParent();
4388 while (!pMedium.isNull() && pMedium != this)
4389 pMedium = pMedium->getParent();
4390 if (pMedium == this)
4391 fMergeForward = true;
4392 else
4393 {
4394 Utf8Str tgtLoc;
4395 {
4396 AutoReadLock alock(pTarget COMMA_LOCKVAL_SRC_POS);
4397 tgtLoc = pTarget->getLocationFull();
4398 }
4399
4400 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4401 throw setError(VBOX_E_INVALID_OBJECT_STATE,
4402 tr("Media '%s' and '%s' are unrelated"),
4403 m->strLocationFull.raw(), tgtLoc.raw());
4404 }
4405 }
4406
4407 /* Build the lock list. */
4408 aMediumLockList = new MediumLockList();
4409 if (fMergeForward)
4410 rc = pTarget->createMediumLockList(true /* fFailIfInaccessible */,
4411 true /* fMediumLockWrite */,
4412 NULL,
4413 *aMediumLockList);
4414 else
4415 rc = createMediumLockList(true /* fFailIfInaccessible */,
4416 false /* fMediumLockWrite */,
4417 NULL,
4418 *aMediumLockList);
4419 if (FAILED(rc))
4420 throw rc;
4421
4422 /* Sanity checking, must be after lock list creation as it depends on
4423 * valid medium states. The medium objects must be accessible. Only
4424 * do this if immediate locking is requested, otherwise it fails when
4425 * we construct a medium lock list for an already running VM. Snapshot
4426 * deletion uses this to simplify its life. */
4427 if (fLockMedia)
4428 {
4429 {
4430 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4431 if (m->state != MediumState_Created)
4432 throw setStateError();
4433 }
4434 {
4435 AutoReadLock alock(pTarget COMMA_LOCKVAL_SRC_POS);
4436 if (pTarget->m->state != MediumState_Created)
4437 throw pTarget->setStateError();
4438 }
4439 }
4440
4441 /* check medium attachment and other sanity conditions */
4442 if (fMergeForward)
4443 {
4444 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4445 if (getChildren().size() > 1)
4446 {
4447 throw setError(VBOX_E_INVALID_OBJECT_STATE,
4448 tr("Medium '%s' involved in the merge operation has more than one child medium (%d)"),
4449 m->strLocationFull.raw(), getChildren().size());
4450 }
4451 /* One backreference is only allowed if the machine ID is not empty
4452 * and it matches the machine the medium is attached to (including
4453 * the snapshot ID if not empty). */
4454 if ( m->backRefs.size() != 0
4455 && ( !aMachineId
4456 || m->backRefs.size() != 1
4457 || aMachineId->isEmpty()
4458 || *getFirstMachineBackrefId() != *aMachineId
4459 || ( (!aSnapshotId || !aSnapshotId->isEmpty())
4460 && *getFirstMachineBackrefSnapshotId() != *aSnapshotId)))
4461 throw setError(VBOX_E_OBJECT_IN_USE,
4462 tr("Medium '%s' is attached to %d virtual machines"),
4463 m->strLocationFull.raw(), m->backRefs.size());
4464 if (m->type == MediumType_Immutable)
4465 throw setError(VBOX_E_INVALID_OBJECT_STATE,
4466 tr("Medium '%s' is immutable"),
4467 m->strLocationFull.raw());
4468 }
4469 else
4470 {
4471 AutoReadLock alock(pTarget COMMA_LOCKVAL_SRC_POS);
4472 if (pTarget->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 pTarget->m->strLocationFull.raw(),
4477 pTarget->getChildren().size());
4478 }
4479 if (pTarget->m->type == MediumType_Immutable)
4480 throw setError(VBOX_E_INVALID_OBJECT_STATE,
4481 tr("Medium '%s' is immutable"),
4482 pTarget->m->strLocationFull.raw());
4483 }
4484 ComObjPtr<Medium> pLast(fMergeForward ? (Medium *)pTarget : this);
4485 ComObjPtr<Medium> pLastIntermediate = pLast->getParent();
4486 for (pLast = pLastIntermediate;
4487 !pLast.isNull() && pLast != pTarget && pLast != this;
4488 pLast = pLast->getParent())
4489 {
4490 AutoReadLock alock(pLast COMMA_LOCKVAL_SRC_POS);
4491 if (pLast->getChildren().size() > 1)
4492 {
4493 throw setError(VBOX_E_OBJECT_IN_USE,
4494 tr("Medium '%s' involved in the merge operation has more than one child medium (%d)"),
4495 pLast->m->strLocationFull.raw(),
4496 pLast->getChildren().size());
4497 }
4498 if (pLast->m->backRefs.size() != 0)
4499 throw setError(VBOX_E_OBJECT_IN_USE,
4500 tr("Medium '%s' is attached to %d virtual machines"),
4501 pLast->m->strLocationFull.raw(),
4502 pLast->m->backRefs.size());
4503
4504 }
4505
4506 /* Update medium states appropriately */
4507 if (m->state == MediumState_Created)
4508 {
4509 rc = markForDeletion();
4510 if (FAILED(rc))
4511 throw rc;
4512 }
4513 else
4514 {
4515 if (fLockMedia)
4516 throw setStateError();
4517 else if ( m->state == MediumState_LockedWrite
4518 || m->state == MediumState_LockedRead)
4519 {
4520 /* Either mark it for deletiion in locked state or allow
4521 * others to have done so. */
4522 if (m->preLockState == MediumState_Created)
4523 markLockedForDeletion();
4524 else if (m->preLockState != MediumState_Deleting)
4525 throw setStateError();
4526 }
4527 else
4528 throw setStateError();
4529 }
4530
4531 if (fMergeForward)
4532 {
4533 /* we will need parent to reparent target */
4534 pParentForTarget = m->pParent;
4535 }
4536 else
4537 {
4538 /* we will need to reparent children of the source */
4539 for (MediaList::const_iterator it = getChildren().begin();
4540 it != getChildren().end();
4541 ++it)
4542 {
4543 pMedium = *it;
4544 if (fLockMedia)
4545 {
4546 rc = pMedium->LockWrite(NULL);
4547 if (FAILED(rc))
4548 throw rc;
4549 }
4550
4551 aChildrenToReparent.push_back(pMedium);
4552 }
4553 }
4554 for (pLast = pLastIntermediate;
4555 !pLast.isNull() && pLast != pTarget && pLast != this;
4556 pLast = pLast->getParent())
4557 {
4558 AutoWriteLock alock(pLast COMMA_LOCKVAL_SRC_POS);
4559 if (pLast->m->state == MediumState_Created)
4560 {
4561 rc = pLast->markForDeletion();
4562 if (FAILED(rc))
4563 throw rc;
4564 }
4565 else
4566 throw pLast->setStateError();
4567 }
4568
4569 /* Tweak the lock list in the backward merge case, as the target
4570 * isn't marked to be locked for writing yet. */
4571 if (!fMergeForward)
4572 {
4573 MediumLockList::Base::iterator lockListBegin =
4574 aMediumLockList->GetBegin();
4575 MediumLockList::Base::iterator lockListEnd =
4576 aMediumLockList->GetEnd();
4577 lockListEnd--;
4578 for (MediumLockList::Base::iterator it = lockListBegin;
4579 it != lockListEnd;
4580 ++it)
4581 {
4582 MediumLock &mediumLock = *it;
4583 if (mediumLock.GetMedium() == pTarget)
4584 {
4585 HRESULT rc2 = mediumLock.UpdateLock(true);
4586 AssertComRC(rc2);
4587 break;
4588 }
4589 }
4590 }
4591
4592 if (fLockMedia)
4593 {
4594 rc = aMediumLockList->Lock();
4595 if (FAILED(rc))
4596 {
4597 AutoReadLock alock(pTarget COMMA_LOCKVAL_SRC_POS);
4598 throw setError(rc,
4599 tr("Failed to lock media when merging to '%s'"),
4600 pTarget->getLocationFull().raw());
4601 }
4602 }
4603 }
4604 catch (HRESULT aRC) { rc = aRC; }
4605
4606 if (FAILED(rc))
4607 {
4608 delete aMediumLockList;
4609 aMediumLockList = NULL;
4610 }
4611
4612 return rc;
4613}
4614
4615/**
4616 * Merges this medium to the specified medium which must be either its
4617 * direct ancestor or descendant.
4618 *
4619 * Given this medium is SOURCE and the specified medium is TARGET, we will
4620 * get two variants of the merge operation:
4621 *
4622 * forward merge
4623 * ------------------------->
4624 * [Extra] <- SOURCE <- Intermediate <- TARGET
4625 * Any Del Del LockWr
4626 *
4627 *
4628 * backward merge
4629 * <-------------------------
4630 * TARGET <- Intermediate <- SOURCE <- [Extra]
4631 * LockWr Del Del LockWr
4632 *
4633 * Each diagram shows the involved media on the media chain where
4634 * SOURCE and TARGET belong. Under each medium there is a state value which
4635 * the medium must have at a time of the mergeTo() call.
4636 *
4637 * The media in the square braces may be absent (e.g. when the forward
4638 * operation takes place and SOURCE is the base medium, or when the backward
4639 * merge operation takes place and TARGET is the last child in the chain) but if
4640 * they present they are involved too as shown.
4641 *
4642 * Neither the source medium nor intermediate media may be attached to
4643 * any VM directly or in the snapshot, otherwise this method will assert.
4644 *
4645 * The #prepareMergeTo() method must be called prior to this method to place all
4646 * involved to necessary states and perform other consistency checks.
4647 *
4648 * If @a aWait is @c true then this method will perform the operation on the
4649 * calling thread and will not return to the caller until the operation is
4650 * completed. When this method succeeds, all intermediate medium objects in
4651 * the chain will be uninitialized, the state of the target medium (and all
4652 * involved extra media) will be restored. @a aMediumLockList will not be
4653 * deleted, whether the operation is successful or not. The caller has to do
4654 * this if appropriate. Note that this (source) medium is not uninitialized
4655 * because of possible AutoCaller instances held by the caller of this method
4656 * on the current thread. It's therefore the responsibility of the caller to
4657 * call Medium::uninit() after releasing all callers.
4658 *
4659 * If @a aWait is @c false then this method will create a thread to perform the
4660 * operation asynchronously and will return immediately. If the operation
4661 * succeeds, the thread will uninitialize the source medium object and all
4662 * intermediate medium objects in the chain, reset the state of the target
4663 * medium (and all involved extra media) and delete @a aMediumLockList.
4664 * If the operation fails, the thread will only reset the states of all
4665 * involved media and delete @a aMediumLockList.
4666 *
4667 * When this method fails (regardless of the @a aWait mode), it is a caller's
4668 * responsiblity to undo state changes and delete @a aMediumLockList using
4669 * #cancelMergeTo().
4670 *
4671 * If @a aProgress is not NULL but the object it points to is @c null then a new
4672 * progress object will be created and assigned to @a *aProgress on success,
4673 * otherwise the existing progress object is used. If Progress is NULL, then no
4674 * progress object is created/used at all. Note that @a aProgress cannot be
4675 * NULL when @a aWait is @c false (this method will assert in this case).
4676 *
4677 * @param pTarget Target medium.
4678 * @param fMergeForward Merge direction.
4679 * @param pParentForTarget New parent for target medium after merge.
4680 * @param aChildrenToReparent List of children of the source which will have
4681 * to be reparented to the target after merge.
4682 * @param aMediumLockList Medium locking information.
4683 * @param aProgress Where to find/store a Progress object to track operation
4684 * completion.
4685 * @param aWait @c true if this method should block instead of creating
4686 * an asynchronous thread.
4687 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
4688 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
4689 * This only works in "wait" mode; otherwise saveSettings gets called automatically by the thread that was created,
4690 * and this parameter is ignored.
4691 *
4692 * @note Locks the tree lock for writing. Locks the media from the chain
4693 * for writing.
4694 */
4695HRESULT Medium::mergeTo(const ComObjPtr<Medium> &pTarget,
4696 bool fMergeForward,
4697 const ComObjPtr<Medium> &pParentForTarget,
4698 const MediaList &aChildrenToReparent,
4699 MediumLockList *aMediumLockList,
4700 ComObjPtr <Progress> *aProgress,
4701 bool aWait,
4702 bool *pfNeedsSaveSettings)
4703{
4704 AssertReturn(pTarget != NULL, E_FAIL);
4705 AssertReturn(pTarget != this, E_FAIL);
4706 AssertReturn(aMediumLockList != NULL, E_FAIL);
4707 AssertReturn(aProgress != NULL || aWait == true, E_FAIL);
4708
4709 AutoCaller autoCaller(this);
4710 if (FAILED(autoCaller.rc())) return autoCaller.rc();
4711
4712 AutoCaller targetCaller(pTarget);
4713 AssertComRCReturnRC(targetCaller.rc());
4714
4715 HRESULT rc = S_OK;
4716 ComObjPtr <Progress> pProgress;
4717 Medium::Task *pTask = NULL;
4718
4719 try
4720 {
4721 if (aProgress != NULL)
4722 {
4723 /* use the existing progress object... */
4724 pProgress = *aProgress;
4725
4726 /* ...but create a new one if it is null */
4727 if (pProgress.isNull())
4728 {
4729 Utf8Str tgtName;
4730 {
4731 AutoReadLock alock(pTarget COMMA_LOCKVAL_SRC_POS);
4732 tgtName = pTarget->getName();
4733 }
4734
4735 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
4736
4737 pProgress.createObject();
4738 rc = pProgress->init(m->pVirtualBox,
4739 static_cast<IMedium*>(this),
4740 BstrFmt(tr("Merging medium '%s' to '%s'"),
4741 getName().raw(),
4742 tgtName.raw()),
4743 TRUE /* aCancelable */);
4744 if (FAILED(rc))
4745 throw rc;
4746 }
4747 }
4748
4749 /* setup task object to carry out the operation sync/async */
4750 pTask = new Medium::MergeTask(this, pTarget, fMergeForward,
4751 pParentForTarget, aChildrenToReparent,
4752 pProgress, aMediumLockList,
4753 aWait /* fKeepMediumLockList */);
4754 rc = pTask->rc();
4755 AssertComRC(rc);
4756 if (FAILED(rc))
4757 throw rc;
4758 }
4759 catch (HRESULT aRC) { rc = aRC; }
4760
4761 if (SUCCEEDED(rc))
4762 {
4763 if (aWait)
4764 rc = runNow(pTask, pfNeedsSaveSettings);
4765 else
4766 rc = startThread(pTask);
4767
4768 if (SUCCEEDED(rc) && aProgress != NULL)
4769 *aProgress = pProgress;
4770 }
4771 else if (pTask != NULL)
4772 delete pTask;
4773
4774 return rc;
4775}
4776
4777/**
4778 * Undoes what #prepareMergeTo() did. Must be called if #mergeTo() is not
4779 * called or fails. Frees memory occupied by @a aMediumLockList and unlocks
4780 * the medium objects in @a aChildrenToReparent.
4781 *
4782 * @param aChildrenToReparent List of children of the source which will have
4783 * to be reparented to the target after merge.
4784 * @param aMediumLockList Medium locking information.
4785 *
4786 * @note Locks the media from the chain for writing.
4787 */
4788void Medium::cancelMergeTo(const MediaList &aChildrenToReparent,
4789 MediumLockList *aMediumLockList)
4790{
4791 AutoCaller autoCaller(this);
4792 AssertComRCReturnVoid(autoCaller.rc());
4793
4794 AssertReturnVoid(aMediumLockList != NULL);
4795
4796 /* Revert media marked for deletion to previous state. */
4797 HRESULT rc;
4798 MediumLockList::Base::const_iterator mediumListBegin =
4799 aMediumLockList->GetBegin();
4800 MediumLockList::Base::const_iterator mediumListEnd =
4801 aMediumLockList->GetEnd();
4802 for (MediumLockList::Base::const_iterator it = mediumListBegin;
4803 it != mediumListEnd;
4804 ++it)
4805 {
4806 const MediumLock &mediumLock = *it;
4807 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
4808 AutoWriteLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
4809
4810 if (pMedium->m->state == MediumState_Deleting)
4811 {
4812 rc = pMedium->unmarkForDeletion();
4813 AssertComRC(rc);
4814 }
4815 }
4816
4817 /* the destructor will do the work */
4818 delete aMediumLockList;
4819
4820 /* unlock the children which had to be reparented */
4821 for (MediaList::const_iterator it = aChildrenToReparent.begin();
4822 it != aChildrenToReparent.end();
4823 ++it)
4824 {
4825 const ComObjPtr<Medium> &pMedium = *it;
4826
4827 AutoWriteLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
4828 pMedium->UnlockWrite(NULL);
4829 }
4830}
4831
4832/**
4833 * Checks that the format ID is valid and sets it on success.
4834 *
4835 * Note that this method will caller-reference the format object on success!
4836 * This reference must be released somewhere to let the MediumFormat object be
4837 * uninitialized.
4838 *
4839 * @note Must be called from under this object's write lock.
4840 */
4841HRESULT Medium::setFormat(CBSTR aFormat)
4842{
4843 /* get the format object first */
4844 {
4845 SystemProperties *pSysProps = m->pVirtualBox->getSystemProperties();
4846 AutoReadLock propsLock(pSysProps COMMA_LOCKVAL_SRC_POS);
4847
4848 unconst(m->formatObj) = pSysProps->mediumFormat(aFormat);
4849 if (m->formatObj.isNull())
4850 return setError(E_INVALIDARG,
4851 tr("Invalid medium storage format '%ls'"),
4852 aFormat);
4853
4854 /* reference the format permanently to prevent its unexpected
4855 * uninitialization */
4856 HRESULT rc = m->formatObj->addCaller();
4857 AssertComRCReturnRC(rc);
4858
4859 /* get properties (preinsert them as keys in the map). Note that the
4860 * map doesn't grow over the object life time since the set of
4861 * properties is meant to be constant. */
4862
4863 Assert(m->properties.empty());
4864
4865 for (MediumFormat::PropertyList::const_iterator it =
4866 m->formatObj->properties().begin();
4867 it != m->formatObj->properties().end();
4868 ++it)
4869 {
4870 m->properties.insert(std::make_pair(it->name, Bstr::Empty));
4871 }
4872 }
4873
4874 unconst(m->strFormat) = aFormat;
4875
4876 return S_OK;
4877}
4878
4879/**
4880 * Performs extra checks if the medium can be closed and returns S_OK in
4881 * this case. Otherwise, returns a respective error message. Called by
4882 * Close() under the medium tree lock and the medium lock.
4883 *
4884 * @note Also reused by Medium::Reset().
4885 *
4886 * @note Caller must hold the media tree write lock!
4887 */
4888HRESULT Medium::canClose()
4889{
4890 Assert(m->pVirtualBox->getMediaTreeLockHandle().isWriteLockOnCurrentThread());
4891
4892 if (getChildren().size() != 0)
4893 return setError(VBOX_E_OBJECT_IN_USE,
4894 tr("Cannot close medium '%s' because it has %d child media"),
4895 m->strLocationFull.raw(), getChildren().size());
4896
4897 return S_OK;
4898}
4899
4900/**
4901 * Unregisters this medium with mVirtualBox. Called by close() under the medium tree lock.
4902 *
4903 * This calls either VirtualBox::unregisterImage or VirtualBox::unregisterHardDisk depending
4904 * on the device type of this medium.
4905 *
4906 * @param pfNeedsSaveSettings Optional pointer to a bool that must have been initialized to false and that will be set to true
4907 * by this function if the caller should invoke VirtualBox::saveSettings() because the global settings have changed.
4908 *
4909 * @note Caller must have locked the media tree lock for writing!
4910 */
4911HRESULT Medium::unregisterWithVirtualBox(bool *pfNeedsSaveSettings)
4912{
4913 /* Note that we need to de-associate ourselves from the parent to let
4914 * unregisterHardDisk() properly save the registry */
4915
4916 /* we modify mParent and access children */
4917 Assert(m->pVirtualBox->getMediaTreeLockHandle().isWriteLockOnCurrentThread());
4918
4919 Medium *pParentBackup = m->pParent;
4920 AssertReturn(getChildren().size() == 0, E_FAIL);
4921 if (m->pParent)
4922 deparent();
4923
4924 HRESULT rc = E_FAIL;
4925 switch (m->devType)
4926 {
4927 case DeviceType_DVD:
4928 rc = m->pVirtualBox->unregisterImage(this, DeviceType_DVD, pfNeedsSaveSettings);
4929 break;
4930
4931 case DeviceType_Floppy:
4932 rc = m->pVirtualBox->unregisterImage(this, DeviceType_Floppy, pfNeedsSaveSettings);
4933 break;
4934
4935 case DeviceType_HardDisk:
4936 rc = m->pVirtualBox->unregisterHardDisk(this, pfNeedsSaveSettings);
4937 break;
4938
4939 default:
4940 break;
4941 }
4942
4943 if (FAILED(rc))
4944 {
4945 if (pParentBackup)
4946 {
4947 // re-associate with the parent as we are still relatives in the registry
4948 m->pParent = pParentBackup;
4949 m->pParent->m->llChildren.push_back(this);
4950 }
4951 }
4952
4953 return rc;
4954}
4955
4956/**
4957 * Returns the last error message collected by the vdErrorCall callback and
4958 * resets it.
4959 *
4960 * The error message is returned prepended with a dot and a space, like this:
4961 * <code>
4962 * ". <error_text> (%Rrc)"
4963 * </code>
4964 * to make it easily appendable to a more general error message. The @c %Rrc
4965 * format string is given @a aVRC as an argument.
4966 *
4967 * If there is no last error message collected by vdErrorCall or if it is a
4968 * null or empty string, then this function returns the following text:
4969 * <code>
4970 * " (%Rrc)"
4971 * </code>
4972 *
4973 * @note Doesn't do any object locking; it is assumed that the caller makes sure
4974 * the callback isn't called by more than one thread at a time.
4975 *
4976 * @param aVRC VBox error code to use when no error message is provided.
4977 */
4978Utf8Str Medium::vdError(int aVRC)
4979{
4980 Utf8Str error;
4981
4982 if (m->vdError.isEmpty())
4983 error = Utf8StrFmt(" (%Rrc)", aVRC);
4984 else
4985 error = Utf8StrFmt(".\n%s", m->vdError.raw());
4986
4987 m->vdError.setNull();
4988
4989 return error;
4990}
4991
4992/**
4993 * Error message callback.
4994 *
4995 * Puts the reported error message to the m->vdError field.
4996 *
4997 * @note Doesn't do any object locking; it is assumed that the caller makes sure
4998 * the callback isn't called by more than one thread at a time.
4999 *
5000 * @param pvUser The opaque data passed on container creation.
5001 * @param rc The VBox error code.
5002 * @param RT_SRC_POS_DECL Use RT_SRC_POS.
5003 * @param pszFormat Error message format string.
5004 * @param va Error message arguments.
5005 */
5006/*static*/
5007DECLCALLBACK(void) Medium::vdErrorCall(void *pvUser, int rc, RT_SRC_POS_DECL,
5008 const char *pszFormat, va_list va)
5009{
5010 NOREF(pszFile); NOREF(iLine); NOREF(pszFunction); /* RT_SRC_POS_DECL */
5011
5012 Medium *that = static_cast<Medium*>(pvUser);
5013 AssertReturnVoid(that != NULL);
5014
5015 if (that->m->vdError.isEmpty())
5016 that->m->vdError =
5017 Utf8StrFmt("%s (%Rrc)", Utf8StrFmtVA(pszFormat, va).raw(), rc);
5018 else
5019 that->m->vdError =
5020 Utf8StrFmt("%s.\n%s (%Rrc)", that->m->vdError.raw(),
5021 Utf8StrFmtVA(pszFormat, va).raw(), rc);
5022}
5023
5024/* static */
5025DECLCALLBACK(bool) Medium::vdConfigAreKeysValid(void *pvUser,
5026 const char * /* pszzValid */)
5027{
5028 Medium *that = static_cast<Medium*>(pvUser);
5029 AssertReturn(that != NULL, false);
5030
5031 /* we always return true since the only keys we have are those found in
5032 * VDBACKENDINFO */
5033 return true;
5034}
5035
5036/* static */
5037DECLCALLBACK(int) Medium::vdConfigQuerySize(void *pvUser, const char *pszName,
5038 size_t *pcbValue)
5039{
5040 AssertReturn(VALID_PTR(pcbValue), VERR_INVALID_POINTER);
5041
5042 Medium *that = static_cast<Medium*>(pvUser);
5043 AssertReturn(that != NULL, VERR_GENERAL_FAILURE);
5044
5045 Data::PropertyMap::const_iterator it =
5046 that->m->properties.find(Bstr(pszName));
5047 if (it == that->m->properties.end())
5048 return VERR_CFGM_VALUE_NOT_FOUND;
5049
5050 /* we interpret null values as "no value" in Medium */
5051 if (it->second.isEmpty())
5052 return VERR_CFGM_VALUE_NOT_FOUND;
5053
5054 *pcbValue = it->second.length() + 1 /* include terminator */;
5055
5056 return VINF_SUCCESS;
5057}
5058
5059/* static */
5060DECLCALLBACK(int) Medium::vdConfigQuery(void *pvUser, const char *pszName,
5061 char *pszValue, size_t cchValue)
5062{
5063 AssertReturn(VALID_PTR(pszValue), VERR_INVALID_POINTER);
5064
5065 Medium *that = static_cast<Medium*>(pvUser);
5066 AssertReturn(that != NULL, VERR_GENERAL_FAILURE);
5067
5068 Data::PropertyMap::const_iterator it =
5069 that->m->properties.find(Bstr(pszName));
5070 if (it == that->m->properties.end())
5071 return VERR_CFGM_VALUE_NOT_FOUND;
5072
5073 Utf8Str value = it->second;
5074 if (value.length() >= cchValue)
5075 return VERR_CFGM_NOT_ENOUGH_SPACE;
5076
5077 /* we interpret null values as "no value" in Medium */
5078 if (it->second.isEmpty())
5079 return VERR_CFGM_VALUE_NOT_FOUND;
5080
5081 memcpy(pszValue, value.c_str(), value.length() + 1);
5082
5083 return VINF_SUCCESS;
5084}
5085
5086DECLCALLBACK(int) Medium::vdTcpSocketCreate(uint32_t fFlags, PVDSOCKET pSock)
5087{
5088 PVDSOCKETINT pSocketInt = NULL;
5089
5090 if ((fFlags & VD_INTERFACETCPNET_CONNECT_EXTENDED_SELECT) != 0)
5091 return VERR_NOT_SUPPORTED;
5092
5093 pSocketInt = (PVDSOCKETINT)RTMemAllocZ(sizeof(VDSOCKETINT));
5094 if (!pSocketInt)
5095 return VERR_NO_MEMORY;
5096
5097 pSocketInt->hSocket = NIL_RTSOCKET;
5098 *pSock = pSocketInt;
5099 return VINF_SUCCESS;
5100}
5101
5102DECLCALLBACK(int) Medium::vdTcpSocketDestroy(VDSOCKET Sock)
5103{
5104 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
5105
5106 if (pSocketInt->hSocket != NIL_RTSOCKET)
5107 RTTcpClientClose(pSocketInt->hSocket);
5108
5109 RTMemFree(pSocketInt);
5110
5111 return VINF_SUCCESS;
5112}
5113
5114DECLCALLBACK(int) Medium::vdTcpClientConnect(VDSOCKET Sock, const char *pszAddress, uint32_t uPort)
5115{
5116 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
5117
5118 return RTTcpClientConnect(pszAddress, uPort, &pSocketInt->hSocket);
5119}
5120
5121DECLCALLBACK(int) Medium::vdTcpClientClose(VDSOCKET Sock)
5122{
5123 int rc = VINF_SUCCESS;
5124 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
5125
5126 rc = RTTcpClientClose(pSocketInt->hSocket);
5127 pSocketInt->hSocket = NIL_RTSOCKET;
5128 return rc;
5129}
5130
5131DECLCALLBACK(bool) Medium::vdTcpIsClientConnected(VDSOCKET Sock)
5132{
5133 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
5134 return pSocketInt->hSocket != NIL_RTSOCKET;
5135}
5136
5137DECLCALLBACK(int) Medium::vdTcpSelectOne(VDSOCKET Sock, RTMSINTERVAL cMillies)
5138{
5139 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
5140 return RTTcpSelectOne(pSocketInt->hSocket, cMillies);
5141}
5142
5143DECLCALLBACK(int) Medium::vdTcpRead(VDSOCKET Sock, void *pvBuffer, size_t cbBuffer, size_t *pcbRead)
5144{
5145 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
5146 return RTTcpRead(pSocketInt->hSocket, pvBuffer, cbBuffer, pcbRead);
5147}
5148
5149DECLCALLBACK(int) Medium::vdTcpWrite(VDSOCKET Sock, const void *pvBuffer, size_t cbBuffer)
5150{
5151 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
5152 return RTTcpWrite(pSocketInt->hSocket, pvBuffer, cbBuffer);
5153}
5154
5155DECLCALLBACK(int) Medium::vdTcpSgWrite(VDSOCKET Sock, PCRTSGBUF pSgBuf)
5156{
5157 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
5158 return RTTcpSgWrite(pSocketInt->hSocket, pSgBuf);
5159}
5160
5161DECLCALLBACK(int) Medium::vdTcpFlush(VDSOCKET Sock)
5162{
5163 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
5164 return RTTcpFlush(pSocketInt->hSocket);
5165}
5166
5167DECLCALLBACK(int) Medium::vdTcpSetSendCoalescing(VDSOCKET Sock, bool fEnable)
5168{
5169 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
5170 return RTTcpSetSendCoalescing(pSocketInt->hSocket, fEnable);
5171}
5172
5173DECLCALLBACK(int) Medium::vdTcpGetLocalAddress(VDSOCKET Sock, PRTNETADDR pAddr)
5174{
5175 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
5176 return RTTcpGetLocalAddress(pSocketInt->hSocket, pAddr);
5177}
5178
5179DECLCALLBACK(int) Medium::vdTcpGetPeerAddress(VDSOCKET Sock, PRTNETADDR pAddr)
5180{
5181 PVDSOCKETINT pSocketInt = (PVDSOCKETINT)Sock;
5182 return RTTcpGetPeerAddress(pSocketInt->hSocket, pAddr);
5183}
5184
5185
5186/**
5187 * Starts a new thread driven by the appropriate Medium::Task::handler() method.
5188 *
5189 * @note When the task is executed by this method, IProgress::notifyComplete()
5190 * is automatically called for the progress object associated with this
5191 * task when the task is finished to signal the operation completion for
5192 * other threads asynchronously waiting for it.
5193 */
5194HRESULT Medium::startThread(Medium::Task *pTask)
5195{
5196#ifdef VBOX_WITH_MAIN_LOCK_VALIDATION
5197 /* Extreme paranoia: The calling thread should not hold the medium
5198 * tree lock or any medium lock. Since there is no separate lock class
5199 * for medium objects be even more strict: no other object locks. */
5200 Assert(!AutoLockHoldsLocksInClass(LOCKCLASS_LISTOFMEDIA));
5201 Assert(!AutoLockHoldsLocksInClass(getLockingClass()));
5202#endif
5203
5204 /// @todo use a more descriptive task name
5205 int vrc = RTThreadCreate(NULL, Medium::Task::fntMediumTask, pTask,
5206 0, RTTHREADTYPE_MAIN_HEAVY_WORKER, 0,
5207 "Medium::Task");
5208 if (RT_FAILURE(vrc))
5209 {
5210 delete pTask;
5211 return setError(E_FAIL, "Could not create Medium::Task thread (%Rrc)\n", vrc);
5212 }
5213
5214 return S_OK;
5215}
5216
5217/**
5218 * Fix the parent UUID of all children to point to this medium as their
5219 * parent.
5220 */
5221HRESULT Medium::fixParentUuidOfChildren(const MediaList &childrenToReparent)
5222{
5223 MediumLockList mediumLockList;
5224 HRESULT rc = createMediumLockList(true /* fFailIfInaccessible */,
5225 false /* fMediumLockWrite */,
5226 this,
5227 mediumLockList);
5228 AssertComRCReturnRC(rc);
5229
5230 try
5231 {
5232 PVBOXHDD hdd;
5233 int vrc = VDCreate(m->vdDiskIfaces, &hdd);
5234 ComAssertRCThrow(vrc, E_FAIL);
5235
5236 try
5237 {
5238 MediumLockList::Base::iterator lockListBegin =
5239 mediumLockList.GetBegin();
5240 MediumLockList::Base::iterator lockListEnd =
5241 mediumLockList.GetEnd();
5242 for (MediumLockList::Base::iterator it = lockListBegin;
5243 it != lockListEnd;
5244 ++it)
5245 {
5246 MediumLock &mediumLock = *it;
5247 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
5248 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
5249
5250 // open the medium
5251 vrc = VDOpen(hdd,
5252 pMedium->m->strFormat.c_str(),
5253 pMedium->m->strLocationFull.c_str(),
5254 VD_OPEN_FLAGS_READONLY,
5255 pMedium->m->vdDiskIfaces);
5256 if (RT_FAILURE(vrc))
5257 throw vrc;
5258 }
5259
5260 for (MediaList::const_iterator it = childrenToReparent.begin();
5261 it != childrenToReparent.end();
5262 ++it)
5263 {
5264 /* VD_OPEN_FLAGS_INFO since UUID is wrong yet */
5265 vrc = VDOpen(hdd,
5266 (*it)->m->strFormat.c_str(),
5267 (*it)->m->strLocationFull.c_str(),
5268 VD_OPEN_FLAGS_INFO,
5269 (*it)->m->vdDiskIfaces);
5270 if (RT_FAILURE(vrc))
5271 throw vrc;
5272
5273 vrc = VDSetParentUuid(hdd, VD_LAST_IMAGE, m->id);
5274 if (RT_FAILURE(vrc))
5275 throw vrc;
5276
5277 vrc = VDClose(hdd, false /* fDelete */);
5278 if (RT_FAILURE(vrc))
5279 throw vrc;
5280
5281 (*it)->UnlockWrite(NULL);
5282 }
5283 }
5284 catch (HRESULT aRC) { rc = aRC; }
5285 catch (int aVRC)
5286 {
5287 throw setError(E_FAIL,
5288 tr("Could not update medium UUID references to parent '%s' (%s)"),
5289 m->strLocationFull.raw(),
5290 vdError(aVRC).raw());
5291 }
5292
5293 VDDestroy(hdd);
5294 }
5295 catch (HRESULT aRC) { rc = aRC; }
5296
5297 return rc;
5298}
5299
5300/**
5301 * Runs Medium::Task::handler() on the current thread instead of creating
5302 * a new one.
5303 *
5304 * This call implies that it is made on another temporary thread created for
5305 * some asynchronous task. Avoid calling it from a normal thread since the task
5306 * operations are potentially lengthy and will block the calling thread in this
5307 * case.
5308 *
5309 * @note When the task is executed by this method, IProgress::notifyComplete()
5310 * is not called for the progress object associated with this task when
5311 * the task is finished. Instead, the result of the operation is returned
5312 * by this method directly and it's the caller's responsibility to
5313 * complete the progress object in this case.
5314 */
5315HRESULT Medium::runNow(Medium::Task *pTask,
5316 bool *pfNeedsSaveSettings)
5317{
5318#ifdef VBOX_WITH_MAIN_LOCK_VALIDATION
5319 /* Extreme paranoia: The calling thread should not hold the medium
5320 * tree lock or any medium lock. Since there is no separate lock class
5321 * for medium objects be even more strict: no other object locks. */
5322 Assert(!AutoLockHoldsLocksInClass(LOCKCLASS_LISTOFMEDIA));
5323 Assert(!AutoLockHoldsLocksInClass(getLockingClass()));
5324#endif
5325
5326 pTask->m_pfNeedsSaveSettings = pfNeedsSaveSettings;
5327
5328 /* NIL_RTTHREAD indicates synchronous call. */
5329 return (HRESULT)Medium::Task::fntMediumTask(NIL_RTTHREAD, pTask);
5330}
5331
5332/**
5333 * Implementation code for the "create base" task.
5334 *
5335 * This only gets started from Medium::CreateBaseStorage() and always runs
5336 * asynchronously. As a result, we always save the VirtualBox.xml file when
5337 * we're done here.
5338 *
5339 * @param task
5340 * @return
5341 */
5342HRESULT Medium::taskCreateBaseHandler(Medium::CreateBaseTask &task)
5343{
5344 HRESULT rc = S_OK;
5345
5346 /* these parameters we need after creation */
5347 uint64_t size = 0, logicalSize = 0;
5348 MediumVariant_T variant = MediumVariant_Standard;
5349 bool fGenerateUuid = false;
5350
5351 try
5352 {
5353 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
5354
5355 /* The object may request a specific UUID (through a special form of
5356 * the setLocation() argument). Otherwise we have to generate it */
5357 Guid id = m->id;
5358 fGenerateUuid = id.isEmpty();
5359 if (fGenerateUuid)
5360 {
5361 id.create();
5362 /* VirtualBox::registerHardDisk() will need UUID */
5363 unconst(m->id) = id;
5364 }
5365
5366 Utf8Str format(m->strFormat);
5367 Utf8Str location(m->strLocationFull);
5368 uint64_t capabilities = m->formatObj->capabilities();
5369 ComAssertThrow(capabilities & ( VD_CAP_CREATE_FIXED
5370 | VD_CAP_CREATE_DYNAMIC), E_FAIL);
5371 Assert(m->state == MediumState_Creating);
5372
5373 PVBOXHDD hdd;
5374 int vrc = VDCreate(m->vdDiskIfaces, &hdd);
5375 ComAssertRCThrow(vrc, E_FAIL);
5376
5377 /* unlock before the potentially lengthy operation */
5378 thisLock.release();
5379
5380 try
5381 {
5382 /* ensure the directory exists */
5383 rc = VirtualBox::ensureFilePathExists(location);
5384 if (FAILED(rc))
5385 throw rc;
5386
5387 PDMMEDIAGEOMETRY geo = { 0, 0, 0 }; /* auto-detect */
5388
5389 vrc = VDCreateBase(hdd,
5390 format.c_str(),
5391 location.c_str(),
5392 task.mSize * _1M,
5393 task.mVariant,
5394 NULL,
5395 &geo,
5396 &geo,
5397 id.raw(),
5398 VD_OPEN_FLAGS_NORMAL,
5399 NULL,
5400 task.mVDOperationIfaces);
5401 if (RT_FAILURE(vrc))
5402 throw setError(VBOX_E_FILE_ERROR,
5403 tr("Could not create the medium storage unit '%s'%s"),
5404 location.raw(), vdError(vrc).raw());
5405
5406 size = VDGetFileSize(hdd, 0);
5407 logicalSize = VDGetSize(hdd, 0) / _1M;
5408 unsigned uImageFlags;
5409 vrc = VDGetImageFlags(hdd, 0, &uImageFlags);
5410 if (RT_SUCCESS(vrc))
5411 variant = (MediumVariant_T)uImageFlags;
5412 }
5413 catch (HRESULT aRC) { rc = aRC; }
5414
5415 VDDestroy(hdd);
5416 }
5417 catch (HRESULT aRC) { rc = aRC; }
5418
5419 if (SUCCEEDED(rc))
5420 {
5421 /* register with mVirtualBox as the last step and move to
5422 * Created state only on success (leaving an orphan file is
5423 * better than breaking media registry consistency) */
5424 bool fNeedsSaveSettings = false;
5425 AutoWriteLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
5426 rc = m->pVirtualBox->registerHardDisk(this, &fNeedsSaveSettings);
5427 treeLock.release();
5428
5429 if (fNeedsSaveSettings)
5430 {
5431 AutoWriteLock vboxlock(m->pVirtualBox COMMA_LOCKVAL_SRC_POS);
5432 m->pVirtualBox->saveSettings();
5433 }
5434 }
5435
5436 // reenter the lock before changing state
5437 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
5438
5439 if (SUCCEEDED(rc))
5440 {
5441 m->state = MediumState_Created;
5442
5443 m->size = size;
5444 m->logicalSize = logicalSize;
5445 m->variant = variant;
5446 }
5447 else
5448 {
5449 /* back to NotCreated on failure */
5450 m->state = MediumState_NotCreated;
5451
5452 /* reset UUID to prevent it from being reused next time */
5453 if (fGenerateUuid)
5454 unconst(m->id).clear();
5455 }
5456
5457 return rc;
5458}
5459
5460/**
5461 * Implementation code for the "create diff" task.
5462 *
5463 * This task always gets started from Medium::createDiffStorage() and can run
5464 * synchronously or asynchronously depending on the "wait" parameter passed to
5465 * that function. If we run synchronously, the caller expects the bool
5466 * *pfNeedsSaveSettings to be set before returning; otherwise (in asynchronous
5467 * mode), we save the settings ourselves.
5468 *
5469 * @param task
5470 * @return
5471 */
5472HRESULT Medium::taskCreateDiffHandler(Medium::CreateDiffTask &task)
5473{
5474 HRESULT rc = S_OK;
5475
5476 bool fNeedsSaveSettings = false;
5477
5478 const ComObjPtr<Medium> &pTarget = task.mTarget;
5479
5480 uint64_t size = 0, logicalSize = 0;
5481 MediumVariant_T variant = MediumVariant_Standard;
5482 bool fGenerateUuid = false;
5483
5484 try
5485 {
5486 /* Lock both in {parent,child} order. */
5487 AutoMultiWriteLock2 mediaLock(this, pTarget COMMA_LOCKVAL_SRC_POS);
5488
5489 /* The object may request a specific UUID (through a special form of
5490 * the setLocation() argument). Otherwise we have to generate it */
5491 Guid targetId = pTarget->m->id;
5492 fGenerateUuid = targetId.isEmpty();
5493 if (fGenerateUuid)
5494 {
5495 targetId.create();
5496 /* VirtualBox::registerHardDisk() will need UUID */
5497 unconst(pTarget->m->id) = targetId;
5498 }
5499
5500 Guid id = m->id;
5501
5502 Utf8Str targetFormat(pTarget->m->strFormat);
5503 Utf8Str targetLocation(pTarget->m->strLocationFull);
5504 uint64_t capabilities = m->formatObj->capabilities();
5505 ComAssertThrow(capabilities & VD_CAP_CREATE_DYNAMIC, E_FAIL);
5506
5507 Assert(pTarget->m->state == MediumState_Creating);
5508 Assert(m->state == MediumState_LockedRead);
5509
5510 PVBOXHDD hdd;
5511 int vrc = VDCreate(m->vdDiskIfaces, &hdd);
5512 ComAssertRCThrow(vrc, E_FAIL);
5513
5514 /* the two media are now protected by their non-default states;
5515 * unlock the media before the potentially lengthy operation */
5516 mediaLock.release();
5517
5518 try
5519 {
5520 /* Open all media in the target chain but the last. */
5521 MediumLockList::Base::const_iterator targetListBegin =
5522 task.mpMediumLockList->GetBegin();
5523 MediumLockList::Base::const_iterator targetListEnd =
5524 task.mpMediumLockList->GetEnd();
5525 for (MediumLockList::Base::const_iterator it = targetListBegin;
5526 it != targetListEnd;
5527 ++it)
5528 {
5529 const MediumLock &mediumLock = *it;
5530 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
5531
5532 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
5533
5534 /* Skip over the target diff medium */
5535 if (pMedium->m->state == MediumState_Creating)
5536 continue;
5537
5538 /* sanity check */
5539 Assert(pMedium->m->state == MediumState_LockedRead);
5540
5541 /* Open all media in appropriate mode. */
5542 vrc = VDOpen(hdd,
5543 pMedium->m->strFormat.c_str(),
5544 pMedium->m->strLocationFull.c_str(),
5545 VD_OPEN_FLAGS_READONLY,
5546 pMedium->m->vdDiskIfaces);
5547 if (RT_FAILURE(vrc))
5548 throw setError(VBOX_E_FILE_ERROR,
5549 tr("Could not open the medium storage unit '%s'%s"),
5550 pMedium->m->strLocationFull.raw(),
5551 vdError(vrc).raw());
5552 }
5553
5554 /* ensure the target directory exists */
5555 rc = VirtualBox::ensureFilePathExists(targetLocation);
5556 if (FAILED(rc))
5557 throw rc;
5558
5559 vrc = VDCreateDiff(hdd,
5560 targetFormat.c_str(),
5561 targetLocation.c_str(),
5562 task.mVariant | VD_IMAGE_FLAGS_DIFF,
5563 NULL,
5564 targetId.raw(),
5565 id.raw(),
5566 VD_OPEN_FLAGS_NORMAL,
5567 pTarget->m->vdDiskIfaces,
5568 task.mVDOperationIfaces);
5569 if (RT_FAILURE(vrc))
5570 throw setError(VBOX_E_FILE_ERROR,
5571 tr("Could not create the differencing medium storage unit '%s'%s"),
5572 targetLocation.raw(), vdError(vrc).raw());
5573
5574 size = VDGetFileSize(hdd, VD_LAST_IMAGE);
5575 logicalSize = VDGetSize(hdd, VD_LAST_IMAGE) / _1M;
5576 unsigned uImageFlags;
5577 vrc = VDGetImageFlags(hdd, 0, &uImageFlags);
5578 if (RT_SUCCESS(vrc))
5579 variant = (MediumVariant_T)uImageFlags;
5580 }
5581 catch (HRESULT aRC) { rc = aRC; }
5582
5583 VDDestroy(hdd);
5584 }
5585 catch (HRESULT aRC) { rc = aRC; }
5586
5587 if (SUCCEEDED(rc))
5588 {
5589 AutoWriteLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
5590
5591 Assert(pTarget->m->pParent.isNull());
5592
5593 /* associate the child with the parent */
5594 pTarget->m->pParent = this;
5595 m->llChildren.push_back(pTarget);
5596
5597 /** @todo r=klaus neither target nor base() are locked,
5598 * potential race! */
5599 /* diffs for immutable media are auto-reset by default */
5600 pTarget->m->autoReset = (getBase()->m->type == MediumType_Immutable);
5601
5602 /* register with mVirtualBox as the last step and move to
5603 * Created state only on success (leaving an orphan file is
5604 * better than breaking media registry consistency) */
5605 rc = m->pVirtualBox->registerHardDisk(pTarget, &fNeedsSaveSettings);
5606
5607 if (FAILED(rc))
5608 /* break the parent association on failure to register */
5609 deparent();
5610 }
5611
5612 AutoMultiWriteLock2 mediaLock(this, pTarget COMMA_LOCKVAL_SRC_POS);
5613
5614 if (SUCCEEDED(rc))
5615 {
5616 pTarget->m->state = MediumState_Created;
5617
5618 pTarget->m->size = size;
5619 pTarget->m->logicalSize = logicalSize;
5620 pTarget->m->variant = variant;
5621 }
5622 else
5623 {
5624 /* back to NotCreated on failure */
5625 pTarget->m->state = MediumState_NotCreated;
5626
5627 pTarget->m->autoReset = false;
5628
5629 /* reset UUID to prevent it from being reused next time */
5630 if (fGenerateUuid)
5631 unconst(pTarget->m->id).clear();
5632 }
5633
5634 // deregister the task registered in createDiffStorage()
5635 Assert(m->numCreateDiffTasks != 0);
5636 --m->numCreateDiffTasks;
5637
5638 if (task.isAsync())
5639 {
5640 if (fNeedsSaveSettings)
5641 {
5642 // save the global settings; for that we should hold only the VirtualBox lock
5643 mediaLock.release();
5644 AutoWriteLock vboxlock(m->pVirtualBox COMMA_LOCKVAL_SRC_POS);
5645 m->pVirtualBox->saveSettings();
5646 }
5647 }
5648 else
5649 // synchronous mode: report save settings result to caller
5650 if (task.m_pfNeedsSaveSettings)
5651 *task.m_pfNeedsSaveSettings = fNeedsSaveSettings;
5652
5653 /* Note that in sync mode, it's the caller's responsibility to
5654 * unlock the medium. */
5655
5656 return rc;
5657}
5658
5659/**
5660 * Implementation code for the "merge" task.
5661 *
5662 * This task always gets started from Medium::mergeTo() and can run
5663 * synchronously or asynchrously depending on the "wait" parameter passed to
5664 * that function. If we run synchronously, the caller expects the bool
5665 * *pfNeedsSaveSettings to be set before returning; otherwise (in asynchronous
5666 * mode), we save the settings ourselves.
5667 *
5668 * @param task
5669 * @return
5670 */
5671HRESULT Medium::taskMergeHandler(Medium::MergeTask &task)
5672{
5673 HRESULT rc = S_OK;
5674
5675 const ComObjPtr<Medium> &pTarget = task.mTarget;
5676
5677 try
5678 {
5679 PVBOXHDD hdd;
5680 int vrc = VDCreate(m->vdDiskIfaces, &hdd);
5681 ComAssertRCThrow(vrc, E_FAIL);
5682
5683 try
5684 {
5685 // Similar code appears in SessionMachine::onlineMergeMedium, so
5686 // if you make any changes below check whether they are applicable
5687 // in that context as well.
5688
5689 unsigned uTargetIdx = VD_LAST_IMAGE;
5690 unsigned uSourceIdx = VD_LAST_IMAGE;
5691 /* Open all media in the chain. */
5692 MediumLockList::Base::iterator lockListBegin =
5693 task.mpMediumLockList->GetBegin();
5694 MediumLockList::Base::iterator lockListEnd =
5695 task.mpMediumLockList->GetEnd();
5696 unsigned i = 0;
5697 for (MediumLockList::Base::iterator it = lockListBegin;
5698 it != lockListEnd;
5699 ++it)
5700 {
5701 MediumLock &mediumLock = *it;
5702 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
5703
5704 if (pMedium == this)
5705 uSourceIdx = i;
5706 else if (pMedium == pTarget)
5707 uTargetIdx = i;
5708
5709 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
5710
5711 /*
5712 * complex sanity (sane complexity)
5713 *
5714 * The current medium must be in the Deleting (medium is merged)
5715 * or LockedRead (parent medium) state if it is not the target.
5716 * If it is the target it must be in the LockedWrite state.
5717 */
5718 Assert( ( pMedium != pTarget
5719 && ( pMedium->m->state == MediumState_Deleting
5720 || pMedium->m->state == MediumState_LockedRead))
5721 || ( pMedium == pTarget
5722 && pMedium->m->state == MediumState_LockedWrite));
5723
5724 /*
5725 * Medium must be the target, in the LockedRead state
5726 * or Deleting state where it is not allowed to be attached
5727 * to a virtual machine.
5728 */
5729 Assert( pMedium == pTarget
5730 || pMedium->m->state == MediumState_LockedRead
5731 || ( pMedium->m->backRefs.size() == 0
5732 && pMedium->m->state == MediumState_Deleting));
5733 /* The source medium must be in Deleting state. */
5734 Assert( pMedium != this
5735 || pMedium->m->state == MediumState_Deleting);
5736
5737 unsigned uOpenFlags = VD_OPEN_FLAGS_NORMAL;
5738
5739 if ( pMedium->m->state == MediumState_LockedRead
5740 || pMedium->m->state == MediumState_Deleting)
5741 uOpenFlags = VD_OPEN_FLAGS_READONLY;
5742 if (pMedium->m->type == MediumType_Shareable)
5743 uOpenFlags |= VD_OPEN_FLAGS_SHAREABLE;
5744
5745 /* Open the medium */
5746 vrc = VDOpen(hdd,
5747 pMedium->m->strFormat.c_str(),
5748 pMedium->m->strLocationFull.c_str(),
5749 uOpenFlags,
5750 pMedium->m->vdDiskIfaces);
5751 if (RT_FAILURE(vrc))
5752 throw vrc;
5753
5754 i++;
5755 }
5756
5757 ComAssertThrow( uSourceIdx != VD_LAST_IMAGE
5758 && uTargetIdx != VD_LAST_IMAGE, E_FAIL);
5759
5760 vrc = VDMerge(hdd, uSourceIdx, uTargetIdx,
5761 task.mVDOperationIfaces);
5762 if (RT_FAILURE(vrc))
5763 throw vrc;
5764
5765 /* update parent UUIDs */
5766 if (!task.mfMergeForward)
5767 {
5768 /* we need to update UUIDs of all source's children
5769 * which cannot be part of the container at once so
5770 * add each one in there individually */
5771 if (task.mChildrenToReparent.size() > 0)
5772 {
5773 for (MediaList::const_iterator it = task.mChildrenToReparent.begin();
5774 it != task.mChildrenToReparent.end();
5775 ++it)
5776 {
5777 /* VD_OPEN_FLAGS_INFO since UUID is wrong yet */
5778 vrc = VDOpen(hdd,
5779 (*it)->m->strFormat.c_str(),
5780 (*it)->m->strLocationFull.c_str(),
5781 VD_OPEN_FLAGS_INFO,
5782 (*it)->m->vdDiskIfaces);
5783 if (RT_FAILURE(vrc))
5784 throw vrc;
5785
5786 vrc = VDSetParentUuid(hdd, VD_LAST_IMAGE,
5787 pTarget->m->id);
5788 if (RT_FAILURE(vrc))
5789 throw vrc;
5790
5791 vrc = VDClose(hdd, false /* fDelete */);
5792 if (RT_FAILURE(vrc))
5793 throw vrc;
5794
5795 (*it)->UnlockWrite(NULL);
5796 }
5797 }
5798 }
5799 }
5800 catch (HRESULT aRC) { rc = aRC; }
5801 catch (int aVRC)
5802 {
5803 throw setError(VBOX_E_FILE_ERROR,
5804 tr("Could not merge the medium '%s' to '%s'%s"),
5805 m->strLocationFull.raw(),
5806 pTarget->m->strLocationFull.raw(),
5807 vdError(aVRC).raw());
5808 }
5809
5810 VDDestroy(hdd);
5811 }
5812 catch (HRESULT aRC) { rc = aRC; }
5813
5814 HRESULT rc2;
5815
5816 if (SUCCEEDED(rc))
5817 {
5818 /* all media but the target were successfully deleted by
5819 * VDMerge; reparent the last one and uninitialize deleted media. */
5820
5821 AutoWriteLock treeLock(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
5822
5823 if (task.mfMergeForward)
5824 {
5825 /* first, unregister the target since it may become a base
5826 * medium which needs re-registration */
5827 rc2 = m->pVirtualBox->unregisterHardDisk(pTarget, NULL /*&fNeedsSaveSettings*/);
5828 AssertComRC(rc2);
5829
5830 /* then, reparent it and disconnect the deleted branch at
5831 * both ends (chain->parent() is source's parent) */
5832 pTarget->deparent();
5833 pTarget->m->pParent = task.mParentForTarget;
5834 if (pTarget->m->pParent)
5835 {
5836 pTarget->m->pParent->m->llChildren.push_back(pTarget);
5837 deparent();
5838 }
5839
5840 /* then, register again */
5841 rc2 = m->pVirtualBox->registerHardDisk(pTarget, NULL /*&fNeedsSaveSettings*/);
5842 AssertComRC(rc2);
5843 }
5844 else
5845 {
5846 Assert(pTarget->getChildren().size() == 1);
5847 Medium *targetChild = pTarget->getChildren().front();
5848
5849 /* disconnect the deleted branch at the elder end */
5850 targetChild->deparent();
5851
5852 /* reparent source's children and disconnect the deleted
5853 * branch at the younger end */
5854 if (task.mChildrenToReparent.size() > 0)
5855 {
5856 /* obey {parent,child} lock order */
5857 AutoWriteLock sourceLock(this COMMA_LOCKVAL_SRC_POS);
5858
5859 for (MediaList::const_iterator it = task.mChildrenToReparent.begin();
5860 it != task.mChildrenToReparent.end();
5861 it++)
5862 {
5863 Medium *pMedium = *it;
5864 AutoWriteLock childLock(pMedium COMMA_LOCKVAL_SRC_POS);
5865
5866 pMedium->deparent(); // removes pMedium from source
5867 pMedium->setParent(pTarget);
5868 }
5869 }
5870 }
5871
5872 /* unregister and uninitialize all media removed by the merge */
5873 MediumLockList::Base::iterator lockListBegin =
5874 task.mpMediumLockList->GetBegin();
5875 MediumLockList::Base::iterator lockListEnd =
5876 task.mpMediumLockList->GetEnd();
5877 for (MediumLockList::Base::iterator it = lockListBegin;
5878 it != lockListEnd;
5879 )
5880 {
5881 MediumLock &mediumLock = *it;
5882 /* Create a real copy of the medium pointer, as the medium
5883 * lock deletion below would invalidate the referenced object. */
5884 const ComObjPtr<Medium> pMedium = mediumLock.GetMedium();
5885
5886 /* The target and all media not merged (readonly) are skipped */
5887 if ( pMedium == pTarget
5888 || pMedium->m->state == MediumState_LockedRead)
5889 {
5890 ++it;
5891 continue;
5892 }
5893
5894 rc2 = pMedium->m->pVirtualBox->unregisterHardDisk(pMedium,
5895 NULL /*pfNeedsSaveSettings*/);
5896 AssertComRC(rc2);
5897
5898 /* now, uninitialize the deleted medium (note that
5899 * due to the Deleting state, uninit() will not touch
5900 * the parent-child relationship so we need to
5901 * uninitialize each disk individually) */
5902
5903 /* note that the operation initiator medium (which is
5904 * normally also the source medium) is a special case
5905 * -- there is one more caller added by Task to it which
5906 * we must release. Also, if we are in sync mode, the
5907 * caller may still hold an AutoCaller instance for it
5908 * and therefore we cannot uninit() it (it's therefore
5909 * the caller's responsibility) */
5910 if (pMedium == this)
5911 {
5912 Assert(getChildren().size() == 0);
5913 Assert(m->backRefs.size() == 0);
5914 task.mMediumCaller.release();
5915 }
5916
5917 /* Delete the medium lock list entry, which also releases the
5918 * caller added by MergeChain before uninit() and updates the
5919 * iterator to point to the right place. */
5920 rc2 = task.mpMediumLockList->RemoveByIterator(it);
5921 AssertComRC(rc2);
5922
5923 if (task.isAsync() || pMedium != this)
5924 pMedium->uninit();
5925 }
5926 }
5927
5928 if (task.isAsync())
5929 {
5930 // in asynchronous mode, save settings now
5931 // for that we should hold only the VirtualBox lock
5932 AutoWriteLock vboxlock(m->pVirtualBox COMMA_LOCKVAL_SRC_POS);
5933 m->pVirtualBox->saveSettings();
5934 }
5935 else
5936 // synchronous mode: report save settings result to caller
5937 if (task.m_pfNeedsSaveSettings)
5938 *task.m_pfNeedsSaveSettings = true;
5939
5940 if (FAILED(rc))
5941 {
5942 /* Here we come if either VDMerge() failed (in which case we
5943 * assume that it tried to do everything to make a further
5944 * retry possible -- e.g. not deleted intermediate media
5945 * and so on) or VirtualBox::saveSettings() failed (where we
5946 * should have the original tree but with intermediate storage
5947 * units deleted by VDMerge()). We have to only restore states
5948 * (through the MergeChain dtor) unless we are run synchronously
5949 * in which case it's the responsibility of the caller as stated
5950 * in the mergeTo() docs. The latter also implies that we
5951 * don't own the merge chain, so release it in this case. */
5952 if (task.isAsync())
5953 {
5954 Assert(task.mChildrenToReparent.size() == 0);
5955 cancelMergeTo(task.mChildrenToReparent, task.mpMediumLockList);
5956 }
5957 }
5958
5959 return rc;
5960}
5961
5962/**
5963 * Implementation code for the "clone" task.
5964 *
5965 * This only gets started from Medium::CloneTo() and always runs asynchronously.
5966 * As a result, we always save the VirtualBox.xml file when we're done here.
5967 *
5968 * @param task
5969 * @return
5970 */
5971HRESULT Medium::taskCloneHandler(Medium::CloneTask &task)
5972{
5973 HRESULT rc = S_OK;
5974
5975 const ComObjPtr<Medium> &pTarget = task.mTarget;
5976 const ComObjPtr<Medium> &pParent = task.mParent;
5977
5978 bool fCreatingTarget = false;
5979
5980 uint64_t size = 0, logicalSize = 0;
5981 MediumVariant_T variant = MediumVariant_Standard;
5982 bool fGenerateUuid = false;
5983
5984 try
5985 {
5986 /* Lock all in {parent,child} order. The lock is also used as a
5987 * signal from the task initiator (which releases it only after
5988 * RTThreadCreate()) that we can start the job. */
5989 AutoMultiWriteLock3 thisLock(this, pTarget, pParent COMMA_LOCKVAL_SRC_POS);
5990
5991 fCreatingTarget = pTarget->m->state == MediumState_Creating;
5992
5993 /* The object may request a specific UUID (through a special form of
5994 * the setLocation() argument). Otherwise we have to generate it */
5995 Guid targetId = pTarget->m->id;
5996 fGenerateUuid = targetId.isEmpty();
5997 if (fGenerateUuid)
5998 {
5999 targetId.create();
6000 /* VirtualBox::registerHardDisk() will need UUID */
6001 unconst(pTarget->m->id) = targetId;
6002 }
6003
6004 PVBOXHDD hdd;
6005 int vrc = VDCreate(m->vdDiskIfaces, &hdd);
6006 ComAssertRCThrow(vrc, E_FAIL);
6007
6008 try
6009 {
6010 /* Open all media in the source chain. */
6011 MediumLockList::Base::const_iterator sourceListBegin =
6012 task.mpSourceMediumLockList->GetBegin();
6013 MediumLockList::Base::const_iterator sourceListEnd =
6014 task.mpSourceMediumLockList->GetEnd();
6015 for (MediumLockList::Base::const_iterator it = sourceListBegin;
6016 it != sourceListEnd;
6017 ++it)
6018 {
6019 const MediumLock &mediumLock = *it;
6020 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
6021 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
6022
6023 /* sanity check */
6024 Assert(pMedium->m->state == MediumState_LockedRead);
6025
6026 /** Open all media in read-only mode. */
6027 vrc = VDOpen(hdd,
6028 pMedium->m->strFormat.c_str(),
6029 pMedium->m->strLocationFull.c_str(),
6030 VD_OPEN_FLAGS_READONLY,
6031 pMedium->m->vdDiskIfaces);
6032 if (RT_FAILURE(vrc))
6033 throw setError(VBOX_E_FILE_ERROR,
6034 tr("Could not open the medium storage unit '%s'%s"),
6035 pMedium->m->strLocationFull.raw(),
6036 vdError(vrc).raw());
6037 }
6038
6039 Utf8Str targetFormat(pTarget->m->strFormat);
6040 Utf8Str targetLocation(pTarget->m->strLocationFull);
6041
6042 Assert( pTarget->m->state == MediumState_Creating
6043 || pTarget->m->state == MediumState_LockedWrite);
6044 Assert(m->state == MediumState_LockedRead);
6045 Assert(pParent.isNull() || pParent->m->state == MediumState_LockedRead);
6046
6047 /* unlock before the potentially lengthy operation */
6048 thisLock.release();
6049
6050 /* ensure the target directory exists */
6051 rc = VirtualBox::ensureFilePathExists(targetLocation);
6052 if (FAILED(rc))
6053 throw rc;
6054
6055 PVBOXHDD targetHdd;
6056 vrc = VDCreate(m->vdDiskIfaces, &targetHdd);
6057 ComAssertRCThrow(vrc, E_FAIL);
6058
6059 try
6060 {
6061 /* Open all media in the target chain. */
6062 MediumLockList::Base::const_iterator targetListBegin =
6063 task.mpTargetMediumLockList->GetBegin();
6064 MediumLockList::Base::const_iterator targetListEnd =
6065 task.mpTargetMediumLockList->GetEnd();
6066 for (MediumLockList::Base::const_iterator it = targetListBegin;
6067 it != targetListEnd;
6068 ++it)
6069 {
6070 const MediumLock &mediumLock = *it;
6071 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
6072
6073 /* If the target medium is not created yet there's no
6074 * reason to open it. */
6075 if (pMedium == pTarget && fCreatingTarget)
6076 continue;
6077
6078 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
6079
6080 /* sanity check */
6081 Assert( pMedium->m->state == MediumState_LockedRead
6082 || pMedium->m->state == MediumState_LockedWrite);
6083
6084 unsigned uOpenFlags = VD_OPEN_FLAGS_NORMAL;
6085 if (pMedium->m->state != MediumState_LockedWrite)
6086 uOpenFlags = VD_OPEN_FLAGS_READONLY;
6087 if (pMedium->m->type == MediumType_Shareable)
6088 uOpenFlags |= VD_OPEN_FLAGS_SHAREABLE;
6089
6090 /* Open all media in appropriate mode. */
6091 vrc = VDOpen(targetHdd,
6092 pMedium->m->strFormat.c_str(),
6093 pMedium->m->strLocationFull.c_str(),
6094 uOpenFlags,
6095 pMedium->m->vdDiskIfaces);
6096 if (RT_FAILURE(vrc))
6097 throw setError(VBOX_E_FILE_ERROR,
6098 tr("Could not open the medium storage unit '%s'%s"),
6099 pMedium->m->strLocationFull.raw(),
6100 vdError(vrc).raw());
6101 }
6102
6103 /** @todo r=klaus target isn't locked, race getting the state */
6104 vrc = VDCopy(hdd,
6105 VD_LAST_IMAGE,
6106 targetHdd,
6107 targetFormat.c_str(),
6108 (fCreatingTarget) ? targetLocation.raw() : (char *)NULL,
6109 false,
6110 0,
6111 task.mVariant,
6112 targetId.raw(),
6113 NULL,
6114 pTarget->m->vdDiskIfaces,
6115 task.mVDOperationIfaces);
6116 if (RT_FAILURE(vrc))
6117 throw setError(VBOX_E_FILE_ERROR,
6118 tr("Could not create the clone medium '%s'%s"),
6119 targetLocation.raw(), vdError(vrc).raw());
6120
6121 size = VDGetFileSize(targetHdd, VD_LAST_IMAGE);
6122 logicalSize = VDGetSize(targetHdd, VD_LAST_IMAGE) / _1M;
6123 unsigned uImageFlags;
6124 vrc = VDGetImageFlags(targetHdd, 0, &uImageFlags);
6125 if (RT_SUCCESS(vrc))
6126 variant = (MediumVariant_T)uImageFlags;
6127 }
6128 catch (HRESULT aRC) { rc = aRC; }
6129
6130 VDDestroy(targetHdd);
6131 }
6132 catch (HRESULT aRC) { rc = aRC; }
6133
6134 VDDestroy(hdd);
6135 }
6136 catch (HRESULT aRC) { rc = aRC; }
6137
6138 /* Only do the parent changes for newly created media. */
6139 if (SUCCEEDED(rc) && fCreatingTarget)
6140 {
6141 /* we set mParent & children() */
6142 AutoWriteLock alock2(m->pVirtualBox->getMediaTreeLockHandle() COMMA_LOCKVAL_SRC_POS);
6143
6144 Assert(pTarget->m->pParent.isNull());
6145
6146 if (pParent)
6147 {
6148 /* associate the clone with the parent and deassociate
6149 * from VirtualBox */
6150 pTarget->m->pParent = pParent;
6151 pParent->m->llChildren.push_back(pTarget);
6152
6153 /* register with mVirtualBox as the last step and move to
6154 * Created state only on success (leaving an orphan file is
6155 * better than breaking media registry consistency) */
6156 rc = pParent->m->pVirtualBox->registerHardDisk(pTarget, NULL /* pfNeedsSaveSettings */);
6157
6158 if (FAILED(rc))
6159 /* break parent association on failure to register */
6160 pTarget->deparent(); // removes target from parent
6161 }
6162 else
6163 {
6164 /* just register */
6165 rc = m->pVirtualBox->registerHardDisk(pTarget, NULL /* pfNeedsSaveSettings */);
6166 }
6167 }
6168
6169 if (fCreatingTarget)
6170 {
6171 AutoWriteLock mLock(pTarget COMMA_LOCKVAL_SRC_POS);
6172
6173 if (SUCCEEDED(rc))
6174 {
6175 pTarget->m->state = MediumState_Created;
6176
6177 pTarget->m->size = size;
6178 pTarget->m->logicalSize = logicalSize;
6179 pTarget->m->variant = variant;
6180 }
6181 else
6182 {
6183 /* back to NotCreated on failure */
6184 pTarget->m->state = MediumState_NotCreated;
6185
6186 /* reset UUID to prevent it from being reused next time */
6187 if (fGenerateUuid)
6188 unconst(pTarget->m->id).clear();
6189 }
6190 }
6191
6192 // now, at the end of this task (always asynchronous), save the settings
6193 {
6194 AutoWriteLock vboxlock(m->pVirtualBox COMMA_LOCKVAL_SRC_POS);
6195 m->pVirtualBox->saveSettings();
6196 }
6197
6198 /* Everything is explicitly unlocked when the task exits,
6199 * as the task destruction also destroys the source chain. */
6200
6201 /* Make sure the source chain is released early. It could happen
6202 * that we get a deadlock in Appliance::Import when Medium::Close
6203 * is called & the source chain is released at the same time. */
6204 task.mpSourceMediumLockList->Clear();
6205
6206 return rc;
6207}
6208
6209/**
6210 * Implementation code for the "delete" task.
6211 *
6212 * This task always gets started from Medium::deleteStorage() and can run
6213 * synchronously or asynchrously depending on the "wait" parameter passed to
6214 * that function.
6215 *
6216 * @param task
6217 * @return
6218 */
6219HRESULT Medium::taskDeleteHandler(Medium::DeleteTask &task)
6220{
6221 NOREF(task);
6222 HRESULT rc = S_OK;
6223
6224 try
6225 {
6226 /* The lock is also used as a signal from the task initiator (which
6227 * releases it only after RTThreadCreate()) that we can start the job */
6228 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
6229
6230 PVBOXHDD hdd;
6231 int vrc = VDCreate(m->vdDiskIfaces, &hdd);
6232 ComAssertRCThrow(vrc, E_FAIL);
6233
6234 Utf8Str format(m->strFormat);
6235 Utf8Str location(m->strLocationFull);
6236
6237 /* unlock before the potentially lengthy operation */
6238 Assert(m->state == MediumState_Deleting);
6239 thisLock.release();
6240
6241 try
6242 {
6243 vrc = VDOpen(hdd,
6244 format.c_str(),
6245 location.c_str(),
6246 VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_INFO,
6247 m->vdDiskIfaces);
6248 if (RT_SUCCESS(vrc))
6249 vrc = VDClose(hdd, true /* fDelete */);
6250
6251 if (RT_FAILURE(vrc))
6252 throw setError(VBOX_E_FILE_ERROR,
6253 tr("Could not delete the medium storage unit '%s'%s"),
6254 location.raw(), vdError(vrc).raw());
6255
6256 }
6257 catch (HRESULT aRC) { rc = aRC; }
6258
6259 VDDestroy(hdd);
6260 }
6261 catch (HRESULT aRC) { rc = aRC; }
6262
6263 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
6264
6265 /* go to the NotCreated state even on failure since the storage
6266 * may have been already partially deleted and cannot be used any
6267 * more. One will be able to manually re-open the storage if really
6268 * needed to re-register it. */
6269 m->state = MediumState_NotCreated;
6270
6271 /* Reset UUID to prevent Create* from reusing it again */
6272 unconst(m->id).clear();
6273
6274 return rc;
6275}
6276
6277/**
6278 * Implementation code for the "reset" task.
6279 *
6280 * This always gets started asynchronously from Medium::Reset().
6281 *
6282 * @param task
6283 * @return
6284 */
6285HRESULT Medium::taskResetHandler(Medium::ResetTask &task)
6286{
6287 HRESULT rc = S_OK;
6288
6289 uint64_t size = 0, logicalSize = 0;
6290 MediumVariant_T variant = MediumVariant_Standard;
6291
6292 try
6293 {
6294 /* The lock is also used as a signal from the task initiator (which
6295 * releases it only after RTThreadCreate()) that we can start the job */
6296 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
6297
6298 /// @todo Below we use a pair of delete/create operations to reset
6299 /// the diff contents but the most efficient way will of course be
6300 /// to add a VDResetDiff() API call
6301
6302 PVBOXHDD hdd;
6303 int vrc = VDCreate(m->vdDiskIfaces, &hdd);
6304 ComAssertRCThrow(vrc, E_FAIL);
6305
6306 Guid id = m->id;
6307 Utf8Str format(m->strFormat);
6308 Utf8Str location(m->strLocationFull);
6309
6310 Medium *pParent = m->pParent;
6311 Guid parentId = pParent->m->id;
6312 Utf8Str parentFormat(pParent->m->strFormat);
6313 Utf8Str parentLocation(pParent->m->strLocationFull);
6314
6315 Assert(m->state == MediumState_LockedWrite);
6316
6317 /* unlock before the potentially lengthy operation */
6318 thisLock.release();
6319
6320 try
6321 {
6322 /* Open all media in the target chain but the last. */
6323 MediumLockList::Base::const_iterator targetListBegin =
6324 task.mpMediumLockList->GetBegin();
6325 MediumLockList::Base::const_iterator targetListEnd =
6326 task.mpMediumLockList->GetEnd();
6327 for (MediumLockList::Base::const_iterator it = targetListBegin;
6328 it != targetListEnd;
6329 ++it)
6330 {
6331 const MediumLock &mediumLock = *it;
6332 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
6333
6334 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
6335
6336 /* sanity check, "this" is checked above */
6337 Assert( pMedium == this
6338 || pMedium->m->state == MediumState_LockedRead);
6339
6340 /* Open all media in appropriate mode. */
6341 vrc = VDOpen(hdd,
6342 pMedium->m->strFormat.c_str(),
6343 pMedium->m->strLocationFull.c_str(),
6344 VD_OPEN_FLAGS_READONLY,
6345 pMedium->m->vdDiskIfaces);
6346 if (RT_FAILURE(vrc))
6347 throw setError(VBOX_E_FILE_ERROR,
6348 tr("Could not open the medium storage unit '%s'%s"),
6349 pMedium->m->strLocationFull.raw(),
6350 vdError(vrc).raw());
6351
6352 /* Done when we hit the media which should be reset */
6353 if (pMedium == this)
6354 break;
6355 }
6356
6357 /* first, delete the storage unit */
6358 vrc = VDClose(hdd, true /* fDelete */);
6359 if (RT_FAILURE(vrc))
6360 throw setError(VBOX_E_FILE_ERROR,
6361 tr("Could not delete the medium storage unit '%s'%s"),
6362 location.raw(), vdError(vrc).raw());
6363
6364 /* next, create it again */
6365 vrc = VDOpen(hdd,
6366 parentFormat.c_str(),
6367 parentLocation.c_str(),
6368 VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_INFO,
6369 m->vdDiskIfaces);
6370 if (RT_FAILURE(vrc))
6371 throw setError(VBOX_E_FILE_ERROR,
6372 tr("Could not open the medium storage unit '%s'%s"),
6373 parentLocation.raw(), vdError(vrc).raw());
6374
6375 vrc = VDCreateDiff(hdd,
6376 format.c_str(),
6377 location.c_str(),
6378 /// @todo use the same medium variant as before
6379 VD_IMAGE_FLAGS_NONE,
6380 NULL,
6381 id.raw(),
6382 parentId.raw(),
6383 VD_OPEN_FLAGS_NORMAL,
6384 m->vdDiskIfaces,
6385 task.mVDOperationIfaces);
6386 if (RT_FAILURE(vrc))
6387 throw setError(VBOX_E_FILE_ERROR,
6388 tr("Could not create the differencing medium storage unit '%s'%s"),
6389 location.raw(), vdError(vrc).raw());
6390
6391 size = VDGetFileSize(hdd, VD_LAST_IMAGE);
6392 logicalSize = VDGetSize(hdd, VD_LAST_IMAGE) / _1M;
6393 unsigned uImageFlags;
6394 vrc = VDGetImageFlags(hdd, 0, &uImageFlags);
6395 if (RT_SUCCESS(vrc))
6396 variant = (MediumVariant_T)uImageFlags;
6397 }
6398 catch (HRESULT aRC) { rc = aRC; }
6399
6400 VDDestroy(hdd);
6401 }
6402 catch (HRESULT aRC) { rc = aRC; }
6403
6404 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
6405
6406 m->size = size;
6407 m->logicalSize = logicalSize;
6408 m->variant = variant;
6409
6410 if (task.isAsync())
6411 {
6412 /* unlock ourselves when done */
6413 HRESULT rc2 = UnlockWrite(NULL);
6414 AssertComRC(rc2);
6415 }
6416
6417 /* Note that in sync mode, it's the caller's responsibility to
6418 * unlock the medium. */
6419
6420 return rc;
6421}
6422
6423/**
6424 * Implementation code for the "compact" task.
6425 *
6426 * @param task
6427 * @return
6428 */
6429HRESULT Medium::taskCompactHandler(Medium::CompactTask &task)
6430{
6431 HRESULT rc = S_OK;
6432
6433 /* Lock all in {parent,child} order. The lock is also used as a
6434 * signal from the task initiator (which releases it only after
6435 * RTThreadCreate()) that we can start the job. */
6436 AutoWriteLock thisLock(this COMMA_LOCKVAL_SRC_POS);
6437
6438 try
6439 {
6440 PVBOXHDD hdd;
6441 int vrc = VDCreate(m->vdDiskIfaces, &hdd);
6442 ComAssertRCThrow(vrc, E_FAIL);
6443
6444 try
6445 {
6446 /* Open all media in the chain. */
6447 MediumLockList::Base::const_iterator mediumListBegin =
6448 task.mpMediumLockList->GetBegin();
6449 MediumLockList::Base::const_iterator mediumListEnd =
6450 task.mpMediumLockList->GetEnd();
6451 MediumLockList::Base::const_iterator mediumListLast =
6452 mediumListEnd;
6453 mediumListLast--;
6454 for (MediumLockList::Base::const_iterator it = mediumListBegin;
6455 it != mediumListEnd;
6456 ++it)
6457 {
6458 const MediumLock &mediumLock = *it;
6459 const ComObjPtr<Medium> &pMedium = mediumLock.GetMedium();
6460 AutoReadLock alock(pMedium COMMA_LOCKVAL_SRC_POS);
6461
6462 /* sanity check */
6463 if (it == mediumListLast)
6464 Assert(pMedium->m->state == MediumState_LockedWrite);
6465 else
6466 Assert(pMedium->m->state == MediumState_LockedRead);
6467
6468 /* Open all media but last in read-only mode. Do not handle
6469 * shareable media, as compaction and sharing are mutually
6470 * exclusive. */
6471 vrc = VDOpen(hdd,
6472 pMedium->m->strFormat.c_str(),
6473 pMedium->m->strLocationFull.c_str(),
6474 (it == mediumListLast) ? VD_OPEN_FLAGS_NORMAL : VD_OPEN_FLAGS_READONLY,
6475 pMedium->m->vdDiskIfaces);
6476 if (RT_FAILURE(vrc))
6477 throw setError(VBOX_E_FILE_ERROR,
6478 tr("Could not open the medium storage unit '%s'%s"),
6479 pMedium->m->strLocationFull.raw(),
6480 vdError(vrc).raw());
6481 }
6482
6483 Assert(m->state == MediumState_LockedWrite);
6484
6485 Utf8Str location(m->strLocationFull);
6486
6487 /* unlock before the potentially lengthy operation */
6488 thisLock.release();
6489
6490 vrc = VDCompact(hdd, VD_LAST_IMAGE, task.mVDOperationIfaces);
6491 if (RT_FAILURE(vrc))
6492 {
6493 if (vrc == VERR_NOT_SUPPORTED)
6494 throw setError(VBOX_E_NOT_SUPPORTED,
6495 tr("Compacting is not yet supported for medium '%s'"),
6496 location.raw());
6497 else if (vrc == VERR_NOT_IMPLEMENTED)
6498 throw setError(E_NOTIMPL,
6499 tr("Compacting is not implemented, medium '%s'"),
6500 location.raw());
6501 else
6502 throw setError(VBOX_E_FILE_ERROR,
6503 tr("Could not compact medium '%s'%s"),
6504 location.raw(),
6505 vdError(vrc).raw());
6506 }
6507 }
6508 catch (HRESULT aRC) { rc = aRC; }
6509
6510 VDDestroy(hdd);
6511 }
6512 catch (HRESULT aRC) { rc = aRC; }
6513
6514 /* Everything is explicitly unlocked when the task exits,
6515 * as the task destruction also destroys the media chain. */
6516
6517 return rc;
6518}
6519
6520/* vi: set tabstop=4 shiftwidth=4 expandtab: */
Note: See TracBrowser for help on using the repository browser.

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