VirtualBox

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

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

Main: Added ISystemProperties::defaultHardDiskFormat.

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