VirtualBox

source: vbox/trunk/src/VBox/Main/HardDisk2Impl.cpp@ 15466

Last change on this file since 15466 was 15215, checked in by vboxsync, 16 years ago

Main: #3312: Restore the proper hard disk accessibility state after unlock if checked while being locked; allow to delete hard disks in Inaccessible state (backends will fail anyway). Fixes the problem of orphan diffs after reverting to the current snapshot on power off.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Date Revision Author Id
File size: 124.8 KB
Line 
1/* $Id: HardDisk2Impl.cpp 15215 2008-12-09 23:46:52Z vboxsync $ */
2
3/** @file
4 *
5 * VirtualBox COM class implementation
6 */
7
8/*
9 * Copyright (C) 2008 Sun Microsystems, Inc.
10 *
11 * This file is part of VirtualBox Open Source Edition (OSE), as
12 * available from http://www.virtualbox.org. This file is free software;
13 * you can redistribute it and/or modify it under the terms of the GNU
14 * General Public License (GPL) as published by the Free Software
15 * Foundation, in version 2 as it comes in the "COPYING" file of the
16 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
17 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
18 *
19 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
20 * Clara, CA 95054 USA or visit http://www.sun.com if you need
21 * additional information or have any questions.
22 */
23
24#include "HardDisk2Impl.h"
25
26#include "ProgressImpl.h"
27#include "SystemPropertiesImpl.h"
28
29#include "Logging.h"
30
31#include <VBox/com/array.h>
32#include <VBox/com/SupportErrorInfo.h>
33
34#include <VBox/err.h>
35
36#include <iprt/param.h>
37#include <iprt/path.h>
38#include <iprt/file.h>
39#include <iprt/tcp.h>
40
41#include <list>
42#include <memory>
43
44////////////////////////////////////////////////////////////////////////////////
45// Globals
46////////////////////////////////////////////////////////////////////////////////
47
48/**
49 * Asynchronous task thread parameter bucket.
50 *
51 * Note that instances of this class must be created using new() because the
52 * task thread function will delete them when the task is complete!
53 *
54 * @note The constructor of this class adds a caller on the managed HardDisk2
55 * object which is automatically released upon destruction.
56 */
57struct HardDisk2::Task : public com::SupportErrorInfoBase
58{
59 enum Operation { CreateDynamic, CreateFixed, CreateDiff, Merge, Delete };
60
61 HardDisk2 *that;
62 VirtualBoxBaseProto::AutoCaller autoCaller;
63
64 ComObjPtr <Progress> progress;
65 Operation operation;
66
67 /** Where to save the result when executed using #runNow(). */
68 HRESULT rc;
69
70 Task (HardDisk2 *aThat, Progress *aProgress, Operation aOperation)
71 : that (aThat), autoCaller (aThat)
72 , progress (aProgress)
73 , operation (aOperation)
74 , rc (S_OK) {}
75
76 ~Task();
77
78 void setData (HardDisk2 *aTarget)
79 {
80 d.target = aTarget;
81 HRESULT rc = d.target->addCaller();
82 AssertComRC (rc);
83 }
84
85 void setData (MergeChain *aChain)
86 {
87 AssertReturnVoid (aChain != NULL);
88 d.chain.reset (aChain);
89 }
90
91 HRESULT startThread();
92 HRESULT runNow();
93
94 struct Data
95 {
96 Data() : size (0) {}
97
98 /* CreateDynamic, CreateStatic */
99
100 uint64_t size;
101
102 /* CreateDiff */
103
104 ComObjPtr <HardDisk2> target;
105
106 /* Merge */
107
108 /** Hard disks to merge, in {parent,child} order */
109 std::auto_ptr <MergeChain> chain;
110 }
111 d;
112
113protected:
114
115 // SupportErrorInfoBase interface
116 const GUID &mainInterfaceID() const { return COM_IIDOF (IHardDisk2); }
117 const char *componentName() const { return HardDisk2::ComponentName(); }
118};
119
120HardDisk2::Task::~Task()
121{
122 /* remove callers added by setData() */
123 if (!d.target.isNull())
124 d.target->releaseCaller();
125}
126
127/**
128 * Starts a new thread driven by the HardDisk2::taskThread() function and passes
129 * this Task instance as an argument.
130 *
131 * Note that if this method returns success, this Task object becomes an ownee
132 * of the started thread and will be automatically deleted when the thread
133 * terminates.
134 *
135 * @note When the task is executed by this method, IProgress::notifyComplete()
136 * is automatically called for the progress object associated with this
137 * task when the task is finished to signal the operation completion for
138 * other threads asynchronously waiting for it.
139 */
140HRESULT HardDisk2::Task::startThread()
141{
142 int vrc = RTThreadCreate (NULL, HardDisk2::taskThread, this,
143 0, RTTHREADTYPE_MAIN_HEAVY_WORKER, 0,
144 "HardDisk::Task");
145 ComAssertMsgRCRet (vrc,
146 ("Could not create HardDisk::Task thread (%Rrc)\n", vrc), E_FAIL);
147
148 return S_OK;
149}
150
151/**
152 * Runs HardDisk2::taskThread() by passing it this Task instance as an argument
153 * on the current thread instead of creating a new one.
154 *
155 * This call implies that it is made on another temporary thread created for
156 * some asynchronous task. Avoid calling it from a normal thread since the task
157 * operatinos are potentially lengthy and will block the calling thread in this
158 * case.
159 *
160 * Note that this Task object will be deleted by taskThread() when this method
161 * returns!
162 *
163 * @note When the task is executed by this method, IProgress::notifyComplete()
164 * is not called for the progress object associated with this task when
165 * the task is finished. Instead, the result of the operation is returned
166 * by this method directly and it's the caller's responsibility to
167 * complete the progress object in this case.
168 */
169HRESULT HardDisk2::Task::runNow()
170{
171 HardDisk2::taskThread (NIL_RTTHREAD, this);
172
173 return rc;
174}
175
176////////////////////////////////////////////////////////////////////////////////
177
178/**
179 * Helper class for merge operations.
180 *
181 * @note It is assumed that when modifying methods of this class are called,
182 * HardDisk2::treeLock() is held in read mode.
183 */
184class HardDisk2::MergeChain : public HardDisk2::List,
185 public com::SupportErrorInfoBase
186{
187public:
188
189 MergeChain (bool aForward, bool aIgnoreAttachments)
190 : mForward (aForward)
191 , mIgnoreAttachments (aIgnoreAttachments) {}
192
193 ~MergeChain()
194 {
195 for (iterator it = mChildren.begin(); it != mChildren.end(); ++ it)
196 {
197 HRESULT rc = (*it)->UnlockWrite (NULL);
198 AssertComRC (rc);
199
200 (*it)->releaseCaller();
201 }
202
203 for (iterator it = begin(); it != end(); ++ it)
204 {
205 AutoWriteLock alock (*it);
206 Assert ((*it)->m.state == MediaState_LockedWrite ||
207 (*it)->m.state == MediaState_Deleting);
208 if ((*it)->m.state == MediaState_LockedWrite)
209 (*it)->UnlockWrite (NULL);
210 else
211 (*it)->m.state = MediaState_Created;
212
213 (*it)->releaseCaller();
214 }
215
216 if (!mParent.isNull())
217 mParent->releaseCaller();
218 }
219
220 HRESULT addSource (HardDisk2 *aHardDisk)
221 {
222 HRESULT rc = aHardDisk->addCaller();
223 CheckComRCReturnRC (rc);
224
225 AutoWriteLock alock (aHardDisk);
226
227 if (mForward)
228 {
229 rc = checkChildrenAndAttachmentsAndImmutable (aHardDisk);
230 if (FAILED (rc))
231 {
232 aHardDisk->releaseCaller();
233 return rc;
234 }
235 }
236
237 /* go to Deleting */
238 switch (aHardDisk->m.state)
239 {
240 case MediaState_Created:
241 aHardDisk->m.state = MediaState_Deleting;
242 break;
243 default:
244 aHardDisk->releaseCaller();
245 return aHardDisk->setStateError();
246 }
247
248 push_front (aHardDisk);
249
250 if (mForward)
251 {
252 /* we will need parent to reparent target */
253 if (!aHardDisk->mParent.isNull())
254 {
255 rc = aHardDisk->mParent->addCaller();
256 CheckComRCReturnRC (rc);
257
258 mParent = aHardDisk->mParent;
259 }
260 }
261 else
262 {
263 /* we will need to reparent children */
264 for (List::const_iterator it = aHardDisk->children().begin();
265 it != aHardDisk->children().end(); ++ it)
266 {
267 rc = (*it)->addCaller();
268 CheckComRCReturnRC (rc);
269
270 rc = (*it)->LockWrite (NULL);
271 if (FAILED (rc))
272 {
273 (*it)->releaseCaller();
274 return rc;
275 }
276
277 mChildren.push_back (*it);
278 }
279 }
280
281 return S_OK;
282 }
283
284 HRESULT addTarget (HardDisk2 *aHardDisk)
285 {
286 HRESULT rc = aHardDisk->addCaller();
287 CheckComRCReturnRC (rc);
288
289 AutoWriteLock alock (aHardDisk);
290
291 if (!mForward)
292 {
293 rc = checkChildrenAndImmutable (aHardDisk);
294 if (FAILED (rc))
295 {
296 aHardDisk->releaseCaller();
297 return rc;
298 }
299 }
300
301 /* go to LockedWrite */
302 rc = aHardDisk->LockWrite (NULL);
303 if (FAILED (rc))
304 {
305 aHardDisk->releaseCaller();
306 return rc;
307 }
308
309 push_front (aHardDisk);
310
311 return S_OK;
312 }
313
314 HRESULT addIntermediate (HardDisk2 *aHardDisk)
315 {
316 HRESULT rc = aHardDisk->addCaller();
317 CheckComRCReturnRC (rc);
318
319 AutoWriteLock alock (aHardDisk);
320
321 rc = checkChildrenAndAttachments (aHardDisk);
322 if (FAILED (rc))
323 {
324 aHardDisk->releaseCaller();
325 return rc;
326 }
327
328 /* go to Deleting */
329 switch (aHardDisk->m.state)
330 {
331 case MediaState_Created:
332 aHardDisk->m.state = MediaState_Deleting;
333 break;
334 default:
335 aHardDisk->releaseCaller();
336 return aHardDisk->setStateError();
337 }
338
339 push_front (aHardDisk);
340
341 return S_OK;
342 }
343
344 bool isForward() const { return mForward; }
345 HardDisk2 *parent() const { return mParent; }
346 const List &children() const { return mChildren; }
347
348 HardDisk2 *source() const
349 { AssertReturn (size() > 0, NULL); return mForward ? front() : back(); }
350
351 HardDisk2 *target() const
352 { AssertReturn (size() > 0, NULL); return mForward ? back() : front(); }
353
354protected:
355
356 // SupportErrorInfoBase interface
357 const GUID &mainInterfaceID() const { return COM_IIDOF (IHardDisk2); }
358 const char *componentName() const { return HardDisk2::ComponentName(); }
359
360private:
361
362 HRESULT check (HardDisk2 *aHardDisk, bool aChildren, bool aAttachments,
363 bool aImmutable)
364 {
365 if (aChildren)
366 {
367 /* not going to multi-merge as it's too expensive */
368 if (aHardDisk->children().size() > 1)
369 {
370 return setError (E_FAIL,
371 tr ("Hard disk '%ls' involved in the merge operation "
372 "has more than one child hard disk (%d)"),
373 aHardDisk->m.locationFull.raw(),
374 aHardDisk->children().size());
375 }
376 }
377
378 if (aAttachments && !mIgnoreAttachments)
379 {
380 if (aHardDisk->m.backRefs.size() != 0)
381 return setError (E_FAIL,
382 tr ("Hard disk '%ls' is attached to %d virtual machines"),
383 aHardDisk->m.locationFull.raw(),
384 aHardDisk->m.backRefs.size());
385 }
386
387 if (aImmutable)
388 {
389 if (aHardDisk->mm.type == HardDiskType_Immutable)
390 return setError (E_FAIL,
391 tr ("Hard disk '%ls' is immutable"),
392 aHardDisk->m.locationFull.raw());
393 }
394
395 return S_OK;
396 }
397
398 HRESULT checkChildren (HardDisk2 *aHardDisk)
399 { return check (aHardDisk, true, false, false); }
400
401 HRESULT checkChildrenAndImmutable (HardDisk2 *aHardDisk)
402 { return check (aHardDisk, true, false, true); }
403
404 HRESULT checkChildrenAndAttachments (HardDisk2 *aHardDisk)
405 { return check (aHardDisk, true, true, false); }
406
407 HRESULT checkChildrenAndAttachmentsAndImmutable (HardDisk2 *aHardDisk)
408 { return check (aHardDisk, true, true, true); }
409
410 /** true if forward merge, false if backward */
411 bool mForward : 1;
412 /** true to not perform attachment checks */
413 bool mIgnoreAttachments : 1;
414
415 /** Parent of the source when forward merge (if any) */
416 ComObjPtr <HardDisk2> mParent;
417 /** Children of the source when backward merge (if any) */
418 List mChildren;
419};
420
421////////////////////////////////////////////////////////////////////////////////
422// HardDisk2 class
423////////////////////////////////////////////////////////////////////////////////
424
425// constructor / destructor
426////////////////////////////////////////////////////////////////////////////////
427
428DEFINE_EMPTY_CTOR_DTOR (HardDisk2)
429
430HRESULT HardDisk2::FinalConstruct()
431{
432 /* Initialize the callbacks of the VD error interface */
433 mm.vdIfCallsError.cbSize = sizeof (VDINTERFACEERROR);
434 mm.vdIfCallsError.enmInterface = VDINTERFACETYPE_ERROR;
435 mm.vdIfCallsError.pfnError = vdErrorCall;
436
437 /* Initialize the callbacks of the VD progress interface */
438 mm.vdIfCallsProgress.cbSize = sizeof (VDINTERFACEPROGRESS);
439 mm.vdIfCallsProgress.enmInterface = VDINTERFACETYPE_PROGRESS;
440 mm.vdIfCallsProgress.pfnProgress = vdProgressCall;
441
442 /* Initialize the callbacks of the VD config interface */
443 mm.vdIfCallsConfig.cbSize = sizeof (VDINTERFACECONFIG);
444 mm.vdIfCallsConfig.enmInterface = VDINTERFACETYPE_CONFIG;
445 mm.vdIfCallsConfig.pfnAreKeysValid = vdConfigAreKeysValid;
446 mm.vdIfCallsConfig.pfnQuerySize = vdConfigQuerySize;
447 mm.vdIfCallsConfig.pfnQuery = vdConfigQuery;
448
449 /* Initialize the callbacks of the VD TCP interface (we always use the host
450 * IP stack for now) */
451 mm.vdIfCallsTcpNet.cbSize = sizeof (VDINTERFACETCPNET);
452 mm.vdIfCallsTcpNet.enmInterface = VDINTERFACETYPE_TCPNET;
453 mm.vdIfCallsTcpNet.pfnClientConnect = RTTcpClientConnect;
454 mm.vdIfCallsTcpNet.pfnClientClose = RTTcpClientClose;
455 mm.vdIfCallsTcpNet.pfnSelectOne = RTTcpSelectOne;
456 mm.vdIfCallsTcpNet.pfnRead = RTTcpRead;
457 mm.vdIfCallsTcpNet.pfnWrite = RTTcpWrite;
458 mm.vdIfCallsTcpNet.pfnFlush = RTTcpFlush;
459
460 /* Initialize the per-disk interface chain */
461 int vrc;
462 vrc = VDInterfaceAdd (&mm.vdIfError,
463 "HardDisk2::vdInterfaceError",
464 VDINTERFACETYPE_ERROR,
465 &mm.vdIfCallsError, this, &mm.vdDiskIfaces);
466 AssertRCReturn (vrc, E_FAIL);
467
468 vrc = VDInterfaceAdd (&mm.vdIfProgress,
469 "HardDisk2::vdInterfaceProgress",
470 VDINTERFACETYPE_PROGRESS,
471 &mm.vdIfCallsProgress, this, &mm.vdDiskIfaces);
472 AssertRCReturn (vrc, E_FAIL);
473
474 vrc = VDInterfaceAdd (&mm.vdIfConfig,
475 "HardDisk2::vdInterfaceConfig",
476 VDINTERFACETYPE_CONFIG,
477 &mm.vdIfCallsConfig, this, &mm.vdDiskIfaces);
478 AssertRCReturn (vrc, E_FAIL);
479
480 vrc = VDInterfaceAdd (&mm.vdIfTcpNet,
481 "HardDisk2::vdInterfaceTcpNet",
482 VDINTERFACETYPE_TCPNET,
483 &mm.vdIfCallsTcpNet, this, &mm.vdDiskIfaces);
484 AssertRCReturn (vrc, E_FAIL);
485
486 return S_OK;
487}
488
489void HardDisk2::FinalRelease()
490{
491 uninit();
492}
493
494// public initializer/uninitializer for internal purposes only
495////////////////////////////////////////////////////////////////////////////////
496
497/**
498 * Initializes the hard disk object without creating or opening an associated
499 * storage unit.
500 *
501 * For hard disks that don't have the VD_CAP_CREATE_FIXED or
502 * VD_CAP_CREATE_DYNAMIC capability (and therefore cannot be created or deleted
503 * with the means of VirtualBox) the associated storage unit is assumed to be
504 * ready for use so the state of the hard disk object will be set to Created.
505 *
506 * @param aVirtualBox VirtualBox object.
507 * @param aLocaiton Storage unit location.
508 */
509HRESULT HardDisk2::init (VirtualBox *aVirtualBox, CBSTR aFormat,
510 CBSTR aLocation)
511{
512 AssertReturn (aVirtualBox != NULL, E_FAIL);
513 AssertReturn (aFormat != NULL && *aFormat != '\0', E_FAIL);
514
515 /* Enclose the state transition NotReady->InInit->Ready */
516 AutoInitSpan autoInitSpan (this);
517 AssertReturn (autoInitSpan.isOk(), E_FAIL);
518
519 HRESULT rc = S_OK;
520
521 /* share VirtualBox weakly (parent remains NULL so far) */
522 unconst (mVirtualBox) = aVirtualBox;
523
524 /* register with VirtualBox early, since uninit() will
525 * unconditionally unregister on failure */
526 aVirtualBox->addDependentChild (this);
527
528 /* no storage yet */
529 m.state = MediaState_NotCreated;
530
531 /* No storage unit is created yet, no need to queryInfo() */
532
533 rc = setFormat (aFormat);
534 CheckComRCReturnRC (rc);
535
536 if (mm.formatObj->capabilities() & HardDiskFormatCapabilities_File)
537 {
538 rc = setLocation (aLocation);
539 CheckComRCReturnRC (rc);
540 }
541 else
542 {
543 rc = setLocation (aLocation);
544 CheckComRCReturnRC (rc);
545
546 /// @todo later we may want to use a pfnComposeLocation backend info
547 /// callback to generate a well-formed location value (based on the hard
548 /// disk properties we have) rather than allowing each caller to invent
549 /// its own (pseudo-)location.
550 }
551
552 if (!(mm.formatObj->capabilities() &
553 (HardDiskFormatCapabilities_CreateFixed |
554 HardDiskFormatCapabilities_CreateDynamic)))
555 {
556 /* storage for hard disks of this format can neither be explicitly
557 * created by VirtualBox nor deleted, so we place the hard disk to
558 * Created state here and also add it to the registry */
559 m.state = MediaState_Created;
560 unconst (m.id).create();
561 rc = mVirtualBox->registerHardDisk2 (this);
562
563 /// @todo later we may want to use a pfnIsConfigSufficient backend info
564 /// callback that would tell us when we have enough properties to work
565 /// with the hard disk and this information could be used to actually
566 /// move such hard disks from NotCreated to Created state. Instead of
567 /// pfnIsConfigSufficient we can use HardDiskFormat property
568 /// descriptions to see which properties are mandatory
569 }
570
571 /* Confirm a successful initialization when it's the case */
572 if (SUCCEEDED (rc))
573 autoInitSpan.setSucceeded();
574
575 return rc;
576}
577
578/**
579 * Initializes the hard disk object by opening the storage unit at the specified
580 * location.
581 *
582 * Note that the UUID, format and the parent of this hard disk will be
583 * determined when reading the hard disk storage unit. If the detected parent is
584 * not known to VirtualBox, then this method will fail.
585 *
586 * @param aVirtualBox VirtualBox object.
587 * @param aLocaiton Storage unit location.
588 */
589HRESULT HardDisk2::init (VirtualBox *aVirtualBox, CBSTR aLocation)
590{
591 AssertReturn (aVirtualBox, E_INVALIDARG);
592 AssertReturn (aLocation, E_INVALIDARG);
593
594 /* Enclose the state transition NotReady->InInit->Ready */
595 AutoInitSpan autoInitSpan (this);
596 AssertReturn (autoInitSpan.isOk(), E_FAIL);
597
598 HRESULT rc = S_OK;
599
600 /* share VirtualBox weakly (parent remains NULL so far) */
601 unconst (mVirtualBox) = aVirtualBox;
602
603 /* register with VirtualBox early, since uninit() will
604 * unconditionally unregister on failure */
605 aVirtualBox->addDependentChild (this);
606
607 /* there must be a storage unit */
608 m.state = MediaState_Created;
609
610 rc = setLocation (aLocation);
611 CheckComRCReturnRC (rc);
612
613 /* get all the information about the medium from the storage unit */
614 rc = queryInfo();
615 if (SUCCEEDED (rc))
616 {
617 /* if the storage unit is not accessible, it's not acceptable for the
618 * newly opened media so convert this into an error */
619 if (m.state == MediaState_Inaccessible)
620 {
621 Assert (!m.lastAccessError.isEmpty());
622 rc = setError (E_FAIL, Utf8Str (m.lastAccessError));
623 }
624
625 /* storage format must be detected by queryInfo() if the medium is
626 * accessible */
627 AssertReturn (!m.id.isEmpty() && !mm.format.isNull(), E_FAIL);
628 }
629
630 /* Confirm a successful initialization when it's the case */
631 if (SUCCEEDED (rc))
632 autoInitSpan.setSucceeded();
633
634 return rc;
635}
636
637/**
638 * Initializes the hard disk object by loading its data from the given settings
639 * node.
640 *
641 * @param aVirtualBox VirtualBox object.
642 * @param aParent Parent hard disk or NULL for a root hard disk.
643 * @param aNode <HardDisk> settings node.
644 *
645 * @note Locks VirtualBox lock for writing, treeLock() for writing.
646 */
647HRESULT HardDisk2::init (VirtualBox *aVirtualBox, HardDisk2 *aParent,
648 const settings::Key &aNode)
649{
650 using namespace settings;
651
652 AssertReturn (aVirtualBox, E_INVALIDARG);
653
654 /* Enclose the state transition NotReady->InInit->Ready */
655 AutoInitSpan autoInitSpan (this);
656 AssertReturn (autoInitSpan.isOk(), E_FAIL);
657
658 HRESULT rc = S_OK;
659
660 /* share VirtualBox and parent weakly */
661 unconst (mVirtualBox) = aVirtualBox;
662
663 /* register with VirtualBox/parent early, since uninit() will
664 * unconditionally unregister on failure */
665 if (aParent == NULL)
666 aVirtualBox->addDependentChild (this);
667 else
668 {
669 /* we set mParent */
670 AutoWriteLock treeLock (this->treeLock());
671
672 mParent = aParent;
673 aParent->addDependentChild (this);
674 }
675
676 /* see below why we don't call queryInfo() (and therefore treat the medium
677 * as inaccessible for now */
678 m.state = MediaState_Inaccessible;
679 m.lastAccessError = tr ("Accessibility check was not yet performed");
680
681 /* required */
682 unconst (m.id) = aNode.value <Guid> ("uuid");
683
684 /* optional */
685 {
686 settings::Key descNode = aNode.findKey ("Description");
687 if (!descNode.isNull())
688 m.description = descNode.keyStringValue();
689 }
690
691 /* required */
692 Bstr format = aNode.stringValue ("format");
693 AssertReturn (!format.isNull(), E_FAIL);
694 rc = setFormat (format);
695 CheckComRCReturnRC (rc);
696
697 /* properties (after setting the format as it populates the map). Note that
698 * if some properties are not supported but preseint in the settings file,
699 * they will still be read and accessible (for possible backward
700 * compatibility; we can also clean them up from the XML upon next
701 * XML format versino change if we wish) */
702 Key::List properties = aNode.keys ("Property");
703 for (Key::List::const_iterator it = properties.begin();
704 it != properties.end(); ++ it)
705 {
706 mm.properties [Bstr (it->stringValue ("name"))] =
707 Bstr (it->stringValue ("value"));
708 }
709
710 /* required */
711 Bstr location = aNode.stringValue ("location");
712 rc = setLocation (location);
713 CheckComRCReturnRC (rc);
714
715 /* type is only for base hard disks */
716 if (mParent.isNull())
717 {
718 const char *type = aNode.stringValue ("type");
719 if (strcmp (type, "Normal") == 0)
720 mm.type = HardDiskType_Normal;
721 else if (strcmp (type, "Immutable") == 0)
722 mm.type = HardDiskType_Immutable;
723 else if (strcmp (type, "Writethrough") == 0)
724 mm.type = HardDiskType_Writethrough;
725 else
726 AssertFailed();
727 }
728
729 LogFlowThisFunc (("m.locationFull='%ls', mm.format=%ls, m.id={%RTuuid}\n",
730 m.locationFull.raw(), mm.format.raw(), m.id.raw()));
731
732 /* Don't call queryInfo() for registered media to prevent the calling
733 * thread (i.e. the VirtualBox server startup thread) from an unexpected
734 * freeze but mark it as initially inaccessible instead. The vital UUID,
735 * location and format properties are read from the registry file above; to
736 * get the actual state and the rest of the data, the user will have to call
737 * COMGETTER(State). */
738
739 /* load all children */
740 Key::List hardDisks = aNode.keys ("HardDisk");
741 for (Key::List::const_iterator it = hardDisks.begin();
742 it != hardDisks.end(); ++ it)
743 {
744 ComObjPtr <HardDisk2> hardDisk;
745 hardDisk.createObject();
746 rc = hardDisk->init (aVirtualBox, this, *it);
747 CheckComRCBreakRC (rc);
748
749 rc = mVirtualBox->registerHardDisk2 (hardDisk, false /* aSaveRegistry */);
750 CheckComRCBreakRC (rc);
751 }
752
753 /* Confirm a successful initialization when it's the case */
754 if (SUCCEEDED (rc))
755 autoInitSpan.setSucceeded();
756
757 return rc;
758}
759
760/**
761 * Uninitializes the instance.
762 *
763 * Called either from FinalRelease() or by the parent when it gets destroyed.
764 *
765 * @note All children of this hard disk get uninitialized by calling their
766 * uninit() methods.
767 *
768 * @note Locks treeLock() for writing, VirtualBox for writing.
769 */
770void HardDisk2::uninit()
771{
772 /* Enclose the state transition Ready->InUninit->NotReady */
773 AutoUninitSpan autoUninitSpan (this);
774 if (autoUninitSpan.uninitDone())
775 return;
776
777 if (!mm.formatObj.isNull())
778 {
779 /* remove the caller reference we added in setFormat() */
780 mm.formatObj->releaseCaller();
781 mm.formatObj.setNull();
782 }
783
784 if (m.state == MediaState_Deleting)
785 {
786 /* we are being uninitialized after've been deleted by merge.
787 * Reparenting has already been done so don't touch it here (we are
788 * now orphans and remoeDependentChild() will assert) */
789
790 Assert (mParent.isNull());
791 }
792 else
793 {
794 /* we uninit children and reset mParent
795 * and VirtualBox::removeDependentChild() needs a write lock */
796 AutoMultiWriteLock2 alock (mVirtualBox->lockHandle(), this->treeLock());
797
798 uninitDependentChildren();
799
800 if (!mParent.isNull())
801 {
802 mParent->removeDependentChild (this);
803 mParent.setNull();
804 }
805 else
806 mVirtualBox->removeDependentChild (this);
807 }
808
809 unconst (mVirtualBox).setNull();
810}
811
812// IHardDisk2 properties
813////////////////////////////////////////////////////////////////////////////////
814
815STDMETHODIMP HardDisk2::COMGETTER(Format) (BSTR *aFormat)
816{
817 if (aFormat == NULL)
818 return E_POINTER;
819
820 AutoCaller autoCaller (this);
821 CheckComRCReturnRC (autoCaller.rc());
822
823 /* no need to lock, mm.format is const */
824 mm.format.cloneTo (aFormat);
825
826 return S_OK;
827}
828
829STDMETHODIMP HardDisk2::COMGETTER(Type) (HardDiskType_T *aType)
830{
831 if (aType == NULL)
832 return E_POINTER;
833
834 AutoCaller autoCaller (this);
835 CheckComRCReturnRC (autoCaller.rc());
836
837 AutoReadLock alock (this);
838
839 *aType = mm.type;
840
841 return S_OK;
842}
843
844STDMETHODIMP HardDisk2::COMSETTER(Type) (HardDiskType_T aType)
845{
846 AutoCaller autoCaller (this);
847 CheckComRCReturnRC (autoCaller.rc());
848
849 /* VirtualBox::saveSettings() needs a write lock */
850 AutoMultiWriteLock2 alock (mVirtualBox, this);
851
852 switch (m.state)
853 {
854 case MediaState_Created:
855 case MediaState_Inaccessible:
856 break;
857 default:
858 return setStateError();
859 }
860
861 if (mm.type == aType)
862 {
863 /* Nothing to do */
864 return S_OK;
865 }
866
867 /* we access mParent & children() */
868 AutoReadLock treeLock (this->treeLock());
869
870 /* cannot change the type of a differencing hard disk */
871 if (!mParent.isNull())
872 return setError (E_FAIL,
873 tr ("Hard disk '%ls' is a differencing hard disk"),
874 m.locationFull.raw());
875
876 /* cannot change the type of a hard disk being in use */
877 if (m.backRefs.size() != 0)
878 return setError (E_FAIL,
879 tr ("Hard disk '%ls' is attached to %d virtual machines"),
880 m.locationFull.raw(), m.backRefs.size());
881
882 switch (aType)
883 {
884 case HardDiskType_Normal:
885 case HardDiskType_Immutable:
886 {
887 /* normal can be easily converted to imutable and vice versa even
888 * if they have children as long as they are not attached to any
889 * machine themselves */
890 break;
891 }
892 case HardDiskType_Writethrough:
893 {
894 /* cannot change to writethrough if there are children */
895 if (children().size() != 0)
896 return setError (E_FAIL,
897 tr ("Hard disk '%ls' has %d child hard disks"),
898 children().size());
899 break;
900 }
901 default:
902 AssertFailedReturn (E_FAIL);
903 }
904
905 mm.type = aType;
906
907 HRESULT rc = mVirtualBox->saveSettings();
908
909 return rc;
910}
911
912STDMETHODIMP HardDisk2::COMGETTER(Parent) (IHardDisk2 **aParent)
913{
914 if (aParent == NULL)
915 return E_POINTER;
916
917 AutoCaller autoCaller (this);
918 CheckComRCReturnRC (autoCaller.rc());
919
920 /* we access mParent */
921 AutoReadLock treeLock (this->treeLock());
922
923 mParent.queryInterfaceTo (aParent);
924
925 return S_OK;
926}
927
928STDMETHODIMP HardDisk2::COMGETTER(Children) (ComSafeArrayOut (IHardDisk2 *, aChildren))
929{
930 if (ComSafeArrayOutIsNull (aChildren))
931 return E_POINTER;
932
933 AutoCaller autoCaller (this);
934 CheckComRCReturnRC (autoCaller.rc());
935
936 /* we access children */
937 AutoReadLock treeLock (this->treeLock());
938
939 SafeIfaceArray <IHardDisk2> children (this->children());
940 children.detachTo (ComSafeArrayOutArg (aChildren));
941
942 return S_OK;
943}
944
945STDMETHODIMP HardDisk2::COMGETTER(Root) (IHardDisk2 **aRoot)
946{
947 if (aRoot == NULL)
948 return E_POINTER;
949
950 /* root() will do callers/locking */
951
952 root().queryInterfaceTo (aRoot);
953
954 return S_OK;
955}
956
957STDMETHODIMP HardDisk2::COMGETTER(ReadOnly) (BOOL *aReadOnly)
958{
959 if (aReadOnly == NULL)
960 return E_POINTER;
961
962 AutoCaller autoCaller (this);
963 CheckComRCReturnRC (autoCaller.rc());
964
965 /* isRadOnly() will do locking */
966
967 *aReadOnly = isReadOnly();
968
969 return S_OK;
970}
971
972STDMETHODIMP HardDisk2::COMGETTER(LogicalSize) (ULONG64 *aLogicalSize)
973{
974 if (aLogicalSize == NULL)
975 return E_POINTER;
976
977 {
978 AutoCaller autoCaller (this);
979 CheckComRCReturnRC (autoCaller.rc());
980
981 AutoReadLock alock (this);
982
983 /* we access mParent */
984 AutoReadLock treeLock (this->treeLock());
985
986 if (mParent.isNull())
987 {
988 *aLogicalSize = mm.logicalSize;
989
990 return S_OK;
991 }
992 }
993
994 /* We assume that some backend may decide to return a meaningless value in
995 * response to VDGetSize() for differencing hard disks and therefore
996 * always ask the base hard disk ourselves. */
997
998 /* root() will do callers/locking */
999
1000 return root()->COMGETTER (LogicalSize) (aLogicalSize);
1001}
1002
1003// IHardDisk2 methods
1004////////////////////////////////////////////////////////////////////////////////
1005
1006STDMETHODIMP HardDisk2::GetProperty (IN_BSTR aName, BSTR *aValue)
1007{
1008 CheckComArgStrNotEmptyOrNull (aName);
1009 CheckComArgOutPointerValid (aValue);
1010
1011 AutoCaller autoCaller (this);
1012 CheckComRCReturnRC (autoCaller.rc());
1013
1014 AutoReadLock alock (this);
1015
1016 Data::PropertyMap::const_iterator it = mm.properties.find (Bstr (aName));
1017 if (it == mm.properties.end())
1018 return setError (VBOX_E_OBJECT_NOT_FOUND,
1019 tr ("Property '%ls' does not exist"), aName);
1020
1021 it->second.cloneTo (aValue);
1022
1023 return S_OK;
1024}
1025
1026STDMETHODIMP HardDisk2::SetProperty (IN_BSTR aName, IN_BSTR aValue)
1027{
1028 CheckComArgStrNotEmptyOrNull (aName);
1029
1030 AutoCaller autoCaller (this);
1031 CheckComRCReturnRC (autoCaller.rc());
1032
1033 /* VirtualBox::saveSettings() needs a write lock */
1034 AutoMultiWriteLock2 alock (mVirtualBox, this);
1035
1036 switch (m.state)
1037 {
1038 case MediaState_Created:
1039 case MediaState_Inaccessible:
1040 break;
1041 default:
1042 return setStateError();
1043 }
1044
1045 Data::PropertyMap::iterator it = mm.properties.find (Bstr (aName));
1046 if (it == mm.properties.end())
1047 return setError (VBOX_E_OBJECT_NOT_FOUND,
1048 tr ("Property '%ls' does not exist"), aName);
1049
1050 it->second = aValue;
1051
1052 HRESULT rc = mVirtualBox->saveSettings();
1053
1054 return rc;
1055}
1056
1057STDMETHODIMP HardDisk2::GetProperties (IN_BSTR aNames,
1058 ComSafeArrayOut (BSTR, aReturnNames),
1059 ComSafeArrayOut (BSTR, aReturnValues))
1060{
1061 CheckComArgOutSafeArrayPointerValid (aReturnNames);
1062 CheckComArgOutSafeArrayPointerValid (aReturnValues);
1063
1064 AutoCaller autoCaller (this);
1065 CheckComRCReturnRC (autoCaller.rc());
1066
1067 AutoReadLock alock (this);
1068
1069 /// @todo make use of aNames according to the documentation
1070 NOREF (aNames);
1071
1072 com::SafeArray <BSTR> names (mm.properties.size());
1073 com::SafeArray <BSTR> values (mm.properties.size());
1074 size_t i = 0;
1075
1076 for (Data::PropertyMap::const_iterator it = mm.properties.begin();
1077 it != mm.properties.end(); ++ it)
1078 {
1079 it->first.cloneTo (&names [i]);
1080 it->second.cloneTo (&values [i]);
1081 ++ i;
1082 }
1083
1084 names.detachTo (ComSafeArrayOutArg (aReturnNames));
1085 values.detachTo (ComSafeArrayOutArg (aReturnValues));
1086
1087 return S_OK;
1088}
1089
1090STDMETHODIMP HardDisk2::SetProperties (ComSafeArrayIn (IN_BSTR, aNames),
1091 ComSafeArrayIn (IN_BSTR, aValues))
1092{
1093 CheckComArgSafeArrayNotNull (aNames);
1094 CheckComArgSafeArrayNotNull (aValues);
1095
1096 AutoCaller autoCaller (this);
1097 CheckComRCReturnRC (autoCaller.rc());
1098
1099 /* VirtualBox::saveSettings() needs a write lock */
1100 AutoMultiWriteLock2 alock (mVirtualBox, this);
1101
1102 com::SafeArray <IN_BSTR> names (ComSafeArrayInArg (aNames));
1103 com::SafeArray <IN_BSTR> values (ComSafeArrayInArg (aValues));
1104
1105 /* first pass: validate names */
1106 for (size_t i = 0; i < names.size(); ++ i)
1107 {
1108 if (mm.properties.find (Bstr (names [i])) == mm.properties.end())
1109 return setError (VBOX_E_OBJECT_NOT_FOUND,
1110 tr ("Property '%ls' does not exist"), names [i]);
1111 }
1112
1113 /* second pass: assign */
1114 for (size_t i = 0; i < names.size(); ++ i)
1115 {
1116 Data::PropertyMap::iterator it = mm.properties.find (Bstr (names [i]));
1117 AssertReturn (it != mm.properties.end(), E_FAIL);
1118
1119 it->second = values [i];
1120 }
1121
1122 HRESULT rc = mVirtualBox->saveSettings();
1123
1124 return rc;
1125}
1126
1127STDMETHODIMP HardDisk2::CreateDynamicStorage (ULONG64 aLogicalSize,
1128 IProgress **aProgress)
1129{
1130 if (aProgress == NULL)
1131 return E_POINTER;
1132
1133 AutoCaller autoCaller (this);
1134 CheckComRCReturnRC (autoCaller.rc());
1135
1136 AutoWriteLock alock (this);
1137
1138 if (!(mm.formatObj->capabilities() &
1139 HardDiskFormatCapabilities_CreateDynamic))
1140 return setError (VBOX_E_NOT_SUPPORTED,
1141 tr ("Hard disk format '%ls' does not support dynamic storage "
1142 "creation"), mm.format.raw());
1143
1144 switch (m.state)
1145 {
1146 case MediaState_NotCreated:
1147 break;
1148 default:
1149 return setStateError();
1150 }
1151
1152 ComObjPtr <Progress> progress;
1153 progress.createObject();
1154 HRESULT rc = progress->init (mVirtualBox, static_cast <IHardDisk2 *> (this),
1155 BstrFmt (tr ("Creating dynamic hard disk storage unit '%ls'"),
1156 m.location.raw()),
1157 FALSE /* aCancelable */);
1158 CheckComRCReturnRC (rc);
1159
1160 /* setup task object and thread to carry out the operation
1161 * asynchronously */
1162
1163 std::auto_ptr <Task> task (new Task (this, progress, Task::CreateDynamic));
1164 AssertComRCReturnRC (task->autoCaller.rc());
1165
1166 task->d.size = aLogicalSize;
1167
1168 rc = task->startThread();
1169 CheckComRCReturnRC (rc);
1170
1171 /* go to Creating state on success */
1172 m.state = MediaState_Creating;
1173
1174 /* task is now owned by taskThread() so release it */
1175 task.release();
1176
1177 /* return progress to the caller */
1178 progress.queryInterfaceTo (aProgress);
1179
1180 return S_OK;
1181}
1182
1183STDMETHODIMP HardDisk2::CreateFixedStorage (ULONG64 aLogicalSize,
1184 IProgress **aProgress)
1185{
1186 if (aProgress == NULL)
1187 return E_POINTER;
1188
1189 AutoCaller autoCaller (this);
1190 CheckComRCReturnRC (autoCaller.rc());
1191
1192 AutoWriteLock alock (this);
1193
1194 if (!(mm.formatObj->capabilities() &
1195 HardDiskFormatCapabilities_CreateFixed))
1196 return setError (VBOX_E_NOT_SUPPORTED,
1197 tr ("Hard disk format '%ls' does not support fixed storage "
1198 "creation"), mm.format.raw());
1199
1200 switch (m.state)
1201 {
1202 case MediaState_NotCreated:
1203 break;
1204 default:
1205 return setStateError();
1206 }
1207
1208 ComObjPtr <Progress> progress;
1209 progress.createObject();
1210 HRESULT rc = progress->init (mVirtualBox, static_cast <IHardDisk2 *> (this),
1211 BstrFmt (tr ("Creating fixed hard disk storage unit '%ls'"),
1212 m.location.raw()),
1213 FALSE /* aCancelable */);
1214 CheckComRCReturnRC (rc);
1215
1216 /* setup task object and thread to carry out the operation
1217 * asynchronously */
1218
1219 std::auto_ptr <Task> task (new Task (this, progress, Task::CreateFixed));
1220 AssertComRCReturnRC (task->autoCaller.rc());
1221
1222 task->d.size = aLogicalSize;
1223
1224 rc = task->startThread();
1225 CheckComRCReturnRC (rc);
1226
1227 /* go to Creating state on success */
1228 m.state = MediaState_Creating;
1229
1230 /* task is now owned by taskThread() so release it */
1231 task.release();
1232
1233 /* return progress to the caller */
1234 progress.queryInterfaceTo (aProgress);
1235
1236 return S_OK;
1237}
1238
1239STDMETHODIMP HardDisk2::DeleteStorage (IProgress **aProgress)
1240{
1241 if (aProgress == NULL)
1242 return E_POINTER;
1243
1244 ComObjPtr <Progress> progress;
1245
1246 HRESULT rc = deleteStorageNoWait (progress);
1247 if (SUCCEEDED (rc))
1248 {
1249 /* return progress to the caller */
1250 progress.queryInterfaceTo (aProgress);
1251 }
1252
1253 return rc;
1254}
1255
1256STDMETHODIMP HardDisk2::CreateDiffStorage (IHardDisk2 *aTarget, IProgress **aProgress)
1257{
1258 if (aTarget == NULL)
1259 return E_INVALIDARG;
1260 if (aProgress == NULL)
1261 return E_POINTER;
1262
1263 AutoCaller autoCaller (this);
1264 CheckComRCReturnRC (autoCaller.rc());
1265
1266 ComObjPtr <HardDisk2> diff;
1267 HRESULT rc = mVirtualBox->cast (aTarget, diff);
1268 CheckComRCReturnRC (rc);
1269
1270 AutoWriteLock alock (this);
1271
1272 if (mm.type == HardDiskType_Writethrough)
1273 return setError (E_FAIL, tr ("Hard disk '%ls' is Writethrough"));
1274
1275 /* We want to be locked for reading as long as our diff child is being
1276 * created */
1277 rc = LockRead (NULL);
1278 CheckComRCReturnRC (rc);
1279
1280 ComObjPtr <Progress> progress;
1281
1282 rc = createDiffStorageNoWait (diff, progress);
1283 if (FAILED (rc))
1284 {
1285 HRESULT rc2 = UnlockRead (NULL);
1286 AssertComRC (rc2);
1287 /* Note: on success, taskThread() will unlock this */
1288 }
1289 else
1290 {
1291 /* return progress to the caller */
1292 progress.queryInterfaceTo (aProgress);
1293 }
1294
1295 return rc;
1296}
1297
1298STDMETHODIMP HardDisk2::MergeTo (IN_GUID aTargetId, IProgress **aProgress)
1299{
1300 AutoCaller autoCaller (this);
1301 CheckComRCReturnRC (autoCaller.rc());
1302
1303 ReturnComNotImplemented();
1304}
1305
1306STDMETHODIMP HardDisk2::CloneTo (IHardDisk2 *aTarget, IProgress **aProgress)
1307{
1308 AutoCaller autoCaller (this);
1309 CheckComRCReturnRC (autoCaller.rc());
1310
1311 ReturnComNotImplemented();
1312}
1313
1314STDMETHODIMP HardDisk2::FlattenTo (IHardDisk2 *aTarget, IProgress **aProgress)
1315{
1316 AutoCaller autoCaller (this);
1317 CheckComRCReturnRC (autoCaller.rc());
1318
1319 ReturnComNotImplemented();
1320}
1321
1322// public methods for internal purposes only
1323////////////////////////////////////////////////////////////////////////////////
1324
1325/**
1326 * Checks if the given change of \a aOldPath to \a aNewPath affects the location
1327 * of this hard disk or any its child and updates the paths if necessary to
1328 * reflect the new location.
1329 *
1330 * @param aOldPath Old path (full).
1331 * @param aNewPath New path (full).
1332 *
1333 * @note Locks treeLock() for reading, this object and all children for writing.
1334 */
1335void HardDisk2::updatePaths (const char *aOldPath, const char *aNewPath)
1336{
1337 AssertReturnVoid (aOldPath);
1338 AssertReturnVoid (aNewPath);
1339
1340 AutoCaller autoCaller (this);
1341 AssertComRCReturnVoid (autoCaller.rc());
1342
1343 AutoWriteLock alock (this);
1344
1345 /* we access children() */
1346 AutoReadLock treeLock (this->treeLock());
1347
1348 updatePath (aOldPath, aNewPath);
1349
1350 /* update paths of all children */
1351 for (List::const_iterator it = children().begin();
1352 it != children().end();
1353 ++ it)
1354 {
1355 (*it)->updatePaths (aOldPath, aNewPath);
1356 }
1357}
1358
1359/**
1360 * Returns the base hard disk of the hard disk chain this hard disk is part of.
1361 *
1362 * The root hard disk is found by walking up the parent-child relationship axis.
1363 * If the hard disk doesn't have a parent (i.e. it's a base hard disk), it
1364 * returns itself in response to this method.
1365 *
1366 * @param aLevel Where to store the number of ancestors of this hard disk
1367 * (zero for the root), may be @c NULL.
1368 *
1369 * @note Locks treeLock() for reading.
1370 */
1371ComObjPtr <HardDisk2> HardDisk2::root (uint32_t *aLevel /*= NULL*/)
1372{
1373 ComObjPtr <HardDisk2> root;
1374 uint32_t level;
1375
1376 AutoCaller autoCaller (this);
1377 AssertReturn (autoCaller.isOk(), root);
1378
1379 /* we access mParent */
1380 AutoReadLock treeLock (this->treeLock());
1381
1382 root = this;
1383 level = 0;
1384
1385 if (!mParent.isNull())
1386 {
1387 for (;;)
1388 {
1389 AutoCaller rootCaller (root);
1390 AssertReturn (rootCaller.isOk(), root);
1391
1392 if (root->mParent.isNull())
1393 break;
1394
1395 root = root->mParent;
1396 ++ level;
1397 }
1398 }
1399
1400 if (aLevel != NULL)
1401 *aLevel = level;
1402
1403 return root;
1404}
1405
1406/**
1407 * Returns @c true if this hard disk cannot be modified because it has
1408 * dependants (children) or is part of the snapshot. Related to the hard disk
1409 * type and posterity, not to the current media state.
1410 *
1411 * @note Locks this object and treeLock() for reading.
1412 */
1413bool HardDisk2::isReadOnly()
1414{
1415 AutoCaller autoCaller (this);
1416 AssertComRCReturn (autoCaller.rc(), false);
1417
1418 AutoReadLock alock (this);
1419
1420 /* we access children */
1421 AutoReadLock treeLock (this->treeLock());
1422
1423 switch (mm.type)
1424 {
1425 case HardDiskType_Normal:
1426 {
1427 if (children().size() != 0)
1428 return true;
1429
1430 for (BackRefList::const_iterator it = m.backRefs.begin();
1431 it != m.backRefs.end(); ++ it)
1432 if (it->snapshotIds.size() != 0)
1433 return true;
1434
1435 return false;
1436 }
1437 case HardDiskType_Immutable:
1438 {
1439 return true;
1440 }
1441 case HardDiskType_Writethrough:
1442 {
1443 return false;
1444 }
1445 default:
1446 break;
1447 }
1448
1449 AssertFailedReturn (false);
1450}
1451
1452/**
1453 * Saves hard disk data by appending a new <HardDisk> child node to the given
1454 * parent node which can be either <HardDisks> or <HardDisk>.
1455 *
1456 * @param aaParentNode Parent <HardDisks> or <HardDisk> node.
1457 *
1458 * @note Locks this object, treeLock() and children for reading.
1459 */
1460HRESULT HardDisk2::saveSettings (settings::Key &aParentNode)
1461{
1462 using namespace settings;
1463
1464 AssertReturn (!aParentNode.isNull(), E_FAIL);
1465
1466 AutoCaller autoCaller (this);
1467 CheckComRCReturnRC (autoCaller.rc());
1468
1469 AutoReadLock alock (this);
1470
1471 /* we access mParent */
1472 AutoReadLock treeLock (this->treeLock());
1473
1474 Key diskNode = aParentNode.appendKey ("HardDisk");
1475 /* required */
1476 diskNode.setValue <Guid> ("uuid", m.id);
1477 /* required (note: the original locaiton, not full) */
1478 diskNode.setValue <Bstr> ("location", m.location);
1479 /* required */
1480 diskNode.setValue <Bstr> ("format", mm.format);
1481 /* optional */
1482 if (!m.description.isNull())
1483 {
1484 Key descNode = diskNode.createKey ("Description");
1485 descNode.setKeyValue <Bstr> (m.description);
1486 }
1487
1488 /* optional properties */
1489 for (Data::PropertyMap::const_iterator it = mm.properties.begin();
1490 it != mm.properties.end(); ++ it)
1491 {
1492 /* only save properties that have non-default values */
1493 if (!it->second.isNull())
1494 {
1495 Key propNode = diskNode.appendKey ("Property");
1496 propNode.setValue <Bstr> ("name", it->first);
1497 propNode.setValue <Bstr> ("value", it->second);
1498 }
1499 }
1500
1501 /* only for base hard disks */
1502 if (mParent.isNull())
1503 {
1504 const char *type =
1505 mm.type == HardDiskType_Normal ? "Normal" :
1506 mm.type == HardDiskType_Immutable ? "Immutable" :
1507 mm.type == HardDiskType_Writethrough ? "Writethrough" : NULL;
1508 Assert (type != NULL);
1509 diskNode.setStringValue ("type", type);
1510 }
1511
1512 /* save all children */
1513 for (List::const_iterator it = children().begin();
1514 it != children().end();
1515 ++ it)
1516 {
1517 HRESULT rc = (*it)->saveSettings (diskNode);
1518 AssertComRCReturnRC (rc);
1519 }
1520
1521 return S_OK;
1522}
1523
1524/**
1525 * Compares the location of this hard disk to the given location.
1526 *
1527 * The comparison takes the location details into account. For example, if the
1528 * location is a file in the host's filesystem, a case insensitive comparison
1529 * will be performed for case insensitive filesystems.
1530 *
1531 * @param aLocation Location to compare to (as is).
1532 * @param aResult Where to store the result of comparison: 0 if locations
1533 * are equal, 1 if this object's location is greater than
1534 * the specified location, and -1 otherwise.
1535 */
1536HRESULT HardDisk2::compareLocationTo (const char *aLocation, int &aResult)
1537{
1538 AutoCaller autoCaller (this);
1539 AssertComRCReturnRC (autoCaller.rc());
1540
1541 AutoReadLock alock (this);
1542
1543 Utf8Str locationFull (m.locationFull);
1544
1545 /// @todo NEWMEDIA delegate the comparison to the backend?
1546
1547 if (mm.formatObj->capabilities() & HardDiskFormatCapabilities_File)
1548 {
1549 Utf8Str location (aLocation);
1550
1551 /* For locations represented by files, append the default path if
1552 * only the name is given, and then get the full path. */
1553 if (!RTPathHavePath (aLocation))
1554 {
1555 AutoReadLock propsLock (mVirtualBox->systemProperties());
1556 location = Utf8StrFmt ("%ls%c%s",
1557 mVirtualBox->systemProperties()->defaultHardDiskFolder().raw(),
1558 RTPATH_DELIMITER, aLocation);
1559 }
1560
1561 int vrc = mVirtualBox->calculateFullPath (location, location);
1562 if (RT_FAILURE (vrc))
1563 return setError (E_FAIL,
1564 tr ("Invalid hard disk storage file location '%s' (%Rrc)"),
1565 location.raw(), vrc);
1566
1567 aResult = RTPathCompare (locationFull, location);
1568 }
1569 else
1570 aResult = locationFull.compare (aLocation);
1571
1572 return S_OK;
1573}
1574
1575/**
1576 * Returns a short version of the location attribute.
1577 *
1578 * Reimplements MediumBase::name() to specially treat non-FS-path locations.
1579 *
1580 * @note Must be called from under this object's read or write lock.
1581 */
1582Utf8Str HardDisk2::name()
1583{
1584 /// @todo NEWMEDIA treat non-FS-paths specially! (may require to requiest
1585 /// this information from the VD backend)
1586
1587 Utf8Str location (m.locationFull);
1588
1589 Utf8Str name = RTPathFilename (location);
1590 return name;
1591}
1592
1593/**
1594 * Checks that this hard disk may be discarded and performs necessary state
1595 * changes.
1596 *
1597 * This method is to be called prior to calling the #discrad() to perform
1598 * necessary consistency checks and place involved hard disks to appropriate
1599 * states. If #discard() is not called or fails, the state modifications
1600 * performed by this method must be undone by #cancelDiscard().
1601 *
1602 * See #discard() for more info about discarding hard disks.
1603 *
1604 * @param aChain Where to store the created merge chain (may return NULL
1605 * if no real merge is necessary).
1606 *
1607 * @note Locks treeLock() for reading. Locks this object, aTarget and all
1608 * intermediate hard disks for writing.
1609 */
1610HRESULT HardDisk2::prepareDiscard (MergeChain * &aChain)
1611{
1612 AutoCaller autoCaller (this);
1613 AssertComRCReturnRC (autoCaller.rc());
1614
1615 aChain = NULL;
1616
1617 AutoWriteLock alock (this);
1618
1619 /* we access mParent & children() */
1620 AutoReadLock treeLock (this->treeLock());
1621
1622 AssertReturn (mm.type == HardDiskType_Normal, E_FAIL);
1623
1624 if (children().size() == 0)
1625 {
1626 /* special treatment of the last hard disk in the chain: */
1627
1628 if (mParent.isNull())
1629 {
1630 /* lock only, to prevent any usage; discard() will unlock */
1631 return LockWrite (NULL);
1632 }
1633
1634 /* the differencing hard disk w/o children will be deleted, protect it
1635 * from attaching to other VMs (this is why Deleting) */
1636
1637 switch (m.state)
1638 {
1639 case MediaState_Created:
1640 m.state = MediaState_Deleting;
1641 break;
1642 default:
1643 return setStateError();
1644 }
1645
1646 /* aChain is intentionally NULL here */
1647
1648 return S_OK;
1649 }
1650
1651 /* not going multi-merge as it's too expensive */
1652 if (children().size() > 1)
1653 return setError (E_FAIL,
1654 tr ("Hard disk '%ls' has more than one child hard disk (%d)"),
1655 m.locationFull.raw(), children().size());
1656
1657 /* this is a read-only hard disk with children; it must be associated with
1658 * exactly one snapshot (when the snapshot is being taken, none of the
1659 * current VM's hard disks may be attached to other VMs). Note that by the
1660 * time when discard() is called, there must be no any attachments at all
1661 * (the code calling prepareDiscard() should detach). */
1662 AssertReturn (m.backRefs.size() == 1 &&
1663 !m.backRefs.front().inCurState &&
1664 m.backRefs.front().snapshotIds.size() == 1, E_FAIL);
1665
1666 ComObjPtr <HardDisk2> child = children().front();
1667
1668 /* we keep this locked, so lock the affected child to make sure the lock
1669 * order is correct when calling prepareMergeTo() */
1670 AutoWriteLock childLock (child);
1671
1672 /* delegate the rest to the profi */
1673 if (mParent.isNull())
1674 {
1675 /* base hard disk, backward merge */
1676
1677 Assert (child->m.backRefs.size() == 1);
1678 if (child->m.backRefs.front().machineId != m.backRefs.front().machineId)
1679 {
1680 /* backward merge is too tricky, we'll just detach on discard, so
1681 * lock only, to prevent any usage; discard() will only unlock
1682 * (since we return NULL in aChain) */
1683 return LockWrite (NULL);
1684 }
1685
1686 return child->prepareMergeTo (this, aChain,
1687 true /* aIgnoreAttachments */);
1688 }
1689 else
1690 {
1691 /* forward merge */
1692 return prepareMergeTo (child, aChain,
1693 true /* aIgnoreAttachments */);
1694 }
1695}
1696
1697/**
1698 * Discards this hard disk.
1699 *
1700 * Discarding the hard disk is merging its contents to its differencing child
1701 * hard disk (forward merge) or contents of its child hard disk to itself
1702 * (backward merge) if this hard disk is a base hard disk. If this hard disk is
1703 * a differencing hard disk w/o children, then it will be simply deleted.
1704 * Calling this method on a base hard disk w/o children will do nothing and
1705 * silently succeed. If this hard disk has more than one child, the method will
1706 * currently return an error (since merging in this case would be too expensive
1707 * and result in data duplication).
1708 *
1709 * When the backward merge takes place (i.e. this hard disk is a target) then,
1710 * on success, this hard disk will automatically replace the differencing child
1711 * hard disk used as a source (which will then be deleted) in the attachment
1712 * this child hard disk is associated with. This will happen only if both hard
1713 * disks belong to the same machine because otherwise such a replace would be
1714 * too tricky and could be not expected by the other machine. Same relates to a
1715 * case when the child hard disk is not associated with any machine at all. When
1716 * the backward merge is not applied, the method behaves as if the base hard
1717 * disk were not attached at all -- i.e. simply detaches it from the machine but
1718 * leaves the hard disk chain intact.
1719 *
1720 * This method is basically a wrapper around #mergeTo() that selects the correct
1721 * merge direction and performs additional actions as described above and.
1722 *
1723 * Note that this method will not return until the merge operation is complete
1724 * (which may be quite time consuming depending on the size of the merged hard
1725 * disks).
1726 *
1727 * Note that #prepareDiscard() must be called before calling this method. If
1728 * this method returns a failure, the caller must call #cancelDiscard(). On
1729 * success, #cancelDiscard() must not be called (this method will perform all
1730 * necessary steps such as resetting states of all involved hard disks and
1731 * deleting @a aChain).
1732 *
1733 * @param aChain Merge chain created by #prepareDiscard() (may be NULL if
1734 * no real merge takes place).
1735 *
1736 * @note Locks the hard disks from the chain for writing. Locks the machine
1737 * object when the backward merge takes place. Locks treeLock() lock for
1738 * reading or writing.
1739 */
1740HRESULT HardDisk2::discard (ComObjPtr <Progress> &aProgress, MergeChain *aChain)
1741{
1742 AssertReturn (!aProgress.isNull(), E_FAIL);
1743
1744 ComObjPtr <HardDisk2> hdFrom;
1745
1746 HRESULT rc = S_OK;
1747
1748 {
1749 AutoCaller autoCaller (this);
1750 AssertComRCReturnRC (autoCaller.rc());
1751
1752 aProgress->advanceOperation (BstrFmt (
1753 tr ("Discarding hard disk '%s'"), name().raw()));
1754
1755 if (aChain == NULL)
1756 {
1757 AutoWriteLock alock (this);
1758
1759 /* we access mParent & children() */
1760 AutoReadLock treeLock (this->treeLock());
1761
1762 Assert (children().size() == 0);
1763
1764 /* special treatment of the last hard disk in the chain: */
1765
1766 if (mParent.isNull())
1767 {
1768 rc = UnlockWrite (NULL);
1769 AssertComRC (rc);
1770 return rc;
1771 }
1772
1773 /* delete the differencing hard disk w/o children */
1774
1775 Assert (m.state == MediaState_Deleting);
1776
1777 /* go back to Created since deleteStorage() expects this state */
1778 m.state = MediaState_Created;
1779
1780 hdFrom = this;
1781
1782 rc = deleteStorageAndWait (&aProgress);
1783 }
1784 else
1785 {
1786 hdFrom = aChain->source();
1787
1788 rc = hdFrom->mergeToAndWait (aChain, &aProgress);
1789 }
1790 }
1791
1792 if (SUCCEEDED (rc))
1793 {
1794 /* mergeToAndWait() cannot uninitialize the initiator because of
1795 * possible AutoCallers on the current thread, deleteStorageAndWait()
1796 * doesn't do it either; do it ourselves */
1797 hdFrom->uninit();
1798 }
1799
1800 return rc;
1801}
1802
1803/**
1804 * Undoes what #prepareDiscard() did. Must be called if #discard() is not called
1805 * or fails. Frees memory occupied by @a aChain.
1806 *
1807 * @param aChain Merge chain created by #prepareDiscard() (may be NULL if
1808 * no real merge takes place).
1809 *
1810 * @note Locks the hard disks from the chain for writing. Locks treeLock() for
1811 * reading.
1812 */
1813void HardDisk2::cancelDiscard (MergeChain *aChain)
1814{
1815 AutoCaller autoCaller (this);
1816 AssertComRCReturnVoid (autoCaller.rc());
1817
1818 if (aChain == NULL)
1819 {
1820 AutoWriteLock alock (this);
1821
1822 /* we access mParent & children() */
1823 AutoReadLock treeLock (this->treeLock());
1824
1825 Assert (children().size() == 0);
1826
1827 /* special treatment of the last hard disk in the chain: */
1828
1829 if (mParent.isNull())
1830 {
1831 HRESULT rc = UnlockWrite (NULL);
1832 AssertComRC (rc);
1833 return;
1834 }
1835
1836 /* the differencing hard disk w/o children will be deleted, protect it
1837 * from attaching to other VMs (this is why Deleting) */
1838
1839 Assert (m.state == MediaState_Deleting);
1840 m.state = MediaState_Created;
1841
1842 return;
1843 }
1844
1845 /* delegate the rest to the profi */
1846 cancelMergeTo (aChain);
1847}
1848
1849/**
1850 * Returns a preferred format for differencing hard disks.
1851 */
1852Bstr HardDisk2::preferredDiffFormat()
1853{
1854 Bstr format;
1855
1856 AutoCaller autoCaller (this);
1857 AssertComRCReturn (autoCaller.rc(), format);
1858
1859 /* mm.format is const, no need to lock */
1860 format = mm.format;
1861
1862 /* check that our own format supports diffs */
1863 if (!(mm.formatObj->capabilities() & HardDiskFormatCapabilities_Differencing))
1864 {
1865 /* use the default format if not */
1866 AutoReadLock propsLock (mVirtualBox->systemProperties());
1867 format = mVirtualBox->systemProperties()->defaultHardDiskFormat();
1868 }
1869
1870 return format;
1871}
1872
1873// protected methods
1874////////////////////////////////////////////////////////////////////////////////
1875
1876/**
1877 * Deletes the hard disk storage unit.
1878 *
1879 * If @a aProgress is not NULL but the object it points to is @c null then a new
1880 * progress object will be created and assigned to @a *aProgress on success,
1881 * otherwise the existing progress object is used. If Progress is NULL, then no
1882 * progress object is created/used at all.
1883 *
1884 * When @a aWait is @c false, this method will create a thread to perform the
1885 * delete operation asynchronously and will return immediately. Otherwise, it
1886 * will perform the operation on the calling thread and will not return to the
1887 * caller until the operation is completed. Note that @a aProgress cannot be
1888 * NULL when @a aWait is @c false (this method will assert in this case).
1889 *
1890 * @param aProgress Where to find/store a Progress object to track operation
1891 * completion.
1892 * @param aWait @c true if this method should block instead of creating
1893 * an asynchronous thread.
1894 *
1895 * @note Locks mVirtualBox and this object for writing. Locks treeLock() for
1896 * writing.
1897 */
1898HRESULT HardDisk2::deleteStorage (ComObjPtr <Progress> *aProgress, bool aWait)
1899{
1900 AssertReturn (aProgress != NULL || aWait == true, E_FAIL);
1901
1902 /* unregisterWithVirtualBox() needs a write lock. We want to unregister
1903 * ourselves atomically after detecting that deletion is possible to make
1904 * sure that we don't do that after another thread has done
1905 * VirtualBox::findHardDisk2() but before it starts using us (provided that
1906 * it holds a mVirtualBox lock too of course). */
1907
1908 AutoWriteLock vboxLock (mVirtualBox);
1909
1910 AutoWriteLock alock (this);
1911
1912 if (!(mm.formatObj->capabilities() &
1913 (HardDiskFormatCapabilities_CreateDynamic |
1914 HardDiskFormatCapabilities_CreateFixed)))
1915 return setError (VBOX_E_NOT_SUPPORTED,
1916 tr ("Hard disk format '%ls' does not support storage deletion"),
1917 mm.format.raw());
1918
1919 /* Note that we are fine with Inaccessible state too: a) for symmetry with
1920 * create calls and b) because it doesn't really harm to try, if it is
1921 * really inaccessibke, the delete operation will fail anyway. Accepting
1922 * Inaccessible state is especially important because all registered hard
1923 * disks are initially Inaccessible upon VBoxSVC startup until
1924 * COMGETTER(State) is called. */
1925
1926 switch (m.state)
1927 {
1928 case MediaState_Created:
1929 case MediaState_Inaccessible:
1930 break;
1931 default:
1932 return setStateError();
1933 }
1934
1935 if (m.backRefs.size() != 0)
1936 return setError (VBOX_E_OBJECT_IN_USE,
1937 tr ("Hard disk '%ls' is attached to %d virtual machines"),
1938 m.locationFull.raw(), m.backRefs.size());
1939
1940 HRESULT rc = canClose();
1941 CheckComRCReturnRC (rc);
1942
1943 /* go to Deleting state before leaving the lock */
1944 m.state = MediaState_Deleting;
1945
1946 /* we need to leave this object's write lock now because of
1947 * unregisterWithVirtualBox() that locks treeLock() for writing */
1948 alock.leave();
1949
1950 /* try to remove from the list of known hard disks before performing actual
1951 * deletion (we favor the consistency of the media registry in the first
1952 * place which would have been broken if unregisterWithVirtualBox() failed
1953 * after we successfully deleted the storage) */
1954
1955 rc = unregisterWithVirtualBox();
1956
1957 alock.enter();
1958
1959 /* restore the state because we may fail below; we will set it later again*/
1960 m.state = MediaState_Created;
1961
1962 CheckComRCReturnRC (rc);
1963
1964 ComObjPtr <Progress> progress;
1965
1966 if (aProgress != NULL)
1967 {
1968 /* use the existing progress object... */
1969 progress = *aProgress;
1970
1971 /* ...but create a new one if it is null */
1972 if (progress.isNull())
1973 {
1974 progress.createObject();
1975 rc = progress->init (mVirtualBox, static_cast <IHardDisk2 *> (this),
1976 BstrFmt (tr ("Deleting hard disk storage unit '%ls'"),
1977 name().raw()),
1978 FALSE /* aCancelable */);
1979 CheckComRCReturnRC (rc);
1980 }
1981 }
1982
1983 std::auto_ptr <Task> task (new Task (this, progress, Task::Delete));
1984 AssertComRCReturnRC (task->autoCaller.rc());
1985
1986 if (aWait)
1987 {
1988 /* go to Deleting state before starting the task */
1989 m.state = MediaState_Deleting;
1990
1991 rc = task->runNow();
1992 }
1993 else
1994 {
1995 rc = task->startThread();
1996 CheckComRCReturnRC (rc);
1997
1998 /* go to Deleting state before leaving the lock */
1999 m.state = MediaState_Deleting;
2000 }
2001
2002 /* task is now owned (or already deleted) by taskThread() so release it */
2003 task.release();
2004
2005 if (aProgress != NULL)
2006 {
2007 /* return progress to the caller */
2008 *aProgress = progress;
2009 }
2010
2011 return rc;
2012}
2013
2014/**
2015 * Creates a new differencing storage unit using the given target hard disk's
2016 * format and the location. Note that @c aTarget must be NotCreated.
2017 *
2018 * As opposed to the CreateDiffStorage() method, this method doesn't try to lock
2019 * this hard disk for reading assuming that the caller has already done so. This
2020 * is used when taking an online snaopshot (where all original hard disks are
2021 * locked for writing and must remain such). Note however that if @a aWait is
2022 * @c false and this method returns a success then the thread started by
2023 * this method will unlock the hard disk (unless it is in
2024 * MediaState_LockedWrite state) so make sure the hard disk is either in
2025 * MediaState_LockedWrite or call #LockRead() before calling this method! If @a
2026 * aWait is @c true then this method neither locks nor unlocks the hard disk, so
2027 * make sure you do it yourself as needed.
2028 *
2029 * If @a aProgress is not NULL but the object it points to is @c null then a new
2030 * progress object will be created and assigned to @a *aProgress on success,
2031 * otherwise the existing progress object is used. If @a aProgress is NULL, then no
2032 * progress object is created/used at all.
2033 *
2034 * When @a aWait is @c false, this method will create a thread to perform the
2035 * create operation asynchronously and will return immediately. Otherwise, it
2036 * will perform the operation on the calling thread and will not return to the
2037 * caller until the operation is completed. Note that @a aProgress cannot be
2038 * NULL when @a aWait is @c false (this method will assert in this case).
2039 *
2040 * @param aTarget Target hard disk.
2041 * @param aProgress Where to find/store a Progress object to track operation
2042 * completion.
2043 * @param aWait @c true if this method should block instead of creating
2044 * an asynchronous thread.
2045 *
2046 * @note Locks this object and @a aTarget for writing.
2047 */
2048HRESULT HardDisk2::createDiffStorage (ComObjPtr <HardDisk2> &aTarget,
2049 ComObjPtr <Progress> *aProgress,
2050 bool aWait)
2051{
2052 AssertReturn (!aTarget.isNull(), E_FAIL);
2053 AssertReturn (aProgress != NULL || aWait == true, E_FAIL);
2054
2055 AutoCaller autoCaller (this);
2056 CheckComRCReturnRC (autoCaller.rc());
2057
2058 AutoCaller targetCaller (aTarget);
2059 CheckComRCReturnRC (targetCaller.rc());
2060
2061 AutoMultiWriteLock2 alock (this, aTarget);
2062
2063 AssertReturn (mm.type != HardDiskType_Writethrough, E_FAIL);
2064
2065 /* Note: MediaState_LockedWrite is ok when taking an online snapshot */
2066 AssertReturn (m.state == MediaState_LockedRead ||
2067 m.state == MediaState_LockedWrite, E_FAIL);
2068
2069 if (aTarget->m.state != MediaState_NotCreated)
2070 return aTarget->setStateError();
2071
2072 HRESULT rc = S_OK;
2073
2074 /* check that the hard disk is not attached to any VM in the current state*/
2075 for (BackRefList::const_iterator it = m.backRefs.begin();
2076 it != m.backRefs.end(); ++ it)
2077 {
2078 if (it->inCurState)
2079 {
2080 /* Note: when a VM snapshot is being taken, all normal hard disks
2081 * attached to the VM in the current state will be, as an exception,
2082 * also associated with the snapshot which is about to create (see
2083 * SnapshotMachine::init()) before deassociating them from the
2084 * current state (which takes place only on success in
2085 * Machine::fixupHardDisks2()), so that the size of snapshotIds
2086 * will be 1 in this case. The given condition is used to filter out
2087 * this legal situatinon and do not report an error. */
2088
2089 if (it->snapshotIds.size() == 0)
2090 {
2091 return setError (VBOX_E_INVALID_OBJECT_STATE,
2092 tr ("Hard disk '%ls' is attached to a virtual machine "
2093 "with UUID {%RTuuid}. No differencing hard disks "
2094 "based on it may be created until it is detached"),
2095 m.location.raw(), it->machineId.raw());
2096 }
2097
2098 Assert (it->snapshotIds.size() == 1);
2099 }
2100 }
2101
2102 ComObjPtr <Progress> progress;
2103
2104 if (aProgress != NULL)
2105 {
2106 /* use the existing progress object... */
2107 progress = *aProgress;
2108
2109 /* ...but create a new one if it is null */
2110 if (progress.isNull())
2111 {
2112 progress.createObject();
2113 rc = progress->init (mVirtualBox, static_cast <IHardDisk2 *> (this),
2114 BstrFmt (tr ("Creating differencing hard disk storage unit '%ls'"),
2115 aTarget->name().raw()),
2116 FALSE /* aCancelable */);
2117 CheckComRCReturnRC (rc);
2118 }
2119 }
2120
2121 /* setup task object and thread to carry out the operation
2122 * asynchronously */
2123
2124 std::auto_ptr <Task> task (new Task (this, progress, Task::CreateDiff));
2125 AssertComRCReturnRC (task->autoCaller.rc());
2126
2127 task->setData (aTarget);
2128
2129 /* register a task (it will deregister itself when done) */
2130 ++ mm.numCreateDiffTasks;
2131 Assert (mm.numCreateDiffTasks != 0); /* overflow? */
2132
2133 if (aWait)
2134 {
2135 /* go to Creating state before starting the task */
2136 aTarget->m.state = MediaState_Creating;
2137
2138 rc = task->runNow();
2139 }
2140 else
2141 {
2142 rc = task->startThread();
2143 CheckComRCReturnRC (rc);
2144
2145 /* go to Creating state before leaving the lock */
2146 aTarget->m.state = MediaState_Creating;
2147 }
2148
2149 /* task is now owned (or already deleted) by taskThread() so release it */
2150 task.release();
2151
2152 if (aProgress != NULL)
2153 {
2154 /* return progress to the caller */
2155 *aProgress = progress;
2156 }
2157
2158 return rc;
2159}
2160
2161/**
2162 * Prepares this (source) hard disk, target hard disk and all intermediate hard
2163 * disks for the merge operation.
2164 *
2165 * This method is to be called prior to calling the #mergeTo() to perform
2166 * necessary consistency checks and place involved hard disks to appropriate
2167 * states. If #mergeTo() is not called or fails, the state modifications
2168 * performed by this method must be undone by #cancelMergeTo().
2169 *
2170 * Note that when @a aIgnoreAttachments is @c true then it's the caller's
2171 * responsibility to detach the source and all intermediate hard disks before
2172 * calling #mergeTo() (which will fail otherwise).
2173 *
2174 * See #mergeTo() for more information about merging.
2175 *
2176 * @param aTarget Target hard disk.
2177 * @param aChain Where to store the created merge chain.
2178 * @param aIgnoreAttachments Don't check if the source or any intermediate
2179 * hard disk is attached to any VM.
2180 *
2181 * @note Locks treeLock() for reading. Locks this object, aTarget and all
2182 * intermediate hard disks for writing.
2183 */
2184HRESULT HardDisk2::prepareMergeTo (HardDisk2 *aTarget,
2185 MergeChain * &aChain,
2186 bool aIgnoreAttachments /*= false*/)
2187{
2188 AssertReturn (aTarget != NULL, E_FAIL);
2189
2190 AutoCaller autoCaller (this);
2191 AssertComRCReturnRC (autoCaller.rc());
2192
2193 AutoCaller targetCaller (aTarget);
2194 AssertComRCReturnRC (targetCaller.rc());
2195
2196 aChain = NULL;
2197
2198 /* we walk the tree */
2199 AutoReadLock treeLock (this->treeLock());
2200
2201 HRESULT rc = S_OK;
2202
2203 /* detect the merge direction */
2204 bool forward;
2205 {
2206 HardDisk2 *parent = mParent;
2207 while (parent != NULL && parent != aTarget)
2208 parent = parent->mParent;
2209 if (parent == aTarget)
2210 forward = false;
2211 else
2212 {
2213 parent = aTarget->mParent;
2214 while (parent != NULL && parent != this)
2215 parent = parent->mParent;
2216 if (parent == this)
2217 forward = true;
2218 else
2219 {
2220 Bstr tgtLoc;
2221 {
2222 AutoReadLock alock (this);
2223 tgtLoc = aTarget->locationFull();
2224 }
2225
2226 AutoReadLock alock (this);
2227 return setError (E_FAIL,
2228 tr ("Hard disks '%ls' and '%ls' are unrelated"),
2229 m.locationFull.raw(), tgtLoc.raw());
2230 }
2231 }
2232 }
2233
2234 /* build the chain (will do necessary checks and state changes) */
2235 std::auto_ptr <MergeChain> chain (new MergeChain (forward,
2236 aIgnoreAttachments));
2237 {
2238 HardDisk2 *last = forward ? aTarget : this;
2239 HardDisk2 *first = forward ? this : aTarget;
2240
2241 for (;;)
2242 {
2243 if (last == aTarget)
2244 rc = chain->addTarget (last);
2245 else if (last == this)
2246 rc = chain->addSource (last);
2247 else
2248 rc = chain->addIntermediate (last);
2249 CheckComRCReturnRC (rc);
2250
2251 if (last == first)
2252 break;
2253
2254 last = last->mParent;
2255 }
2256 }
2257
2258 aChain = chain.release();
2259
2260 return S_OK;
2261}
2262
2263/**
2264 * Merges this hard disk to the specified hard disk which must be either its
2265 * direct ancestor or descendant.
2266 *
2267 * Given this hard disk is SOURCE and the specified hard disk is TARGET, we will
2268 * get two varians of the merge operation:
2269 *
2270 * forward merge
2271 * ------------------------->
2272 * [Extra] <- SOURCE <- Intermediate <- TARGET
2273 * Any Del Del LockWr
2274 *
2275 *
2276 * backward merge
2277 * <-------------------------
2278 * TARGET <- Intermediate <- SOURCE <- [Extra]
2279 * LockWr Del Del LockWr
2280 *
2281 * Each scheme shows the involved hard disks on the hard disk chain where
2282 * SOURCE and TARGET belong. Under each hard disk there is a state value which
2283 * the hard disk must have at a time of the mergeTo() call.
2284 *
2285 * The hard disks in the square braces may be absent (e.g. when the forward
2286 * operation takes place and SOURCE is the base hard disk, or when the backward
2287 * merge operation takes place and TARGET is the last child in the chain) but if
2288 * they present they are involved too as shown.
2289 *
2290 * Nor the source hard disk neither intermediate hard disks may be attached to
2291 * any VM directly or in the snapshot, otherwise this method will assert.
2292 *
2293 * The #prepareMergeTo() method must be called prior to this method to place all
2294 * involved to necessary states and perform other consistency checks.
2295 *
2296 * If @a aWait is @c true then this method will perform the operation on the
2297 * calling thread and will not return to the caller until the operation is
2298 * completed. When this method succeeds, all intermediate hard disk objects in
2299 * the chain will be uninitialized, the state of the target hard disk (and all
2300 * involved extra hard disks) will be restored and @a aChain will be deleted.
2301 * Note that this (source) hard disk is not uninitialized because of possible
2302 * AutoCaller instances held by the caller of this method on the current thread.
2303 * It's therefore the responsibility of the caller to call HardDisk2::uninit()
2304 * after releasing all callers in this case!
2305 *
2306 * If @a aWait is @c false then this method will crea,te a thread to perform the
2307 * create operation asynchronously and will return immediately. If the operation
2308 * succeeds, the thread will uninitialize the source hard disk object and all
2309 * intermediate hard disk objects in the chain, reset the state of the target
2310 * hard disk (and all involved extra hard disks) and delete @a aChain. If the
2311 * operation fails, the thread will only reset the states of all involved hard
2312 * disks and delete @a aChain.
2313 *
2314 * When this method fails (regardless of the @a aWait mode), it is a caller's
2315 * responsiblity to undo state changes and delete @a aChain using
2316 * #cancelMergeTo().
2317 *
2318 * If @a aProgress is not NULL but the object it points to is @c null then a new
2319 * progress object will be created and assigned to @a *aProgress on success,
2320 * otherwise the existing progress object is used. If Progress is NULL, then no
2321 * progress object is created/used at all. Note that @a aProgress cannot be
2322 * NULL when @a aWait is @c false (this method will assert in this case).
2323 *
2324 * @param aChain Merge chain created by #prepareMergeTo().
2325 * @param aProgress Where to find/store a Progress object to track operation
2326 * completion.
2327 * @param aWait @c true if this method should block instead of creating
2328 * an asynchronous thread.
2329 *
2330 * @note Locks the branch lock for writing. Locks the hard disks from the chain
2331 * for writing.
2332 */
2333HRESULT HardDisk2::mergeTo (MergeChain *aChain,
2334 ComObjPtr <Progress> *aProgress,
2335 bool aWait)
2336{
2337 AssertReturn (aChain != NULL, E_FAIL);
2338 AssertReturn (aProgress != NULL || aWait == true, E_FAIL);
2339
2340 AutoCaller autoCaller (this);
2341 CheckComRCReturnRC (autoCaller.rc());
2342
2343 HRESULT rc = S_OK;
2344
2345 ComObjPtr <Progress> progress;
2346
2347 if (aProgress != NULL)
2348 {
2349 /* use the existing progress object... */
2350 progress = *aProgress;
2351
2352 /* ...but create a new one if it is null */
2353 if (progress.isNull())
2354 {
2355 AutoReadLock alock (this);
2356
2357 progress.createObject();
2358 rc = progress->init (mVirtualBox, static_cast <IHardDisk2 *> (this),
2359 BstrFmt (tr ("Merging hard disk '%ls' to '%ls'"),
2360 name().raw(), aChain->target()->name().raw()),
2361 FALSE /* aCancelable */);
2362 CheckComRCReturnRC (rc);
2363 }
2364 }
2365
2366 /* setup task object and thread to carry out the operation
2367 * asynchronously */
2368
2369 std::auto_ptr <Task> task (new Task (this, progress, Task::Merge));
2370 AssertComRCReturnRC (task->autoCaller.rc());
2371
2372 task->setData (aChain);
2373
2374 /* Note: task owns aChain (will delete it when not needed) in all cases
2375 * except when @a aWait is @c true and runNow() fails -- in this case
2376 * aChain will be left away because cancelMergeTo() will be applied by the
2377 * caller on it as it is required in the documentation above */
2378
2379 if (aWait)
2380 {
2381 rc = task->runNow();
2382 }
2383 else
2384 {
2385 rc = task->startThread();
2386 CheckComRCReturnRC (rc);
2387 }
2388
2389 /* task is now owned (or already deleted) by taskThread() so release it */
2390 task.release();
2391
2392 if (aProgress != NULL)
2393 {
2394 /* return progress to the caller */
2395 *aProgress = progress;
2396 }
2397
2398 return rc;
2399}
2400
2401/**
2402 * Undoes what #prepareMergeTo() did. Must be called if #mergeTo() is not called
2403 * or fails. Frees memory occupied by @a aChain.
2404 *
2405 * @param aChain Merge chain created by #prepareMergeTo().
2406 *
2407 * @note Locks the hard disks from the chain for writing.
2408 */
2409void HardDisk2::cancelMergeTo (MergeChain *aChain)
2410{
2411 AutoCaller autoCaller (this);
2412 AssertComRCReturnVoid (autoCaller.rc());
2413
2414 AssertReturnVoid (aChain != NULL);
2415
2416 /* the destructor will do the thing */
2417 delete aChain;
2418}
2419
2420// private methods
2421////////////////////////////////////////////////////////////////////////////////
2422
2423/**
2424 * Sets the value of m.location and calculates the value of m.locationFull.
2425 *
2426 * Reimplements MediumBase::setLocation() to specially treat non-FS-path
2427 * locations and to prepend the default hard disk folder if the given location
2428 * string does not contain any path information at all.
2429 *
2430 * Also, if the specified location is a file path that ends with '/' then the
2431 * file name part will be generated by this method automatically in the format
2432 * '{<uuid>}.<ext>' where <uuid> is a fresh UUID that this method will generate
2433 * and assign to this medium, and <ext> is the default extension for this
2434 * medium's storage format. Note that this procedure requires the media state to
2435 * be NotCreated and will return a faiulre otherwise.
2436 *
2437 * @param aLocation Location of the storage unit. If the locaiton is a FS-path,
2438 * then it can be relative to the VirtualBox home directory.
2439 *
2440 * @note Must be called from under this object's write lock.
2441 */
2442HRESULT HardDisk2::setLocation (CBSTR aLocation)
2443{
2444 /// @todo so far, we assert but later it makes sense to support null
2445 /// locations for hard disks that are not yet created fail to create a
2446 /// storage unit instead
2447 CheckComArgStrNotEmptyOrNull (aLocation);
2448
2449 AutoCaller autoCaller (this);
2450 AssertComRCReturnRC (autoCaller.rc());
2451
2452 /* formatObj may be null only when initializing from an existing path and
2453 * no format is known yet */
2454 AssertReturn ((!mm.format.isNull() && !mm.formatObj.isNull()) ||
2455 (autoCaller.state() == InInit &&
2456 m.state != MediaState_NotCreated && m.id.isEmpty() &&
2457 mm.format.isNull() && mm.formatObj.isNull()),
2458 E_FAIL);
2459
2460 /* are we dealing with a new hard disk constructed using the existing
2461 * location? */
2462 bool isImport = mm.format.isNull();
2463
2464 if (isImport ||
2465 (mm.formatObj->capabilities() & HardDiskFormatCapabilities_File))
2466 {
2467 Guid id;
2468
2469 Utf8Str location (aLocation);
2470
2471 if (m.state == MediaState_NotCreated)
2472 {
2473 /* must be a file (formatObj must be already known) */
2474 Assert (mm.formatObj->capabilities() & HardDiskFormatCapabilities_File);
2475
2476 if (RTPathFilename (location) == NULL)
2477 {
2478 /* no file name is given (either an empty string or ends with a
2479 * slash), generate a new UUID + file name if the state allows
2480 * this */
2481
2482 ComAssertMsgRet (!mm.formatObj->fileExtensions().empty(),
2483 ("Must be at least one extension if it is "
2484 "HardDiskFormatCapabilities_File\n"),
2485 E_FAIL);
2486
2487 Bstr ext = mm.formatObj->fileExtensions().front();
2488 ComAssertMsgRet (!ext.isEmpty(),
2489 ("Default extension must not be empty\n"),
2490 E_FAIL);
2491
2492 id.create();
2493
2494 location = Utf8StrFmt ("%s{%RTuuid}.%ls",
2495 location.raw(), id.raw(), ext.raw());
2496 }
2497 }
2498
2499 /* append the default folder if no path is given */
2500 if (!RTPathHavePath (location))
2501 {
2502 AutoReadLock propsLock (mVirtualBox->systemProperties());
2503 location = Utf8StrFmt ("%ls%c%s",
2504 mVirtualBox->systemProperties()->defaultHardDiskFolder().raw(),
2505 RTPATH_DELIMITER,
2506 location.raw());
2507 }
2508
2509 /* get the full file name */
2510 Utf8Str locationFull;
2511 int vrc = mVirtualBox->calculateFullPath (location, locationFull);
2512 if (RT_FAILURE (vrc))
2513 return setError (VBOX_E_FILE_ERROR,
2514 tr ("Invalid hard disk storage file location '%s' (%Rrc)"),
2515 location.raw(), vrc);
2516
2517 /* detect the backend from the storage unit if importing */
2518 if (isImport)
2519 {
2520 char *backendName = NULL;
2521
2522 /* is it a file? */
2523 {
2524 RTFILE file;
2525 vrc = RTFileOpen (&file, locationFull, RTFILE_O_READ);
2526 if (RT_SUCCESS (vrc))
2527 RTFileClose (file);
2528 }
2529 if (RT_SUCCESS (vrc))
2530 {
2531 vrc = VDGetFormat (locationFull, &backendName);
2532 }
2533 else if (vrc != VERR_FILE_NOT_FOUND && vrc != VERR_PATH_NOT_FOUND)
2534 {
2535 /* assume it's not a file, restore the original location */
2536 location = locationFull = aLocation;
2537 vrc = VDGetFormat (locationFull, &backendName);
2538 }
2539
2540 if (RT_FAILURE (vrc))
2541 return setError (VBOX_E_IPRT_ERROR,
2542 tr ("Could not get the storage format of the hard disk "
2543 "'%s' (%Rrc)"), locationFull.raw(), vrc);
2544
2545 ComAssertRet (backendName != NULL && *backendName != '\0', E_FAIL);
2546
2547 HRESULT rc = setFormat (Bstr (backendName));
2548 RTStrFree (backendName);
2549
2550 /* setFormat() must not fail since we've just used the backend so
2551 * the format object must be there */
2552 AssertComRCReturnRC (rc);
2553 }
2554
2555 /* is it still a file? */
2556 if (mm.formatObj->capabilities() & HardDiskFormatCapabilities_File)
2557 {
2558 m.location = location;
2559 m.locationFull = locationFull;
2560
2561 if (m.state == MediaState_NotCreated)
2562 {
2563 /* assign a new UUID (this UUID will be used when calling
2564 * VDCreateBase/VDCreateDiff as a wanted UUID). Note that we
2565 * also do that if we didn't generate it to make sure it is
2566 * either generated by us or reset to null */
2567 unconst (m.id) = id;
2568 }
2569 }
2570 else
2571 {
2572 m.location = locationFull;
2573 m.locationFull = locationFull;
2574 }
2575 }
2576 else
2577 {
2578 m.location = aLocation;
2579 m.locationFull = aLocation;
2580 }
2581
2582 return S_OK;
2583}
2584
2585/**
2586 * Checks that the format ID is valid and sets it on success.
2587 *
2588 * Note that this method will caller-reference the format object on success!
2589 * This reference must be released somewhere to let the HardDiskFormat object be
2590 * uninitialized.
2591 *
2592 * @note Must be called from under this object's write lock.
2593 */
2594HRESULT HardDisk2::setFormat (CBSTR aFormat)
2595{
2596 /* get the format object first */
2597 {
2598 AutoReadLock propsLock (mVirtualBox->systemProperties());
2599
2600 unconst (mm.formatObj)
2601 = mVirtualBox->systemProperties()->hardDiskFormat (aFormat);
2602 if (mm.formatObj.isNull())
2603 return setError (E_INVALIDARG,
2604 tr ("Invalid hard disk storage format '%ls'"), aFormat);
2605
2606 /* reference the format permanently to prevent its unexpected
2607 * uninitialization */
2608 HRESULT rc = mm.formatObj->addCaller();
2609 AssertComRCReturnRC (rc);
2610
2611 /* get properties (preinsert them as keys in the map). Note that the
2612 * map doesn't grow over the object life time since the set of
2613 * properties is meant to be constant. */
2614
2615 Assert (mm.properties.empty());
2616
2617 for (HardDiskFormat::PropertyList::const_iterator it =
2618 mm.formatObj->properties().begin();
2619 it != mm.formatObj->properties().end();
2620 ++ it)
2621 {
2622 mm.properties.insert (std::make_pair (it->name, Bstr::Null));
2623 }
2624 }
2625
2626 unconst (mm.format) = aFormat;
2627
2628 return S_OK;
2629}
2630
2631/**
2632 * Queries information from the image file.
2633 *
2634 * As a result of this call, the accessibility state and data members such as
2635 * size and description will be updated with the current information.
2636 *
2637 * Reimplements MediumBase::queryInfo() to query hard disk information using the
2638 * VD backend interface.
2639 *
2640 * @note This method may block during a system I/O call that checks storage
2641 * accessibility.
2642 *
2643 * @note Locks treeLock() for reading and writing (for new diff media checked
2644 * for the first time). Locks mParent for reading. Locks this object for
2645 * writing.
2646 */
2647HRESULT HardDisk2::queryInfo()
2648{
2649 AutoWriteLock alock (this);
2650
2651 AssertReturn (m.state == MediaState_Created ||
2652 m.state == MediaState_Inaccessible ||
2653 m.state == MediaState_LockedRead ||
2654 m.state == MediaState_LockedWrite,
2655 E_FAIL);
2656
2657 HRESULT rc = S_OK;
2658
2659 int vrc = VINF_SUCCESS;
2660
2661 /* check if a blocking queryInfo() call is in progress on some other thread,
2662 * and wait for it to finish if so instead of querying data ourselves */
2663 if (m.queryInfoSem != NIL_RTSEMEVENTMULTI)
2664 {
2665 Assert (m.state == MediaState_LockedRead);
2666
2667 ++ m.queryInfoCallers;
2668 alock.leave();
2669
2670 vrc = RTSemEventMultiWait (m.queryInfoSem, RT_INDEFINITE_WAIT);
2671
2672 alock.enter();
2673 -- m.queryInfoCallers;
2674
2675 if (m.queryInfoCallers == 0)
2676 {
2677 /* last waiting caller deletes the semaphore */
2678 RTSemEventMultiDestroy (m.queryInfoSem);
2679 m.queryInfoSem = NIL_RTSEMEVENTMULTI;
2680 }
2681
2682 AssertRC (vrc);
2683
2684 return S_OK;
2685 }
2686
2687 /* lazily create a semaphore for possible callers */
2688 vrc = RTSemEventMultiCreate (&m.queryInfoSem);
2689 ComAssertRCRet (vrc, E_FAIL);
2690
2691 bool tempStateSet = false;
2692 if (m.state != MediaState_LockedRead &&
2693 m.state != MediaState_LockedWrite)
2694 {
2695 /* Cause other methods to prevent any modifications before leaving the
2696 * lock. Note that clients will never see this temporary state change
2697 * since any COMGETTER(State) is (or will be) blocked until we finish
2698 * and restore the actual state. */
2699 m.state = MediaState_LockedRead;
2700 tempStateSet = true;
2701 }
2702
2703 /* leave the lock before a blocking operation */
2704 alock.leave();
2705
2706 bool success = false;
2707 Utf8Str lastAccessError;
2708
2709 try
2710 {
2711 Utf8Str location (m.locationFull);
2712
2713 /* are we dealing with a new hard disk constructed using the existing
2714 * location? */
2715 bool isImport = m.id.isEmpty();
2716
2717 PVBOXHDD hdd;
2718 vrc = VDCreate (mm.vdDiskIfaces, &hdd);
2719 ComAssertRCThrow (vrc, E_FAIL);
2720
2721 try
2722 {
2723 unsigned flags = VD_OPEN_FLAGS_INFO;
2724
2725 /* Note that we don't use VD_OPEN_FLAGS_READONLY when opening new
2726 * hard disks because that would prevent necessary modifications
2727 * when opening hard disks of some third-party formats for the first
2728 * time in VirtualBox (such as VMDK for which VDOpen() needs to
2729 * generate an UUID if it is missing) */
2730 if (!isImport)
2731 flags |= VD_OPEN_FLAGS_READONLY;
2732
2733 vrc = VDOpen (hdd, Utf8Str (mm.format), location, flags,
2734 mm.vdDiskIfaces);
2735 if (RT_FAILURE (vrc))
2736 {
2737 lastAccessError = Utf8StrFmt (
2738 tr ("Could not open the hard disk '%ls'%s"),
2739 m.locationFull.raw(), vdError (vrc).raw());
2740 throw S_OK;
2741 }
2742
2743 if (mm.formatObj->capabilities() & HardDiskFormatCapabilities_Uuid)
2744 {
2745 /* check the UUID */
2746 RTUUID uuid;
2747 vrc = VDGetUuid (hdd, 0, &uuid);
2748 ComAssertRCThrow (vrc, E_FAIL);
2749
2750 if (isImport)
2751 {
2752 unconst (m.id) = uuid;
2753 }
2754 else
2755 {
2756 Assert (!m.id.isEmpty());
2757
2758 if (m.id != uuid)
2759 {
2760 lastAccessError = Utf8StrFmt (
2761 tr ("UUID {%RTuuid} of the hard disk '%ls' does "
2762 "not match the value {%RTuuid} stored in the "
2763 "media registry ('%ls')"),
2764 &uuid, m.locationFull.raw(), m.id.raw(),
2765 mVirtualBox->settingsFileName().raw());
2766 throw S_OK;
2767 }
2768 }
2769 }
2770 else
2771 {
2772 /* the backend does not support storing UUIDs within the
2773 * underlying storage so use what we store in XML */
2774
2775 /* generate an UUID for an imported UUID-less hard disk */
2776 if (isImport)
2777 unconst (m.id).create();
2778 }
2779
2780 /* check the type */
2781 VDIMAGETYPE type;
2782 vrc = VDGetImageType (hdd, 0, &type);
2783 ComAssertRCThrow (vrc, E_FAIL);
2784
2785 if (type == VD_IMAGE_TYPE_DIFF)
2786 {
2787 RTUUID parentId;
2788 vrc = VDGetParentUuid (hdd, 0, &parentId);
2789 ComAssertRCThrow (vrc, E_FAIL);
2790
2791 if (isImport)
2792 {
2793 /* the parent must be known to us. Note that we freely
2794 * call locking methods of mVirtualBox and parent from the
2795 * write lock (breaking the {parent,child} lock order)
2796 * because there may be no concurrent access to the just
2797 * opened hard disk on ther threads yet (and init() will
2798 * fail if this method reporst MediaState_Inaccessible) */
2799
2800 Guid id = parentId;
2801 ComObjPtr <HardDisk2> parent;
2802 rc = mVirtualBox->findHardDisk2 (&id, NULL,
2803 false /* aSetError */,
2804 &parent);
2805 if (FAILED (rc))
2806 {
2807 lastAccessError = Utf8StrFmt (
2808 tr ("Parent hard disk with UUID {%RTuuid} of the "
2809 "hard disk '%ls' is not found in the media "
2810 "registry ('%ls')"),
2811 &parentId, m.locationFull.raw(),
2812 mVirtualBox->settingsFileName().raw());
2813 throw S_OK;
2814 }
2815
2816 /* deassociate from VirtualBox, associate with parent */
2817
2818 mVirtualBox->removeDependentChild (this);
2819
2820 /* we set mParent & children() */
2821 AutoWriteLock treeLock (this->treeLock());
2822
2823 Assert (mParent.isNull());
2824 mParent = parent;
2825 mParent->addDependentChild (this);
2826 }
2827 else
2828 {
2829 /* we access mParent */
2830 AutoReadLock treeLock (this->treeLock());
2831
2832 /* check that parent UUIDs match. Note that there's no need
2833 * for the parent's AutoCaller (our lifetime is bound to
2834 * it) */
2835
2836 if (mParent.isNull())
2837 {
2838 lastAccessError = Utf8StrFmt (
2839 tr ("Hard disk '%ls' is differencing but it is not "
2840 "associated with any parent hard disk in the "
2841 "media registry ('%ls')"),
2842 m.locationFull.raw(),
2843 mVirtualBox->settingsFileName().raw());
2844 throw S_OK;
2845 }
2846
2847 AutoReadLock parentLock (mParent);
2848 if (mParent->state() != MediaState_Inaccessible &&
2849 mParent->id() != parentId)
2850 {
2851 lastAccessError = Utf8StrFmt (
2852 tr ("Parent UUID {%RTuuid} of the hard disk '%ls' "
2853 "does not match UUID {%RTuuid} of its parent "
2854 "hard disk stored in the media registry ('%ls')"),
2855 &parentId, m.locationFull.raw(),
2856 mParent->id().raw(),
2857 mVirtualBox->settingsFileName().raw());
2858 throw S_OK;
2859 }
2860
2861 /// @todo NEWMEDIA what to do if the parent is not
2862 /// accessible while the diff is? Probably, nothing. The
2863 /// real code will detect the mismatch anyway.
2864 }
2865 }
2866
2867 m.size = VDGetFileSize (hdd, 0);
2868 mm.logicalSize = VDGetSize (hdd, 0) / _1M;
2869
2870 success = true;
2871 }
2872 catch (HRESULT aRC)
2873 {
2874 rc = aRC;
2875 }
2876
2877 VDDestroy (hdd);
2878
2879 }
2880 catch (HRESULT aRC)
2881 {
2882 rc = aRC;
2883 }
2884
2885 alock.enter();
2886
2887 if (success)
2888 m.lastAccessError.setNull();
2889 else
2890 {
2891 m.lastAccessError = lastAccessError;
2892 LogWarningFunc (("'%ls' is not accessible (error='%ls', "
2893 "rc=%Rhrc, vrc=%Rrc)\n",
2894 m.locationFull.raw(), m.lastAccessError.raw(),
2895 rc, vrc));
2896 }
2897
2898 /* inform other callers if there are any */
2899 if (m.queryInfoCallers > 0)
2900 {
2901 RTSemEventMultiSignal (m.queryInfoSem);
2902 }
2903 else
2904 {
2905 /* delete the semaphore ourselves */
2906 RTSemEventMultiDestroy (m.queryInfoSem);
2907 m.queryInfoSem = NIL_RTSEMEVENTMULTI;
2908 }
2909
2910 if (tempStateSet)
2911 {
2912 /* Set the proper state according to the result of the check */
2913 if (success)
2914 m.state = MediaState_Created;
2915 else
2916 m.state = MediaState_Inaccessible;
2917 }
2918 else
2919 {
2920 /* we're locked, use a special field to store the result */
2921 m.accessibleInLock = success;
2922 }
2923
2924 return rc;
2925}
2926
2927/**
2928 * @note Called from this object's AutoMayUninitSpan and from under mVirtualBox
2929 * write lock.
2930 *
2931 * @note Locks treeLock() for reading.
2932 */
2933HRESULT HardDisk2::canClose()
2934{
2935 /* we access children */
2936 AutoReadLock treeLock (this->treeLock());
2937
2938 if (children().size() != 0)
2939 return setError (E_FAIL,
2940 tr ("Hard disk '%ls' has %d child hard disks"),
2941 children().size());
2942
2943 return S_OK;
2944}
2945
2946/**
2947 * @note Called from within this object's AutoWriteLock.
2948 */
2949HRESULT HardDisk2::canAttach (const Guid &aMachineId,
2950 const Guid &aSnapshotId)
2951{
2952 if (mm.numCreateDiffTasks > 0)
2953 return setError (E_FAIL,
2954 tr ("One or more differencing child hard disks are "
2955 "being created for the hard disk '%ls' (%u)"),
2956 m.locationFull.raw(), mm.numCreateDiffTasks);
2957
2958 return S_OK;
2959}
2960
2961/**
2962 * @note Called from within this object's AutoMayUninitSpan (or AutoCaller) and
2963 * from under mVirtualBox write lock.
2964 *
2965 * @note Locks treeLock() for writing.
2966 */
2967HRESULT HardDisk2::unregisterWithVirtualBox()
2968{
2969 /* Note that we need to de-associate ourselves from the parent to let
2970 * unregisterHardDisk2() properly save the registry */
2971
2972 /* we modify mParent and access children */
2973 AutoWriteLock treeLock (this->treeLock());
2974
2975 const ComObjPtr <HardDisk2, ComWeakRef> parent = mParent;
2976
2977 AssertReturn (children().size() == 0, E_FAIL);
2978
2979 if (!mParent.isNull())
2980 {
2981 /* deassociate from the parent, associate with VirtualBox */
2982 mVirtualBox->addDependentChild (this);
2983 mParent->removeDependentChild (this);
2984 mParent.setNull();
2985 }
2986
2987 HRESULT rc = mVirtualBox->unregisterHardDisk2 (this);
2988
2989 if (FAILED (rc))
2990 {
2991 if (!parent.isNull())
2992 {
2993 /* re-associate with the parent as we are still relatives in the
2994 * registry */
2995 mParent = parent;
2996 mParent->addDependentChild (this);
2997 mVirtualBox->removeDependentChild (this);
2998 }
2999 }
3000
3001 return rc;
3002}
3003
3004/**
3005 * Returns the last error message collected by the vdErrorCall callback and
3006 * resets it.
3007 *
3008 * The error message is returned prepended with a dot and a space, like this:
3009 * <code>
3010 * ". <error_text> (%Rrc)"
3011 * </code>
3012 * to make it easily appendable to a more general error message. The @c %Rrc
3013 * format string is given @a aVRC as an argument.
3014 *
3015 * If there is no last error message collected by vdErrorCall or if it is a
3016 * null or empty string, then this function returns the following text:
3017 * <code>
3018 * " (%Rrc)"
3019 * </code>
3020 *
3021 * @note Doesn't do any object locking; it is assumed that the caller makes sure
3022 * the callback isn't called by more than one thread at a time.
3023 *
3024 * @param aVRC VBox error code to use when no error message is provided.
3025 */
3026Utf8Str HardDisk2::vdError (int aVRC)
3027{
3028 Utf8Str error;
3029
3030 if (mm.vdError.isEmpty())
3031 error = Utf8StrFmt (" (%Rrc)", aVRC);
3032 else
3033 error = Utf8StrFmt (".\n%s", mm.vdError.raw());
3034
3035 mm.vdError.setNull();
3036
3037 return error;
3038}
3039
3040/**
3041 * Error message callback.
3042 *
3043 * Puts the reported error message to the mm.vdError field.
3044 *
3045 * @note Doesn't do any object locking; it is assumed that the caller makes sure
3046 * the callback isn't called by more than one thread at a time.
3047 *
3048 * @param pvUser The opaque data passed on container creation.
3049 * @param rc The VBox error code.
3050 * @param RT_SRC_POS_DECL Use RT_SRC_POS.
3051 * @param pszFormat Error message format string.
3052 * @param va Error message arguments.
3053 */
3054/*static*/
3055DECLCALLBACK(void) HardDisk2::vdErrorCall (void *pvUser, int rc, RT_SRC_POS_DECL,
3056 const char *pszFormat, va_list va)
3057{
3058 HardDisk2 *that = static_cast <HardDisk2 *> (pvUser);
3059 AssertReturnVoid (that != NULL);
3060
3061 if (that->mm.vdError.isEmpty())
3062 that->mm.vdError =
3063 Utf8StrFmt ("%s (%Rrc)", Utf8StrFmtVA (pszFormat, va).raw(), rc);
3064 else
3065 that->mm.vdError =
3066 Utf8StrFmt ("%s.\n%s (%Rrc)", that->mm.vdError.raw(),
3067 Utf8StrFmtVA (pszFormat, va).raw(), rc);
3068}
3069
3070/**
3071 * PFNVMPROGRESS callback handler for Task operations.
3072 *
3073 * @param uPercent Completetion precentage (0-100).
3074 * @param pvUser Pointer to the Progress instance.
3075 */
3076/*static*/
3077DECLCALLBACK(int) HardDisk2::vdProgressCall (PVM /* pVM */, unsigned uPercent,
3078 void *pvUser)
3079{
3080 HardDisk2 *that = static_cast <HardDisk2 *> (pvUser);
3081 AssertReturn (that != NULL, VERR_GENERAL_FAILURE);
3082
3083 if (that->mm.vdProgress != NULL)
3084 {
3085 /* update the progress object, capping it at 99% as the final percent
3086 * is used for additional operations like setting the UUIDs and similar. */
3087 that->mm.vdProgress->notifyProgress (RT_MIN (uPercent, 99));
3088 }
3089
3090 return VINF_SUCCESS;
3091}
3092
3093/* static */
3094DECLCALLBACK(bool) HardDisk2::vdConfigAreKeysValid (void *pvUser,
3095 const char *pszzValid)
3096{
3097 HardDisk2 *that = static_cast <HardDisk2 *> (pvUser);
3098 AssertReturn (that != NULL, false);
3099
3100 /* we always return true since the only keys we have are those found in
3101 * VDBACKENDINFO */
3102 return true;
3103}
3104
3105/* static */
3106DECLCALLBACK(int) HardDisk2::vdConfigQuerySize (void *pvUser, const char *pszName,
3107 size_t *pcbValue)
3108{
3109 AssertReturn (VALID_PTR (pcbValue), VERR_INVALID_POINTER);
3110
3111 HardDisk2 *that = static_cast <HardDisk2 *> (pvUser);
3112 AssertReturn (that != NULL, VERR_GENERAL_FAILURE);
3113
3114 Data::PropertyMap::const_iterator it =
3115 that->mm.properties.find (Bstr (pszName));
3116 if (it == that->mm.properties.end())
3117 return VERR_CFGM_VALUE_NOT_FOUND;
3118
3119 /* we interpret null values as "no value" in HardDisk2 */
3120 if (it->second.isNull())
3121 return VERR_CFGM_VALUE_NOT_FOUND;
3122
3123 *pcbValue = it->second.length() + 1 /* include terminator */;
3124
3125 return VINF_SUCCESS;
3126}
3127
3128/* static */
3129DECLCALLBACK(int) HardDisk2::vdConfigQuery (void *pvUser, const char *pszName,
3130 char *pszValue, size_t cchValue)
3131{
3132 AssertReturn (VALID_PTR (pszValue), VERR_INVALID_POINTER);
3133
3134 HardDisk2 *that = static_cast <HardDisk2 *> (pvUser);
3135 AssertReturn (that != NULL, VERR_GENERAL_FAILURE);
3136
3137 Data::PropertyMap::const_iterator it =
3138 that->mm.properties.find (Bstr (pszName));
3139 if (it == that->mm.properties.end())
3140 return VERR_CFGM_VALUE_NOT_FOUND;
3141
3142 Utf8Str value = it->second;
3143 if (value.length() >= cchValue)
3144 return VERR_CFGM_NOT_ENOUGH_SPACE;
3145
3146 /* we interpret null values as "no value" in HardDisk2 */
3147 if (it->second.isNull())
3148 return VERR_CFGM_VALUE_NOT_FOUND;
3149
3150 memcpy (pszValue, value, value.length() + 1);
3151
3152 return VINF_SUCCESS;
3153}
3154
3155/**
3156 * Thread function for time-consuming tasks.
3157 *
3158 * The Task structure passed to @a pvUser must be allocated using new and will
3159 * be freed by this method before it returns.
3160 *
3161 * @param pvUser Pointer to the Task instance.
3162 */
3163/* static */
3164DECLCALLBACK(int) HardDisk2::taskThread (RTTHREAD thread, void *pvUser)
3165{
3166 std::auto_ptr <Task> task (static_cast <Task *> (pvUser));
3167 AssertReturn (task.get(), VERR_GENERAL_FAILURE);
3168
3169 bool isAsync = thread != NIL_RTTHREAD;
3170
3171 HardDisk2 *that = task->that;
3172
3173 /// @todo ugly hack, fix ComAssert... later
3174 #define setError that->setError
3175
3176 /* Note: no need in AutoCaller because Task does that */
3177
3178 LogFlowFuncEnter();
3179 LogFlowFunc (("{%p}: operation=%d\n", that, task->operation));
3180
3181 HRESULT rc = S_OK;
3182
3183 switch (task->operation)
3184 {
3185 ////////////////////////////////////////////////////////////////////////
3186
3187 case Task::CreateDynamic:
3188 case Task::CreateFixed:
3189 {
3190 /* The lock is also used as a signal from the task initiator (which
3191 * releases it only after RTThreadCreate()) that we can start the job */
3192 AutoWriteLock thatLock (that);
3193
3194 /* these parameters we need after creation */
3195 uint64_t size = 0, logicalSize = 0;
3196
3197 /* the object may request a specific UUID (through a special
3198 * form of the setLocation() argumet) */
3199 Guid id = that->m.id;
3200
3201 try
3202 {
3203 PVBOXHDD hdd;
3204 int vrc = VDCreate (that->mm.vdDiskIfaces, &hdd);
3205 ComAssertRCThrow (vrc, E_FAIL);
3206
3207 Utf8Str format (that->mm.format);
3208 Utf8Str location (that->m.locationFull);
3209 uint64_t capabilities = that->mm.formatObj->capabilities();
3210
3211 /* unlock before the potentially lengthy operation */
3212 Assert (that->m.state == MediaState_Creating);
3213 thatLock.leave();
3214
3215 try
3216 {
3217 /* ensure the directory exists */
3218 rc = VirtualBox::ensureFilePathExists (location);
3219 CheckComRCThrowRC (rc);
3220
3221 PDMMEDIAGEOMETRY geo = { 0 }; /* auto-detect */
3222
3223 /* needed for vdProgressCallback */
3224 that->mm.vdProgress = task->progress;
3225
3226 vrc = VDCreateBase (hdd, format, location,
3227 task->operation == Task::CreateDynamic ?
3228 VD_IMAGE_TYPE_NORMAL :
3229 VD_IMAGE_TYPE_FIXED,
3230 task->d.size * _1M,
3231 VD_IMAGE_FLAGS_NONE,
3232 NULL, &geo, &geo,
3233 id.isEmpty() ? NULL : id.raw(),
3234 VD_OPEN_FLAGS_NORMAL,
3235 NULL, that->mm.vdDiskIfaces);
3236
3237 if (RT_FAILURE (vrc))
3238 {
3239 throw setError (E_FAIL,
3240 tr ("Could not create the hard disk storage "
3241 "unit '%s'%s"),
3242 location.raw(), that->vdError (vrc).raw());
3243 }
3244
3245 if (capabilities & HardDiskFormatCapabilities_Uuid)
3246 {
3247 RTUUID uuid;
3248 vrc = VDGetUuid (hdd, 0, &uuid);
3249 ComAssertRCThrow (vrc, E_FAIL);
3250
3251 if (!id.isEmpty())
3252 Assert (id == uuid);
3253 else
3254 id = uuid;
3255 }
3256 else
3257 {
3258 /* we have to generate an UUID ourselves */
3259 id.create();
3260 }
3261
3262 size = VDGetFileSize (hdd, 0);
3263 logicalSize = VDGetSize (hdd, 0) / _1M;
3264 }
3265 catch (HRESULT aRC) { rc = aRC; }
3266
3267 VDDestroy (hdd);
3268 }
3269 catch (HRESULT aRC) { rc = aRC; }
3270
3271 if (SUCCEEDED (rc))
3272 {
3273 /* mVirtualBox->registerHardDisk2() needs a write lock */
3274 AutoWriteLock vboxLock (that->mVirtualBox);
3275 thatLock.enter();
3276
3277 unconst (that->m.id) = id;
3278
3279 that->m.size = size;
3280 that->mm.logicalSize = logicalSize;
3281
3282 /* register with mVirtualBox as the last step and move to
3283 * Created state only on success (leaving an orphan file is
3284 * better than breaking media registry consistency) */
3285 rc = that->mVirtualBox->registerHardDisk2 (that);
3286
3287 if (SUCCEEDED (rc))
3288 that->m.state = MediaState_Created;
3289 }
3290
3291 if (FAILED (rc))
3292 {
3293 thatLock.maybeEnter();
3294
3295 /* back to NotCreated on failiure */
3296 that->m.state = MediaState_NotCreated;
3297 }
3298
3299 break;
3300 }
3301
3302 ////////////////////////////////////////////////////////////////////////
3303
3304 case Task::CreateDiff:
3305 {
3306 ComObjPtr <HardDisk2> &target = task->d.target;
3307
3308 /* Lock both in {parent,child} order. The lock is also used as a
3309 * signal from the task initiator (which releases it only after
3310 * RTThreadCreate()) that we can start the job*/
3311 AutoMultiWriteLock2 thatLock (that, target);
3312
3313 uint64_t size = 0, logicalSize = 0;
3314
3315 try
3316 {
3317 PVBOXHDD hdd;
3318 int vrc = VDCreate (that->mm.vdDiskIfaces, &hdd);
3319 ComAssertRCThrow (vrc, E_FAIL);
3320
3321 Utf8Str format (that->mm.format);
3322 Utf8Str location (that->m.locationFull);
3323
3324 Utf8Str targetFormat (target->mm.format);
3325 Utf8Str targetLocation (target->m.locationFull);
3326 Guid targetId = target->m.id;
3327
3328 /* UUID must have been set by setLocation() */
3329 Assert (!targetId.isEmpty());
3330
3331 Assert (target->m.state == MediaState_Creating);
3332
3333 /* Note: MediaState_LockedWrite is ok when taking an online
3334 * snapshot */
3335 Assert (that->m.state == MediaState_LockedRead ||
3336 that->m.state == MediaState_LockedWrite);
3337
3338 /* unlock before the potentially lengthy operation */
3339 thatLock.leave();
3340
3341 try
3342 {
3343 vrc = VDOpen (hdd, format, location,
3344 VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_INFO,
3345 NULL);
3346 if (RT_FAILURE (vrc))
3347 {
3348 throw setError (E_FAIL,
3349 tr ("Could not open the hard disk storage "
3350 "unit '%s'%s"),
3351 location.raw(), that->vdError (vrc).raw());
3352 }
3353
3354 /* ensure the target directory exists */
3355 rc = VirtualBox::ensureFilePathExists (targetLocation);
3356 CheckComRCThrowRC (rc);
3357
3358 /* needed for vdProgressCallback */
3359 that->mm.vdProgress = task->progress;
3360
3361 vrc = VDCreateDiff (hdd, targetFormat, targetLocation,
3362 VD_IMAGE_FLAGS_NONE,
3363 NULL, targetId.raw(),
3364 VD_OPEN_FLAGS_NORMAL,
3365 NULL, that->mm.vdDiskIfaces);
3366
3367 that->mm.vdProgress = NULL;
3368
3369 if (RT_FAILURE (vrc))
3370 {
3371 throw setError (E_FAIL,
3372 tr ("Could not create the differencing hard disk "
3373 "storage unit '%s'%s"),
3374 targetLocation.raw(), that->vdError (vrc).raw());
3375 }
3376
3377 size = VDGetFileSize (hdd, 0);
3378 logicalSize = VDGetSize (hdd, 0) / _1M;
3379 }
3380 catch (HRESULT aRC) { rc = aRC; }
3381
3382 VDDestroy (hdd);
3383 }
3384 catch (HRESULT aRC) { rc = aRC; }
3385
3386 if (SUCCEEDED (rc))
3387 {
3388 /* we set mParent & children() (note that thatLock is released
3389 * here), but lock VirtualBox first to follow the rule */
3390 AutoMultiWriteLock2 alock (that->mVirtualBox->lockHandle(),
3391 that->treeLock());
3392
3393 Assert (target->mParent.isNull());
3394
3395 /* associate the child with the parent and deassociate from
3396 * VirtualBox */
3397 target->mParent = that;
3398 that->addDependentChild (target);
3399 target->mVirtualBox->removeDependentChild (target);
3400
3401 /* register with mVirtualBox as the last step and move to
3402 * Created state only on success (leaving an orphan file is
3403 * better than breaking media registry consistency) */
3404 rc = that->mVirtualBox->registerHardDisk2 (target);
3405
3406 if (FAILED (rc))
3407 {
3408 /* break the parent association on failure to register */
3409 target->mVirtualBox->addDependentChild (target);
3410 that->removeDependentChild (target);
3411 target->mParent.setNull();
3412 }
3413 }
3414
3415 thatLock.maybeEnter();
3416
3417 if (SUCCEEDED (rc))
3418 {
3419 target->m.state = MediaState_Created;
3420
3421 target->m.size = size;
3422 target->mm.logicalSize = logicalSize;
3423 }
3424 else
3425 {
3426 /* back to NotCreated on failiure */
3427 target->m.state = MediaState_NotCreated;
3428 }
3429
3430 if (isAsync)
3431 {
3432 /* unlock ourselves when done (unless in MediaState_LockedWrite
3433 * state because of taking the online snapshot*/
3434 if (that->m.state != MediaState_LockedWrite)
3435 {
3436 HRESULT rc2 = that->UnlockRead (NULL);
3437 AssertComRC (rc2);
3438 }
3439 }
3440
3441 /* deregister the task registered in createDiffStorage() */
3442 Assert (that->mm.numCreateDiffTasks != 0);
3443 -- that->mm.numCreateDiffTasks;
3444
3445 /* Note that in sync mode, it's the caller's responsibility to
3446 * unlock the hard disk */
3447
3448 break;
3449 }
3450
3451 ////////////////////////////////////////////////////////////////////////
3452
3453 case Task::Merge:
3454 {
3455 /* The lock is also used as a signal from the task initiator (which
3456 * releases it only after RTThreadCreate()) that we can start the
3457 * job. We don't actually need the lock for anything else since the
3458 * object is protected by MediaState_Deleting and we don't modify
3459 * its sensitive fields below */
3460 {
3461 AutoWriteLock thatLock (that);
3462 }
3463
3464 MergeChain *chain = task->d.chain.get();
3465
3466#if 1
3467 LogFlow (("*** MERGE forward = %RTbool\n", chain->isForward()));
3468#endif
3469
3470 try
3471 {
3472 PVBOXHDD hdd;
3473 int vrc = VDCreate (that->mm.vdDiskIfaces, &hdd);
3474 ComAssertRCThrow (vrc, E_FAIL);
3475
3476 try
3477 {
3478 /* open all hard disks in the chain (they are in the
3479 * {parent,child} order in there. Note that we don't lock
3480 * objects in this chain since they must be in states
3481 * (Deleting and LockedWrite) that prevent from chaning
3482 * their format and location fields from outside. */
3483
3484 for (MergeChain::const_iterator it = chain->begin();
3485 it != chain->end(); ++ it)
3486 {
3487 /* complex sanity (sane complexity) */
3488 Assert ((chain->isForward() &&
3489 ((*it != chain->back() &&
3490 (*it)->m.state == MediaState_Deleting) ||
3491 (*it == chain->back() &&
3492 (*it)->m.state == MediaState_LockedWrite))) ||
3493 (!chain->isForward() &&
3494 ((*it != chain->front() &&
3495 (*it)->m.state == MediaState_Deleting) ||
3496 (*it == chain->front() &&
3497 (*it)->m.state == MediaState_LockedWrite))));
3498
3499 Assert (*it == chain->target() ||
3500 (*it)->m.backRefs.size() == 0);
3501
3502 /* open the first image with VDOPEN_FLAGS_INFO because
3503 * it's not necessarily the base one */
3504 vrc = VDOpen (hdd, Utf8Str ((*it)->mm.format),
3505 Utf8Str ((*it)->m.locationFull),
3506 it == chain->begin() ?
3507 VD_OPEN_FLAGS_INFO : 0,
3508 NULL);
3509 if (RT_FAILURE (vrc))
3510 throw vrc;
3511#if 1
3512 LogFlow (("*** MERGE disk = %ls\n",
3513 (*it)->m.locationFull.raw()));
3514#endif
3515 }
3516
3517 /* needed for vdProgressCallback */
3518 that->mm.vdProgress = task->progress;
3519
3520 unsigned start = chain->isForward() ?
3521 0 : chain->size() - 1;
3522 unsigned end = chain->isForward() ?
3523 chain->size() - 1 : 0;
3524#if 1
3525 LogFlow (("*** MERGE from %d to %d\n", start, end));
3526#endif
3527 vrc = VDMerge (hdd, start, end, that->mm.vdDiskIfaces);
3528
3529 that->mm.vdProgress = NULL;
3530
3531 if (RT_FAILURE (vrc))
3532 throw vrc;
3533
3534 /* update parent UUIDs */
3535 /// @todo VDMerge should be taught to do so, including the
3536 /// multiple children case
3537 if (chain->isForward())
3538 {
3539 /* target's UUID needs to be updated (note that target
3540 * is the only image in the container on success) */
3541 vrc = VDSetParentUuid (hdd, 0, chain->parent()->m.id);
3542 if (RT_FAILURE (vrc))
3543 throw vrc;
3544 }
3545 else
3546 {
3547 /* we need to update UUIDs of all source's children
3548 * which cannot be part of the container at once so
3549 * add each one in there individually */
3550 if (chain->children().size() > 0)
3551 {
3552 for (List::const_iterator it = chain->children().begin();
3553 it != chain->children().end(); ++ it)
3554 {
3555 /* VD_OPEN_FLAGS_INFO since UUID is wrong yet */
3556 vrc = VDOpen (hdd, Utf8Str ((*it)->mm.format),
3557 Utf8Str ((*it)->m.locationFull),
3558 VD_OPEN_FLAGS_INFO, NULL);
3559 if (RT_FAILURE (vrc))
3560 throw vrc;
3561
3562 vrc = VDSetParentUuid (hdd, 1,
3563 chain->target()->m.id);
3564 if (RT_FAILURE (vrc))
3565 throw vrc;
3566
3567 vrc = VDClose (hdd, false /* fDelete */);
3568 if (RT_FAILURE (vrc))
3569 throw vrc;
3570 }
3571 }
3572 }
3573 }
3574 catch (HRESULT aRC) { rc = aRC; }
3575 catch (int aVRC)
3576 {
3577 throw setError (E_FAIL,
3578 tr ("Could not merge the hard disk '%ls' to '%ls'%s"),
3579 chain->source()->m.locationFull.raw(),
3580 chain->target()->m.locationFull.raw(),
3581 that->vdError (aVRC).raw());
3582 }
3583
3584 VDDestroy (hdd);
3585 }
3586 catch (HRESULT aRC) { rc = aRC; }
3587
3588 HRESULT rc2;
3589
3590 bool saveSettingsFailed = false;
3591
3592 if (SUCCEEDED (rc))
3593 {
3594 /* all hard disks but the target were successfully deleted by
3595 * VDMerge; reparent the last one and uninitialize deleted */
3596
3597 /* we set mParent & children() (note that thatLock is released
3598 * here), but lock VirtualBox first to follow the rule */
3599 AutoMultiWriteLock2 alock (that->mVirtualBox->lockHandle(),
3600 that->treeLock());
3601
3602 HardDisk2 *source = chain->source();
3603 HardDisk2 *target = chain->target();
3604
3605 if (chain->isForward())
3606 {
3607 /* first, unregister the target since it may become a base
3608 * hard disk which needs re-registration */
3609 rc2 = target->mVirtualBox->
3610 unregisterHardDisk2 (target, false /* aSaveSettings */);
3611 AssertComRC (rc2);
3612
3613 /* then, reparent it and disconnect the deleted branch at
3614 * both ends (chain->parent() is source's parent) */
3615 target->mParent->removeDependentChild (target);
3616 target->mParent = chain->parent();
3617 if (!target->mParent.isNull())
3618 {
3619 target->mParent->addDependentChild (target);
3620 target->mParent->removeDependentChild (source);
3621 source->mParent.setNull();
3622 }
3623 else
3624 {
3625 target->mVirtualBox->addDependentChild (target);
3626 target->mVirtualBox->removeDependentChild (source);
3627 }
3628
3629 /* then, register again */
3630 rc2 = target->mVirtualBox->
3631 registerHardDisk2 (target, false /* aSaveSettings */);
3632 AssertComRC (rc2);
3633 }
3634 else
3635 {
3636 Assert (target->children().size() == 1);
3637 HardDisk2 *targetChild = target->children().front();
3638
3639 /* disconnect the deleted branch at the elder end */
3640 target->removeDependentChild (targetChild);
3641 targetChild->mParent.setNull();
3642
3643 const List &children = chain->children();
3644
3645 /* reparent source's chidren and disconnect the deleted
3646 * branch at the younger end m*/
3647 if (children.size() > 0)
3648 {
3649 /* obey {parent,child} lock order */
3650 AutoWriteLock sourceLock (source);
3651
3652 for (List::const_iterator it = children.begin();
3653 it != children.end(); ++ it)
3654 {
3655 AutoWriteLock childLock (*it);
3656
3657 (*it)->mParent = target;
3658 (*it)->mParent->addDependentChild (*it);
3659 source->removeDependentChild (*it);
3660 }
3661 }
3662 }
3663
3664 /* try to save the hard disk registry */
3665 rc = that->mVirtualBox->saveSettings();
3666
3667 if (SUCCEEDED (rc))
3668 {
3669 /* unregister and uninitialize all hard disks in the chain
3670 * but the target */
3671
3672 for (MergeChain::iterator it = chain->begin();
3673 it != chain->end();)
3674 {
3675 if (*it == chain->target())
3676 {
3677 ++ it;
3678 continue;
3679 }
3680
3681 rc2 = (*it)->mVirtualBox->
3682 unregisterHardDisk2 (*it, false /* aSaveSettings */);
3683 AssertComRC (rc2);
3684
3685 /* now, uninitialize the deleted hard disk (note that
3686 * due to the Deleting state, uninit() will not touch
3687 * the parent-child relationship so we need to
3688 * uninitialize each disk individually) */
3689
3690 /* note that the operation initiator hard disk (which is
3691 * normally also the source hard disk) is a special case
3692 * -- there is one more caller added by Task to it which
3693 * we must release. Also, if we are in sync mode, the
3694 * caller may still hold an AutoCaller instance for it
3695 * and therefore we cannot uninit() it (it's therefore
3696 * the caller's responsibility) */
3697 if (*it == that)
3698 task->autoCaller.release();
3699
3700 /* release the caller added by MergeChain before
3701 * uninit() */
3702 (*it)->releaseCaller();
3703
3704 if (isAsync || *it != that)
3705 (*it)->uninit();
3706
3707 /* delete (to prevent uninitialization in MergeChain
3708 * dtor) and advance to the next item */
3709 it = chain->erase (it);
3710 }
3711
3712 /* Note that states of all other hard disks (target, parent,
3713 * children) will be restored by the MergeChain dtor */
3714 }
3715 else
3716 {
3717 /* too bad if we fail, but we'll need to rollback everything
3718 * we did above to at least keep the HD tree in sync with
3719 * the current registry on disk */
3720
3721 saveSettingsFailed = true;
3722
3723 /// @todo NEWMEDIA implement a proper undo
3724
3725 AssertFailed();
3726 }
3727 }
3728
3729 if (FAILED (rc))
3730 {
3731 /* Here we come if either VDMerge() failed (in which case we
3732 * assume that it tried to do everything to make a further
3733 * retry possible -- e.g. not deleted intermediate hard disks
3734 * and so on) or VirtualBox::saveSettings() failed (where we
3735 * should have the original tree but with intermediate storage
3736 * units deleted by VDMerge()). We have to only restore states
3737 * (through the MergeChain dtor) unless we are run synchronously
3738 * in which case it's the responsibility of the caller as stated
3739 * in the mergeTo() docs. The latter also implies that we
3740 * don't own the merge chain, so release it in this case. */
3741
3742 if (!isAsync)
3743 task->d.chain.release();
3744
3745 NOREF (saveSettingsFailed);
3746 }
3747
3748 break;
3749 }
3750
3751 ////////////////////////////////////////////////////////////////////////
3752
3753 case Task::Delete:
3754 {
3755 /* The lock is also used as a signal from the task initiator (which
3756 * releases it only after RTThreadCreate()) that we can start the job */
3757 AutoWriteLock thatLock (that);
3758
3759 try
3760 {
3761 PVBOXHDD hdd;
3762 int vrc = VDCreate (that->mm.vdDiskIfaces, &hdd);
3763 ComAssertRCThrow (vrc, E_FAIL);
3764
3765 Utf8Str format (that->mm.format);
3766 Utf8Str location (that->m.locationFull);
3767
3768 /* unlock before the potentially lengthy operation */
3769 Assert (that->m.state == MediaState_Deleting);
3770 thatLock.leave();
3771
3772 try
3773 {
3774 vrc = VDOpen (hdd, format, location,
3775 VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_INFO,
3776 NULL);
3777 if (RT_SUCCESS (vrc))
3778 vrc = VDClose (hdd, true /* fDelete */);
3779
3780 if (RT_FAILURE (vrc))
3781 {
3782 throw setError (E_FAIL,
3783 tr ("Could not delete the hard disk storage "
3784 "unit '%s'%s"),
3785 location.raw(), that->vdError (vrc).raw());
3786 }
3787
3788 }
3789 catch (HRESULT aRC) { rc = aRC; }
3790
3791 VDDestroy (hdd);
3792 }
3793 catch (HRESULT aRC) { rc = aRC; }
3794
3795 thatLock.maybeEnter();
3796
3797 /* go to the NotCreated state even on failure since the storage
3798 * may have been already partially deleted and cannot be used any
3799 * more. One will be able to manually re-open the storage if really
3800 * needed to re-register it. */
3801 that->m.state = MediaState_NotCreated;
3802
3803 /* Reset UUID to prevent Create* from reusing it again */
3804 unconst (that->m.id).clear();
3805
3806 break;
3807 }
3808
3809 default:
3810 AssertFailedReturn (VERR_GENERAL_FAILURE);
3811 }
3812
3813 /* complete the progress if run asynchronously */
3814 if (isAsync)
3815 {
3816 if (!task->progress.isNull())
3817 task->progress->notifyComplete (rc);
3818 }
3819 else
3820 {
3821 task->rc = rc;
3822 }
3823
3824 LogFlowFunc (("rc=%Rhrc\n", rc));
3825 LogFlowFuncLeave();
3826
3827 return VINF_SUCCESS;
3828
3829 /// @todo ugly hack, fix ComAssert... later
3830 #undef setError
3831}
3832/* vi: set tabstop=4 shiftwidth=4 expandtab: */
Note: See TracBrowser for help on using the repository browser.

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