VirtualBox

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

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

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

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