VirtualBox

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

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

Main/Medium: improve r61220 (add forgotten medium registry save when deleting the storage representation of a medium)

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