VirtualBox

source: vbox/trunk/src/VBox/Storage/VD.cpp@ 43787

Last change on this file since 43787 was 43787, checked in by vboxsync, 12 years ago

Storage: Repair images when opening if they are corrupted and can be repaired

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 343.8 KB
Line 
1/* $Id: VD.cpp 43787 2012-10-31 16:27:29Z vboxsync $ */
2/** @file
3 * VBoxHDD - VBox HDD Container implementation.
4 */
5
6/*
7 * Copyright (C) 2006-2012 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18/*******************************************************************************
19* Header Files *
20*******************************************************************************/
21#define LOG_GROUP LOG_GROUP_VD
22#include <VBox/vd.h>
23#include <VBox/err.h>
24#include <VBox/sup.h>
25#include <VBox/log.h>
26
27#include <iprt/alloc.h>
28#include <iprt/assert.h>
29#include <iprt/uuid.h>
30#include <iprt/file.h>
31#include <iprt/string.h>
32#include <iprt/asm.h>
33#include <iprt/ldr.h>
34#include <iprt/dir.h>
35#include <iprt/path.h>
36#include <iprt/param.h>
37#include <iprt/memcache.h>
38#include <iprt/sg.h>
39#include <iprt/critsect.h>
40#include <iprt/list.h>
41#include <iprt/avl.h>
42
43#include <VBox/vd-plugin.h>
44#include <VBox/vd-cache-plugin.h>
45
46/** Disable dynamic backends on non x86 architectures. This feature
47 * requires the SUPR3 library which is not available there.
48 */
49#if !defined(VBOX_HDD_NO_DYNAMIC_BACKENDS) && !defined(RT_ARCH_X86) && !defined(RT_ARCH_AMD64)
50# define VBOX_HDD_NO_DYNAMIC_BACKENDS
51#endif
52
53#define VBOXHDDDISK_SIGNATURE 0x6f0e2a7d
54
55/** Buffer size used for merging images. */
56#define VD_MERGE_BUFFER_SIZE (16 * _1M)
57
58/** Maximum number of segments in one I/O task. */
59#define VD_IO_TASK_SEGMENTS_MAX 64
60
61/** Threshold after not recently used blocks are removed from the list. */
62#define VD_DISCARD_REMOVE_THRESHOLD (10 * _1M) /** @todo: experiment */
63
64/**
65 * VD async I/O interface storage descriptor.
66 */
67typedef struct VDIIOFALLBACKSTORAGE
68{
69 /** File handle. */
70 RTFILE File;
71 /** Completion callback. */
72 PFNVDCOMPLETED pfnCompleted;
73 /** Thread for async access. */
74 RTTHREAD ThreadAsync;
75} VDIIOFALLBACKSTORAGE, *PVDIIOFALLBACKSTORAGE;
76
77/**
78 * Structure containing everything I/O related
79 * for the image and cache descriptors.
80 */
81typedef struct VDIO
82{
83 /** I/O interface to the upper layer. */
84 PVDINTERFACEIO pInterfaceIo;
85
86 /** Per image internal I/O interface. */
87 VDINTERFACEIOINT VDIfIoInt;
88
89 /** Fallback I/O interface, only used if the caller doesn't provide it. */
90 VDINTERFACEIO VDIfIo;
91
92 /** Opaque backend data. */
93 void *pBackendData;
94 /** Disk this image is part of */
95 PVBOXHDD pDisk;
96 /** Flag whether to ignore flush requests. */
97 bool fIgnoreFlush;
98} VDIO, *PVDIO;
99
100/**
101 * VBox HDD Container image descriptor.
102 */
103typedef struct VDIMAGE
104{
105 /** Link to parent image descriptor, if any. */
106 struct VDIMAGE *pPrev;
107 /** Link to child image descriptor, if any. */
108 struct VDIMAGE *pNext;
109 /** Container base filename. (UTF-8) */
110 char *pszFilename;
111 /** Data managed by the backend which keeps the actual info. */
112 void *pBackendData;
113 /** Cached sanitized image flags. */
114 unsigned uImageFlags;
115 /** Image open flags (only those handled generically in this code and which
116 * the backends will never ever see). */
117 unsigned uOpenFlags;
118
119 /** Function pointers for the various backend methods. */
120 PCVBOXHDDBACKEND Backend;
121 /** Pointer to list of VD interfaces, per-image. */
122 PVDINTERFACE pVDIfsImage;
123 /** I/O related things. */
124 VDIO VDIo;
125} VDIMAGE, *PVDIMAGE;
126
127/**
128 * uModified bit flags.
129 */
130#define VD_IMAGE_MODIFIED_FLAG RT_BIT(0)
131#define VD_IMAGE_MODIFIED_FIRST RT_BIT(1)
132#define VD_IMAGE_MODIFIED_DISABLE_UUID_UPDATE RT_BIT(2)
133
134
135/**
136 * VBox HDD Cache image descriptor.
137 */
138typedef struct VDCACHE
139{
140 /** Cache base filename. (UTF-8) */
141 char *pszFilename;
142 /** Data managed by the backend which keeps the actual info. */
143 void *pBackendData;
144 /** Cached sanitized image flags. */
145 unsigned uImageFlags;
146 /** Image open flags (only those handled generically in this code and which
147 * the backends will never ever see). */
148 unsigned uOpenFlags;
149
150 /** Function pointers for the various backend methods. */
151 PCVDCACHEBACKEND Backend;
152
153 /** Pointer to list of VD interfaces, per-cache. */
154 PVDINTERFACE pVDIfsCache;
155 /** I/O related things. */
156 VDIO VDIo;
157} VDCACHE, *PVDCACHE;
158
159/**
160 * A block waiting for a discard.
161 */
162typedef struct VDDISCARDBLOCK
163{
164 /** AVL core. */
165 AVLRU64NODECORE Core;
166 /** LRU list node. */
167 RTLISTNODE NodeLru;
168 /** Number of bytes to discard. */
169 size_t cbDiscard;
170 /** Bitmap of allocated sectors. */
171 void *pbmAllocated;
172} VDDISCARDBLOCK, *PVDDISCARDBLOCK;
173
174/**
175 * VD discard state.
176 */
177typedef struct VDDISCARDSTATE
178{
179 /** Number of bytes waiting for a discard. */
180 size_t cbDiscarding;
181 /** AVL tree with blocks waiting for a discard.
182 * The uOffset + cbDiscard range is the search key. */
183 PAVLRU64TREE pTreeBlocks;
184 /** LRU list of the least frequently discarded blocks.
185 * If there are to many blocks waiting the least frequently used
186 * will be removed and the range will be set to 0.
187 */
188 RTLISTNODE ListLru;
189} VDDISCARDSTATE, *PVDDISCARDSTATE;
190
191/**
192 * VBox HDD Container main structure, private part.
193 */
194struct VBOXHDD
195{
196 /** Structure signature (VBOXHDDDISK_SIGNATURE). */
197 uint32_t u32Signature;
198
199 /** Image type. */
200 VDTYPE enmType;
201
202 /** Number of opened images. */
203 unsigned cImages;
204
205 /** Base image. */
206 PVDIMAGE pBase;
207
208 /** Last opened image in the chain.
209 * The same as pBase if only one image is used. */
210 PVDIMAGE pLast;
211
212 /** If a merge to one of the parents is running this may be non-NULL
213 * to indicate to what image the writes should be additionally relayed. */
214 PVDIMAGE pImageRelay;
215
216 /** Flags representing the modification state. */
217 unsigned uModified;
218
219 /** Cached size of this disk. */
220 uint64_t cbSize;
221 /** Cached PCHS geometry for this disk. */
222 VDGEOMETRY PCHSGeometry;
223 /** Cached LCHS geometry for this disk. */
224 VDGEOMETRY LCHSGeometry;
225
226 /** Pointer to list of VD interfaces, per-disk. */
227 PVDINTERFACE pVDIfsDisk;
228 /** Pointer to the common interface structure for error reporting. */
229 PVDINTERFACEERROR pInterfaceError;
230 /** Pointer to the optional thread synchronization callbacks. */
231 PVDINTERFACETHREADSYNC pInterfaceThreadSync;
232
233 /** Memory cache for I/O contexts */
234 RTMEMCACHE hMemCacheIoCtx;
235 /** Memory cache for I/O tasks. */
236 RTMEMCACHE hMemCacheIoTask;
237 /** Critical section protecting the disk against concurrent access. */
238 RTCRITSECT CritSect;
239 /** Head of queued I/O contexts - LIFO order. */
240 volatile PVDIOCTX pIoCtxHead;
241 /** Flag whether the disk is currently locked by growing write or a flush
242 * request. Other flush or growing write requests need to wait until
243 * the current one completes.
244 */
245 volatile bool fLocked;
246 /** List of waiting requests. - Protected by the critical section. */
247 RTLISTNODE ListWriteLocked;
248 /** I/O context which locked the disk. */
249 PVDIOCTX pIoCtxLockOwner;
250
251 /** Pointer to the L2 disk cache if any. */
252 PVDCACHE pCache;
253 /** Pointer to the discard state if any. */
254 PVDDISCARDSTATE pDiscard;
255};
256
257# define VD_THREAD_IS_CRITSECT_OWNER(Disk) \
258 do \
259 { \
260 AssertMsg(RTCritSectIsOwner(&Disk->CritSect), \
261 ("Thread does not own critical section\n"));\
262 } while(0)
263
264/**
265 * VBox parent read descriptor, used internally for compaction.
266 */
267typedef struct VDPARENTSTATEDESC
268{
269 /** Pointer to disk descriptor. */
270 PVBOXHDD pDisk;
271 /** Pointer to image descriptor. */
272 PVDIMAGE pImage;
273} VDPARENTSTATEDESC, *PVDPARENTSTATEDESC;
274
275/**
276 * Transfer direction.
277 */
278typedef enum VDIOCTXTXDIR
279{
280 /** Read */
281 VDIOCTXTXDIR_READ = 0,
282 /** Write */
283 VDIOCTXTXDIR_WRITE,
284 /** Flush */
285 VDIOCTXTXDIR_FLUSH,
286 /** Discard */
287 VDIOCTXTXDIR_DISCARD,
288 /** 32bit hack */
289 VDIOCTXTXDIR_32BIT_HACK = 0x7fffffff
290} VDIOCTXTXDIR, *PVDIOCTXTXDIR;
291
292/** Transfer function */
293typedef DECLCALLBACK(int) FNVDIOCTXTRANSFER (PVDIOCTX pIoCtx);
294/** Pointer to a transfer function. */
295typedef FNVDIOCTXTRANSFER *PFNVDIOCTXTRANSFER;
296
297/**
298 * I/O context
299 */
300typedef struct VDIOCTX
301{
302 /** Pointer to the next I/O context. */
303 struct VDIOCTX * volatile pIoCtxNext;
304 /** Disk this is request is for. */
305 PVBOXHDD pDisk;
306 /** Return code. */
307 int rcReq;
308 /** Flag whether the I/O context is blocked because it is in the growing list. */
309 bool fBlocked;
310 /** Number of data transfers currently pending. */
311 volatile uint32_t cDataTransfersPending;
312 /** How many meta data transfers are pending. */
313 volatile uint32_t cMetaTransfersPending;
314 /** Flag whether the request finished */
315 volatile bool fComplete;
316 /** Temporary allocated memory which is freed
317 * when the context completes. */
318 void *pvAllocation;
319 /** Transfer function. */
320 PFNVDIOCTXTRANSFER pfnIoCtxTransfer;
321 /** Next transfer part after the current one completed. */
322 PFNVDIOCTXTRANSFER pfnIoCtxTransferNext;
323 /** Transfer direction */
324 VDIOCTXTXDIR enmTxDir;
325 /** Request type dependent data. */
326 union
327 {
328 /** I/O request (read/write). */
329 struct
330 {
331 /** Number of bytes left until this context completes. */
332 volatile uint32_t cbTransferLeft;
333 /** Current offset */
334 volatile uint64_t uOffset;
335 /** Number of bytes to transfer */
336 volatile size_t cbTransfer;
337 /** Current image in the chain. */
338 PVDIMAGE pImageCur;
339 /** Start image to read from. pImageCur is reset to this
340 * value after it reached the first image in the chain. */
341 PVDIMAGE pImageStart;
342 /** S/G buffer */
343 RTSGBUF SgBuf;
344 } Io;
345 /** Discard requests. */
346 struct
347 {
348 /** Pointer to the range descriptor array. */
349 PCRTRANGE paRanges;
350 /** Number of ranges in the array. */
351 unsigned cRanges;
352 /** Range descriptor index which is processed. */
353 unsigned idxRange;
354 /** Start offset to discard currently. */
355 uint64_t offCur;
356 /** How many bytes left to discard in the current range. */
357 size_t cbDiscardLeft;
358 /** How many bytes to discard in the current block (<= cbDiscardLeft). */
359 size_t cbThisDiscard;
360 /** Discard block handled currently. */
361 PVDDISCARDBLOCK pBlock;
362 } Discard;
363 } Req;
364 /** Parent I/O context if any. Sets the type of the context (root/child) */
365 PVDIOCTX pIoCtxParent;
366 /** Type dependent data (root/child) */
367 union
368 {
369 /** Root data */
370 struct
371 {
372 /** Completion callback */
373 PFNVDASYNCTRANSFERCOMPLETE pfnComplete;
374 /** User argument 1 passed on completion. */
375 void *pvUser1;
376 /** User argument 2 passed on completion. */
377 void *pvUser2;
378 } Root;
379 /** Child data */
380 struct
381 {
382 /** Saved start offset */
383 uint64_t uOffsetSaved;
384 /** Saved transfer size */
385 size_t cbTransferLeftSaved;
386 /** Number of bytes transferred from the parent if this context completes. */
387 size_t cbTransferParent;
388 /** Number of bytes to pre read */
389 size_t cbPreRead;
390 /** Number of bytes to post read. */
391 size_t cbPostRead;
392 /** Number of bytes to write left in the parent. */
393 size_t cbWriteParent;
394 /** Write type dependent data. */
395 union
396 {
397 /** Optimized */
398 struct
399 {
400 /** Bytes to fill to satisfy the block size. Not part of the virtual disk. */
401 size_t cbFill;
402 /** Bytes to copy instead of reading from the parent */
403 size_t cbWriteCopy;
404 /** Bytes to read from the image. */
405 size_t cbReadImage;
406 } Optimized;
407 } Write;
408 } Child;
409 } Type;
410} VDIOCTX;
411
412/**
413 * List node for deferred I/O contexts.
414 */
415typedef struct VDIOCTXDEFERRED
416{
417 /** Node in the list of deferred requests.
418 * A request can be deferred if the image is growing
419 * and the request accesses the same range or if
420 * the backend needs to read or write metadata from the disk
421 * before it can continue. */
422 RTLISTNODE NodeDeferred;
423 /** I/O context this entry points to. */
424 PVDIOCTX pIoCtx;
425} VDIOCTXDEFERRED, *PVDIOCTXDEFERRED;
426
427/**
428 * I/O task.
429 */
430typedef struct VDIOTASK
431{
432 /** Storage this task belongs to. */
433 PVDIOSTORAGE pIoStorage;
434 /** Optional completion callback. */
435 PFNVDXFERCOMPLETED pfnComplete;
436 /** Opaque user data. */
437 void *pvUser;
438 /** Flag whether this is a meta data transfer. */
439 bool fMeta;
440 /** Type dependent data. */
441 union
442 {
443 /** User data transfer. */
444 struct
445 {
446 /** Number of bytes this task transferred. */
447 uint32_t cbTransfer;
448 /** Pointer to the I/O context the task belongs. */
449 PVDIOCTX pIoCtx;
450 } User;
451 /** Meta data transfer. */
452 struct
453 {
454 /** Meta transfer this task is for. */
455 PVDMETAXFER pMetaXfer;
456 } Meta;
457 } Type;
458} VDIOTASK, *PVDIOTASK;
459
460/**
461 * Storage handle.
462 */
463typedef struct VDIOSTORAGE
464{
465 /** Image I/O state this storage handle belongs to. */
466 PVDIO pVDIo;
467 /** AVL tree for pending async metadata transfers. */
468 PAVLRFOFFTREE pTreeMetaXfers;
469 /** Storage handle */
470 void *pStorage;
471} VDIOSTORAGE;
472
473/**
474 * Metadata transfer.
475 *
476 * @note This entry can't be freed if either the list is not empty or
477 * the reference counter is not 0.
478 * The assumption is that the backends don't need to read huge amounts of
479 * metadata to complete a transfer so the additional memory overhead should
480 * be relatively small.
481 */
482typedef struct VDMETAXFER
483{
484 /** AVL core for fast search (the file offset is the key) */
485 AVLRFOFFNODECORE Core;
486 /** I/O storage for this transfer. */
487 PVDIOSTORAGE pIoStorage;
488 /** Flags. */
489 uint32_t fFlags;
490 /** List of I/O contexts waiting for this metadata transfer to complete. */
491 RTLISTNODE ListIoCtxWaiting;
492 /** Number of references to this entry. */
493 unsigned cRefs;
494 /** Size of the data stored with this entry. */
495 size_t cbMeta;
496 /** Data stored - variable size. */
497 uint8_t abData[1];
498} VDMETAXFER;
499
500/**
501 * The transfer direction for the metadata.
502 */
503#define VDMETAXFER_TXDIR_MASK 0x3
504#define VDMETAXFER_TXDIR_NONE 0x0
505#define VDMETAXFER_TXDIR_WRITE 0x1
506#define VDMETAXFER_TXDIR_READ 0x2
507#define VDMETAXFER_TXDIR_FLUSH 0x3
508#define VDMETAXFER_TXDIR_GET(flags) ((flags) & VDMETAXFER_TXDIR_MASK)
509#define VDMETAXFER_TXDIR_SET(flags, dir) ((flags) = (flags & ~VDMETAXFER_TXDIR_MASK) | (dir))
510
511extern VBOXHDDBACKEND g_RawBackend;
512extern VBOXHDDBACKEND g_VmdkBackend;
513extern VBOXHDDBACKEND g_VDIBackend;
514extern VBOXHDDBACKEND g_VhdBackend;
515extern VBOXHDDBACKEND g_ParallelsBackend;
516extern VBOXHDDBACKEND g_DmgBackend;
517extern VBOXHDDBACKEND g_ISCSIBackend;
518extern VBOXHDDBACKEND g_QedBackend;
519extern VBOXHDDBACKEND g_QCowBackend;
520extern VBOXHDDBACKEND g_VhdxBackend;
521
522static unsigned g_cBackends = 0;
523static PVBOXHDDBACKEND *g_apBackends = NULL;
524static PVBOXHDDBACKEND aStaticBackends[] =
525{
526 &g_VmdkBackend,
527 &g_VDIBackend,
528 &g_VhdBackend,
529 &g_ParallelsBackend,
530 &g_DmgBackend,
531 &g_QedBackend,
532 &g_QCowBackend,
533 &g_VhdxBackend,
534 &g_RawBackend,
535 &g_ISCSIBackend
536};
537
538/**
539 * Supported backends for the disk cache.
540 */
541extern VDCACHEBACKEND g_VciCacheBackend;
542
543static unsigned g_cCacheBackends = 0;
544static PVDCACHEBACKEND *g_apCacheBackends = NULL;
545static PVDCACHEBACKEND aStaticCacheBackends[] =
546{
547 &g_VciCacheBackend
548};
549
550/** Forward declaration of the async discard helper. */
551static int vdDiscardHelperAsync(PVDIOCTX pIoCtx);
552
553/**
554 * internal: add several backends.
555 */
556static int vdAddBackends(PVBOXHDDBACKEND *ppBackends, unsigned cBackends)
557{
558 PVBOXHDDBACKEND *pTmp = (PVBOXHDDBACKEND*)RTMemRealloc(g_apBackends,
559 (g_cBackends + cBackends) * sizeof(PVBOXHDDBACKEND));
560 if (RT_UNLIKELY(!pTmp))
561 return VERR_NO_MEMORY;
562 g_apBackends = pTmp;
563 memcpy(&g_apBackends[g_cBackends], ppBackends, cBackends * sizeof(PVBOXHDDBACKEND));
564 g_cBackends += cBackends;
565 return VINF_SUCCESS;
566}
567
568/**
569 * internal: add single backend.
570 */
571DECLINLINE(int) vdAddBackend(PVBOXHDDBACKEND pBackend)
572{
573 return vdAddBackends(&pBackend, 1);
574}
575
576/**
577 * internal: add several cache backends.
578 */
579static int vdAddCacheBackends(PVDCACHEBACKEND *ppBackends, unsigned cBackends)
580{
581 PVDCACHEBACKEND *pTmp = (PVDCACHEBACKEND*)RTMemRealloc(g_apCacheBackends,
582 (g_cCacheBackends + cBackends) * sizeof(PVDCACHEBACKEND));
583 if (RT_UNLIKELY(!pTmp))
584 return VERR_NO_MEMORY;
585 g_apCacheBackends = pTmp;
586 memcpy(&g_apCacheBackends[g_cCacheBackends], ppBackends, cBackends * sizeof(PVDCACHEBACKEND));
587 g_cCacheBackends += cBackends;
588 return VINF_SUCCESS;
589}
590
591/**
592 * internal: add single cache backend.
593 */
594DECLINLINE(int) vdAddCacheBackend(PVDCACHEBACKEND pBackend)
595{
596 return vdAddCacheBackends(&pBackend, 1);
597}
598
599/**
600 * internal: issue error message.
601 */
602static int vdError(PVBOXHDD pDisk, int rc, RT_SRC_POS_DECL,
603 const char *pszFormat, ...)
604{
605 va_list va;
606 va_start(va, pszFormat);
607 if (pDisk->pInterfaceError)
608 pDisk->pInterfaceError->pfnError(pDisk->pInterfaceError->Core.pvUser, rc, RT_SRC_POS_ARGS, pszFormat, va);
609 va_end(va);
610 return rc;
611}
612
613/**
614 * internal: thread synchronization, start read.
615 */
616DECLINLINE(int) vdThreadStartRead(PVBOXHDD pDisk)
617{
618 int rc = VINF_SUCCESS;
619 if (RT_UNLIKELY(pDisk->pInterfaceThreadSync))
620 rc = pDisk->pInterfaceThreadSync->pfnStartRead(pDisk->pInterfaceThreadSync->Core.pvUser);
621 return rc;
622}
623
624/**
625 * internal: thread synchronization, finish read.
626 */
627DECLINLINE(int) vdThreadFinishRead(PVBOXHDD pDisk)
628{
629 int rc = VINF_SUCCESS;
630 if (RT_UNLIKELY(pDisk->pInterfaceThreadSync))
631 rc = pDisk->pInterfaceThreadSync->pfnFinishRead(pDisk->pInterfaceThreadSync->Core.pvUser);
632 return rc;
633}
634
635/**
636 * internal: thread synchronization, start write.
637 */
638DECLINLINE(int) vdThreadStartWrite(PVBOXHDD pDisk)
639{
640 int rc = VINF_SUCCESS;
641 if (RT_UNLIKELY(pDisk->pInterfaceThreadSync))
642 rc = pDisk->pInterfaceThreadSync->pfnStartWrite(pDisk->pInterfaceThreadSync->Core.pvUser);
643 return rc;
644}
645
646/**
647 * internal: thread synchronization, finish write.
648 */
649DECLINLINE(int) vdThreadFinishWrite(PVBOXHDD pDisk)
650{
651 int rc = VINF_SUCCESS;
652 if (RT_UNLIKELY(pDisk->pInterfaceThreadSync))
653 rc = pDisk->pInterfaceThreadSync->pfnFinishWrite(pDisk->pInterfaceThreadSync->Core.pvUser);
654 return rc;
655}
656
657/**
658 * internal: find image format backend.
659 */
660static int vdFindBackend(const char *pszBackend, PCVBOXHDDBACKEND *ppBackend)
661{
662 int rc = VINF_SUCCESS;
663 PCVBOXHDDBACKEND pBackend = NULL;
664
665 if (!g_apBackends)
666 VDInit();
667
668 for (unsigned i = 0; i < g_cBackends; i++)
669 {
670 if (!RTStrICmp(pszBackend, g_apBackends[i]->pszBackendName))
671 {
672 pBackend = g_apBackends[i];
673 break;
674 }
675 }
676 *ppBackend = pBackend;
677 return rc;
678}
679
680/**
681 * internal: find cache format backend.
682 */
683static int vdFindCacheBackend(const char *pszBackend, PCVDCACHEBACKEND *ppBackend)
684{
685 int rc = VINF_SUCCESS;
686 PCVDCACHEBACKEND pBackend = NULL;
687
688 if (!g_apCacheBackends)
689 VDInit();
690
691 for (unsigned i = 0; i < g_cCacheBackends; i++)
692 {
693 if (!RTStrICmp(pszBackend, g_apCacheBackends[i]->pszBackendName))
694 {
695 pBackend = g_apCacheBackends[i];
696 break;
697 }
698 }
699 *ppBackend = pBackend;
700 return rc;
701}
702
703/**
704 * internal: add image structure to the end of images list.
705 */
706static void vdAddImageToList(PVBOXHDD pDisk, PVDIMAGE pImage)
707{
708 pImage->pPrev = NULL;
709 pImage->pNext = NULL;
710
711 if (pDisk->pBase)
712 {
713 Assert(pDisk->cImages > 0);
714 pImage->pPrev = pDisk->pLast;
715 pDisk->pLast->pNext = pImage;
716 pDisk->pLast = pImage;
717 }
718 else
719 {
720 Assert(pDisk->cImages == 0);
721 pDisk->pBase = pImage;
722 pDisk->pLast = pImage;
723 }
724
725 pDisk->cImages++;
726}
727
728/**
729 * internal: remove image structure from the images list.
730 */
731static void vdRemoveImageFromList(PVBOXHDD pDisk, PVDIMAGE pImage)
732{
733 Assert(pDisk->cImages > 0);
734
735 if (pImage->pPrev)
736 pImage->pPrev->pNext = pImage->pNext;
737 else
738 pDisk->pBase = pImage->pNext;
739
740 if (pImage->pNext)
741 pImage->pNext->pPrev = pImage->pPrev;
742 else
743 pDisk->pLast = pImage->pPrev;
744
745 pImage->pPrev = NULL;
746 pImage->pNext = NULL;
747
748 pDisk->cImages--;
749}
750
751/**
752 * internal: find image by index into the images list.
753 */
754static PVDIMAGE vdGetImageByNumber(PVBOXHDD pDisk, unsigned nImage)
755{
756 PVDIMAGE pImage = pDisk->pBase;
757 if (nImage == VD_LAST_IMAGE)
758 return pDisk->pLast;
759 while (pImage && nImage)
760 {
761 pImage = pImage->pNext;
762 nImage--;
763 }
764 return pImage;
765}
766
767/**
768 * Internal: Tries to read the desired range from the given cache.
769 *
770 * @returns VBox status code.
771 * @retval VERR_VD_BLOCK_FREE if the block is not in the cache.
772 * pcbRead will be set to the number of bytes not in the cache.
773 * Everything thereafter might be in the cache.
774 * @param pCache The cache to read from.
775 * @param uOffset Offset of the virtual disk to read.
776 * @param pvBuf Where to store the read data.
777 * @param cbRead How much to read.
778 * @param pcbRead Where to store the number of bytes actually read.
779 * On success this indicates the number of bytes read from the cache.
780 * If VERR_VD_BLOCK_FREE is returned this gives the number of bytes
781 * which are not in the cache.
782 * In both cases everything beyond this value
783 * might or might not be in the cache.
784 */
785static int vdCacheReadHelper(PVDCACHE pCache, uint64_t uOffset,
786 void *pvBuf, size_t cbRead, size_t *pcbRead)
787{
788 int rc = VINF_SUCCESS;
789
790 LogFlowFunc(("pCache=%#p uOffset=%llu pvBuf=%#p cbRead=%zu pcbRead=%#p\n",
791 pCache, uOffset, pvBuf, cbRead, pcbRead));
792
793 AssertPtr(pCache);
794 AssertPtr(pcbRead);
795
796 rc = pCache->Backend->pfnRead(pCache->pBackendData, uOffset, pvBuf,
797 cbRead, pcbRead);
798
799 LogFlowFunc(("returns rc=%Rrc pcbRead=%zu\n", rc, *pcbRead));
800 return rc;
801}
802
803/**
804 * Internal: Writes data for the given block into the cache.
805 *
806 * @returns VBox status code.
807 * @param pCache The cache to write to.
808 * @param uOffset Offset of the virtual disk to write to the cache.
809 * @param pcvBuf The data to write.
810 * @param cbWrite How much to write.
811 * @param pcbWritten How much data could be written, optional.
812 */
813static int vdCacheWriteHelper(PVDCACHE pCache, uint64_t uOffset, const void *pcvBuf,
814 size_t cbWrite, size_t *pcbWritten)
815{
816 int rc = VINF_SUCCESS;
817
818 LogFlowFunc(("pCache=%#p uOffset=%llu pvBuf=%#p cbWrite=%zu pcbWritten=%#p\n",
819 pCache, uOffset, pcvBuf, cbWrite, pcbWritten));
820
821 AssertPtr(pCache);
822 AssertPtr(pcvBuf);
823 Assert(cbWrite > 0);
824
825 if (pcbWritten)
826 rc = pCache->Backend->pfnWrite(pCache->pBackendData, uOffset, pcvBuf,
827 cbWrite, pcbWritten);
828 else
829 {
830 size_t cbWritten = 0;
831
832 do
833 {
834 rc = pCache->Backend->pfnWrite(pCache->pBackendData, uOffset, pcvBuf,
835 cbWrite, &cbWritten);
836 uOffset += cbWritten;
837 pcvBuf = (char *)pcvBuf + cbWritten;
838 cbWrite -= cbWritten;
839 } while ( cbWrite
840 && RT_SUCCESS(rc));
841 }
842
843 LogFlowFunc(("returns rc=%Rrc pcbWritten=%zu\n",
844 rc, pcbWritten ? *pcbWritten : cbWrite));
845 return rc;
846}
847
848/**
849 * Internal: Reads a given amount of data from the image chain of the disk.
850 **/
851static int vdDiskReadHelper(PVBOXHDD pDisk, PVDIMAGE pImage, PVDIMAGE pImageParentOverride,
852 uint64_t uOffset, void *pvBuf, size_t cbRead, size_t *pcbThisRead)
853{
854 int rc = VINF_SUCCESS;
855 size_t cbThisRead = cbRead;
856
857 AssertPtr(pcbThisRead);
858
859 *pcbThisRead = 0;
860
861 /*
862 * Try to read from the given image.
863 * If the block is not allocated read from override chain if present.
864 */
865 rc = pImage->Backend->pfnRead(pImage->pBackendData,
866 uOffset, pvBuf, cbThisRead,
867 &cbThisRead);
868
869 if (rc == VERR_VD_BLOCK_FREE)
870 {
871 for (PVDIMAGE pCurrImage = pImageParentOverride ? pImageParentOverride : pImage->pPrev;
872 pCurrImage != NULL && rc == VERR_VD_BLOCK_FREE;
873 pCurrImage = pCurrImage->pPrev)
874 {
875 rc = pCurrImage->Backend->pfnRead(pCurrImage->pBackendData,
876 uOffset, pvBuf, cbThisRead,
877 &cbThisRead);
878 }
879 }
880
881 if (RT_SUCCESS(rc) || rc == VERR_VD_BLOCK_FREE)
882 *pcbThisRead = cbThisRead;
883
884 return rc;
885}
886
887/**
888 * Extended version of vdReadHelper(), implementing certain optimizations
889 * for image cloning.
890 *
891 * @returns VBox status code.
892 * @param pDisk The disk to read from.
893 * @param pImage The image to start reading from.
894 * @param pImageParentOverride The parent image to read from
895 * if the starting image returns a free block.
896 * If NULL is passed the real parent of the image
897 * in the chain is used.
898 * @param uOffset Offset in the disk to start reading from.
899 * @param pvBuf Where to store the read data.
900 * @param cbRead How much to read.
901 * @param fZeroFreeBlocks Flag whether free blocks should be zeroed.
902 * If false and no image has data for sepcified
903 * range VERR_VD_BLOCK_FREE is returned.
904 * Note that unallocated blocks are still zeroed
905 * if at least one image has valid data for a part
906 * of the range.
907 * @param fUpdateCache Flag whether to update the attached cache if
908 * available.
909 * @param cImagesRead Number of images in the chain to read until
910 * the read is cut off. A value of 0 disables the cut off.
911 */
912static int vdReadHelperEx(PVBOXHDD pDisk, PVDIMAGE pImage, PVDIMAGE pImageParentOverride,
913 uint64_t uOffset, void *pvBuf, size_t cbRead,
914 bool fZeroFreeBlocks, bool fUpdateCache, unsigned cImagesRead)
915{
916 int rc = VINF_SUCCESS;
917 size_t cbThisRead;
918 bool fAllFree = true;
919 size_t cbBufClear = 0;
920
921 /* Loop until all read. */
922 do
923 {
924 /* Search for image with allocated block. Do not attempt to read more
925 * than the previous reads marked as valid. Otherwise this would return
926 * stale data when different block sizes are used for the images. */
927 cbThisRead = cbRead;
928
929 if ( pDisk->pCache
930 && !pImageParentOverride)
931 {
932 rc = vdCacheReadHelper(pDisk->pCache, uOffset, pvBuf,
933 cbThisRead, &cbThisRead);
934
935 if (rc == VERR_VD_BLOCK_FREE)
936 {
937 rc = vdDiskReadHelper(pDisk, pImage, NULL, uOffset, pvBuf, cbThisRead,
938 &cbThisRead);
939
940 /* If the read was successful, write the data back into the cache. */
941 if ( RT_SUCCESS(rc)
942 && fUpdateCache)
943 {
944 rc = vdCacheWriteHelper(pDisk->pCache, uOffset, pvBuf,
945 cbThisRead, NULL);
946 }
947 }
948 }
949 else
950 {
951 /** @todo can be be replaced by vdDiskReadHelper if it proves to be reliable,
952 * don't want to be responsible for data corruption...
953 */
954 /*
955 * Try to read from the given image.
956 * If the block is not allocated read from override chain if present.
957 */
958 rc = pImage->Backend->pfnRead(pImage->pBackendData,
959 uOffset, pvBuf, cbThisRead,
960 &cbThisRead);
961
962 if ( rc == VERR_VD_BLOCK_FREE
963 && cImagesRead != 1)
964 {
965 unsigned cImagesToProcess = cImagesRead;
966
967 for (PVDIMAGE pCurrImage = pImageParentOverride ? pImageParentOverride : pImage->pPrev;
968 pCurrImage != NULL && rc == VERR_VD_BLOCK_FREE;
969 pCurrImage = pCurrImage->pPrev)
970 {
971 rc = pCurrImage->Backend->pfnRead(pCurrImage->pBackendData,
972 uOffset, pvBuf, cbThisRead,
973 &cbThisRead);
974 if (cImagesToProcess == 1)
975 break;
976 else if (cImagesToProcess > 0)
977 cImagesToProcess--;
978 }
979 }
980 }
981
982 /* No image in the chain contains the data for the block. */
983 if (rc == VERR_VD_BLOCK_FREE)
984 {
985 /* Fill the free space with 0 if we are told to do so
986 * or a previous read returned valid data. */
987 if (fZeroFreeBlocks || !fAllFree)
988 memset(pvBuf, '\0', cbThisRead);
989 else
990 cbBufClear += cbThisRead;
991
992 if (pImage->uOpenFlags & VD_OPEN_FLAGS_INFORM_ABOUT_ZERO_BLOCKS)
993 rc = VINF_VD_NEW_ZEROED_BLOCK;
994 else
995 rc = VINF_SUCCESS;
996 }
997 else if (RT_SUCCESS(rc))
998 {
999 /* First not free block, fill the space before with 0. */
1000 if (!fZeroFreeBlocks)
1001 {
1002 memset((char *)pvBuf - cbBufClear, '\0', cbBufClear);
1003 cbBufClear = 0;
1004 fAllFree = false;
1005 }
1006 }
1007
1008 cbRead -= cbThisRead;
1009 uOffset += cbThisRead;
1010 pvBuf = (char *)pvBuf + cbThisRead;
1011 } while (cbRead != 0 && RT_SUCCESS(rc));
1012
1013 return (!fZeroFreeBlocks && fAllFree) ? VERR_VD_BLOCK_FREE : rc;
1014}
1015
1016/**
1017 * internal: read the specified amount of data in whatever blocks the backend
1018 * will give us.
1019 */
1020static int vdReadHelper(PVBOXHDD pDisk, PVDIMAGE pImage, uint64_t uOffset,
1021 void *pvBuf, size_t cbRead, bool fUpdateCache)
1022{
1023 return vdReadHelperEx(pDisk, pImage, NULL, uOffset, pvBuf, cbRead,
1024 true /* fZeroFreeBlocks */, fUpdateCache, 0);
1025}
1026
1027/**
1028 * Creates a new empty discard state.
1029 *
1030 * @returns Pointer to the new discard state or NULL if out of memory.
1031 */
1032static PVDDISCARDSTATE vdDiscardStateCreate(void)
1033{
1034 PVDDISCARDSTATE pDiscard = (PVDDISCARDSTATE)RTMemAllocZ(sizeof(VDDISCARDSTATE));
1035
1036 if (pDiscard)
1037 {
1038 RTListInit(&pDiscard->ListLru);
1039 pDiscard->pTreeBlocks = (PAVLRU64TREE)RTMemAllocZ(sizeof(AVLRU64TREE));
1040 if (!pDiscard->pTreeBlocks)
1041 {
1042 RTMemFree(pDiscard);
1043 pDiscard = NULL;
1044 }
1045 }
1046
1047 return pDiscard;
1048}
1049
1050/**
1051 * Removes the least recently used blocks from the waiting list until
1052 * the new value is reached.
1053 *
1054 * @returns VBox status code.
1055 * @param pDisk VD disk container.
1056 * @param pDiscard The discard state.
1057 * @param cbDiscardingNew How many bytes should be waiting on success.
1058 * The number of bytes waiting can be less.
1059 */
1060static int vdDiscardRemoveBlocks(PVBOXHDD pDisk, PVDDISCARDSTATE pDiscard, size_t cbDiscardingNew)
1061{
1062 int rc = VINF_SUCCESS;
1063
1064 LogFlowFunc(("pDisk=%#p pDiscard=%#p cbDiscardingNew=%zu\n",
1065 pDisk, pDiscard, cbDiscardingNew));
1066
1067 while (pDiscard->cbDiscarding > cbDiscardingNew)
1068 {
1069 PVDDISCARDBLOCK pBlock = RTListGetLast(&pDiscard->ListLru, VDDISCARDBLOCK, NodeLru);
1070
1071 Assert(!RTListIsEmpty(&pDiscard->ListLru));
1072
1073 /* Go over the allocation bitmap and mark all discarded sectors as unused. */
1074 uint64_t offStart = pBlock->Core.Key;
1075 uint32_t idxStart = 0;
1076 size_t cbLeft = pBlock->cbDiscard;
1077 bool fAllocated = ASMBitTest(pBlock->pbmAllocated, idxStart);
1078 uint32_t cSectors = pBlock->cbDiscard / 512;
1079
1080 while (cbLeft > 0)
1081 {
1082 int32_t idxEnd;
1083 size_t cbThis = cbLeft;
1084
1085 if (fAllocated)
1086 {
1087 /* Check for the first unallocated bit. */
1088 idxEnd = ASMBitNextClear(pBlock->pbmAllocated, cSectors, idxStart);
1089 if (idxEnd != -1)
1090 {
1091 cbThis = (idxEnd - idxStart) * 512;
1092 fAllocated = false;
1093 }
1094 }
1095 else
1096 {
1097 /* Mark as unused and check for the first set bit. */
1098 idxEnd = ASMBitNextSet(pBlock->pbmAllocated, cSectors, idxStart);
1099 if (idxEnd != -1)
1100 cbThis = (idxEnd - idxStart) * 512;
1101
1102 rc = pDisk->pLast->Backend->pfnDiscard(pDisk->pLast->pBackendData, offStart,
1103 cbThis, NULL, NULL, &cbThis,
1104 NULL, VD_DISCARD_MARK_UNUSED);
1105 if (RT_FAILURE(rc))
1106 break;
1107
1108 fAllocated = true;
1109 }
1110
1111 idxStart = idxEnd;
1112 offStart += cbThis;
1113 cbLeft -= cbThis;
1114 }
1115
1116 if (RT_FAILURE(rc))
1117 break;
1118
1119 PVDDISCARDBLOCK pBlockRemove = (PVDDISCARDBLOCK)RTAvlrU64RangeRemove(pDiscard->pTreeBlocks, pBlock->Core.Key);
1120 Assert(pBlockRemove == pBlock);
1121 RTListNodeRemove(&pBlock->NodeLru);
1122
1123 pDiscard->cbDiscarding -= pBlock->cbDiscard;
1124 RTMemFree(pBlock->pbmAllocated);
1125 RTMemFree(pBlock);
1126 }
1127
1128 Assert(RT_FAILURE(rc) || pDiscard->cbDiscarding <= cbDiscardingNew);
1129
1130 LogFlowFunc(("returns rc=%Rrc\n", rc));
1131 return rc;
1132}
1133
1134/**
1135 * Destroys the current discard state, writing any waiting blocks to the image.
1136 *
1137 * @returns VBox status code.
1138 * @param pDisk VD disk container.
1139 */
1140static int vdDiscardStateDestroy(PVBOXHDD pDisk)
1141{
1142 int rc = VINF_SUCCESS;
1143
1144 if (pDisk->pDiscard)
1145 {
1146 rc = vdDiscardRemoveBlocks(pDisk, pDisk->pDiscard, 0 /* Remove all blocks. */);
1147 AssertRC(rc);
1148 RTMemFree(pDisk->pDiscard->pTreeBlocks);
1149 RTMemFree(pDisk->pDiscard);
1150 pDisk->pDiscard = NULL;
1151 }
1152
1153 return rc;
1154}
1155
1156/**
1157 * Discards the given range from the underlying block.
1158 *
1159 * @returns VBox status code.
1160 * @param pDisk VD container data.
1161 * @param offStart Where to start discarding.
1162 * @param cbDiscard How many bytes to discard.
1163 */
1164static int vdDiscardRange(PVBOXHDD pDisk, PVDDISCARDSTATE pDiscard, uint64_t offStart, size_t cbDiscard)
1165{
1166 int rc = VINF_SUCCESS;
1167
1168 LogFlowFunc(("pDisk=%#p pDiscard=%#p offStart=%llu cbDiscard=%zu\n",
1169 pDisk, pDiscard, offStart, cbDiscard));
1170
1171 do
1172 {
1173 size_t cbThisDiscard;
1174
1175 /* Look for a matching block in the AVL tree first. */
1176 PVDDISCARDBLOCK pBlock = (PVDDISCARDBLOCK)RTAvlrU64GetBestFit(pDiscard->pTreeBlocks, offStart, false);
1177 if (!pBlock || pBlock->Core.KeyLast < offStart)
1178 {
1179 void *pbmAllocated = NULL;
1180 size_t cbPreAllocated, cbPostAllocated;
1181 PVDDISCARDBLOCK pBlockAbove = (PVDDISCARDBLOCK)RTAvlrU64GetBestFit(pDiscard->pTreeBlocks, offStart, true);
1182
1183 /* Clip range to remain in the current block. */
1184 if (pBlockAbove)
1185 cbThisDiscard = RT_MIN(cbDiscard, pBlockAbove->Core.KeyLast - offStart + 1);
1186 else
1187 cbThisDiscard = cbDiscard;
1188
1189 Assert(!(cbThisDiscard % 512));
1190
1191 /* No block found, try to discard using the backend first. */
1192 rc = pDisk->pLast->Backend->pfnDiscard(pDisk->pLast->pBackendData, offStart,
1193 cbThisDiscard, &cbPreAllocated,
1194 &cbPostAllocated, &cbThisDiscard,
1195 &pbmAllocated, 0);
1196 if (rc == VERR_VD_DISCARD_ALIGNMENT_NOT_MET)
1197 {
1198 /* Create new discard block. */
1199 pBlock = (PVDDISCARDBLOCK)RTMemAllocZ(sizeof(VDDISCARDBLOCK));
1200 if (pBlock)
1201 {
1202 pBlock->Core.Key = offStart - cbPreAllocated;
1203 pBlock->Core.KeyLast = offStart + cbThisDiscard + cbPostAllocated - 1;
1204 pBlock->cbDiscard = cbPreAllocated + cbThisDiscard + cbPostAllocated;
1205 pBlock->pbmAllocated = pbmAllocated;
1206 bool fInserted = RTAvlrU64Insert(pDiscard->pTreeBlocks, &pBlock->Core);
1207 Assert(fInserted);
1208
1209 RTListPrepend(&pDiscard->ListLru, &pBlock->NodeLru);
1210 pDiscard->cbDiscarding += pBlock->cbDiscard;
1211 if (pDiscard->cbDiscarding > VD_DISCARD_REMOVE_THRESHOLD)
1212 rc = vdDiscardRemoveBlocks(pDisk, pDiscard, VD_DISCARD_REMOVE_THRESHOLD);
1213 else
1214 rc = VINF_SUCCESS;
1215 }
1216 else
1217 {
1218 RTMemFree(pbmAllocated);
1219 rc = VERR_NO_MEMORY;
1220 }
1221 }
1222 }
1223 else
1224 {
1225 /* Range lies partly in the block, update allocation bitmap. */
1226 int32_t idxStart, idxEnd;
1227
1228 cbThisDiscard = RT_MIN(cbDiscard, pBlock->Core.KeyLast - offStart + 1);
1229
1230 AssertPtr(pBlock);
1231
1232 Assert(!(cbThisDiscard % 512));
1233 Assert(!((offStart - pBlock->Core.Key) % 512));
1234
1235 idxStart = (offStart - pBlock->Core.Key) / 512;
1236 idxEnd = idxStart + (cbThisDiscard / 512);
1237
1238 ASMBitClearRange(pBlock->pbmAllocated, idxStart, idxEnd);
1239
1240 /* Call the backend to discard the block if it is completely unallocated now. */
1241 if (ASMBitFirstSet((volatile void *)pBlock->pbmAllocated, pBlock->cbDiscard / 512) == -1)
1242 {
1243 size_t cbPreAllocated, cbPostAllocated, cbActuallyDiscarded;
1244
1245 rc = pDisk->pLast->Backend->pfnDiscard(pDisk->pLast->pBackendData, pBlock->Core.Key,
1246 pBlock->cbDiscard, &cbPreAllocated,
1247 &cbPostAllocated, &cbActuallyDiscarded,
1248 NULL, 0);
1249 Assert(rc != VERR_VD_DISCARD_ALIGNMENT_NOT_MET);
1250 Assert(!cbPreAllocated);
1251 Assert(!cbPostAllocated);
1252 Assert(cbActuallyDiscarded == pBlock->cbDiscard || RT_FAILURE(rc));
1253
1254 /* Remove the block on success. */
1255 if (RT_SUCCESS(rc))
1256 {
1257 PVDDISCARDBLOCK pBlockRemove = (PVDDISCARDBLOCK)RTAvlrU64RangeRemove(pDiscard->pTreeBlocks, pBlock->Core.Key);
1258 Assert(pBlockRemove == pBlock);
1259
1260 pDiscard->cbDiscarding -= pBlock->cbDiscard;
1261 RTListNodeRemove(&pBlock->NodeLru);
1262 RTMemFree(pBlock->pbmAllocated);
1263 RTMemFree(pBlock);
1264 }
1265 }
1266 else
1267 {
1268 RTListNodeRemove(&pBlock->NodeLru);
1269 RTListPrepend(&pDiscard->ListLru, &pBlock->NodeLru);
1270 rc = VINF_SUCCESS;
1271 }
1272 }
1273
1274 Assert(cbDiscard >= cbThisDiscard);
1275
1276 cbDiscard -= cbThisDiscard;
1277 offStart += cbThisDiscard;
1278 } while (cbDiscard != 0 && RT_SUCCESS(rc));
1279
1280 LogFlowFunc(("returns rc=%Rrc\n", rc));
1281 return rc;
1282}
1283
1284/**
1285 * Discard helper.
1286 *
1287 * @returns VBox status code.
1288 * @param pDisk VD container data.
1289 * @param paRanges The array of ranges to discard.
1290 * @param cRanges The number of ranges in the array.
1291 */
1292static int vdDiscardHelper(PVBOXHDD pDisk, PCRTRANGE paRanges, unsigned cRanges)
1293{
1294 int rc = VINF_SUCCESS;
1295 PVDDISCARDSTATE pDiscard = pDisk->pDiscard;
1296
1297 if (RT_UNLIKELY(!pDiscard))
1298 {
1299 pDiscard = vdDiscardStateCreate();
1300 if (!pDiscard)
1301 return VERR_NO_MEMORY;
1302
1303 pDisk->pDiscard = pDiscard;
1304 }
1305
1306 /* Go over the range array and discard individual blocks. */
1307 for (unsigned i = 0; i < cRanges; i++)
1308 {
1309 rc = vdDiscardRange(pDisk, pDiscard, paRanges[i].offStart, paRanges[i].cbRange);
1310 if (RT_FAILURE(rc))
1311 break;
1312 }
1313
1314 return rc;
1315}
1316
1317/**
1318 * Marks the given range as allocated in the image.
1319 * Required if there are discards in progress and a write to a block which can get discarded
1320 * is written to.
1321 *
1322 * @returns VBox status code.
1323 * @param pDisk VD container data.
1324 * @param uOffset First byte to mark as allocated.
1325 * @param cbRange Number of bytes to mark as allocated.
1326 */
1327static int vdDiscardSetRangeAllocated(PVBOXHDD pDisk, uint64_t uOffset, size_t cbRange)
1328{
1329 PVDDISCARDSTATE pDiscard = pDisk->pDiscard;
1330 int rc = VINF_SUCCESS;
1331
1332 if (pDiscard)
1333 {
1334 do
1335 {
1336 size_t cbThisRange = cbRange;
1337 PVDDISCARDBLOCK pBlock = (PVDDISCARDBLOCK)RTAvlrU64RangeGet(pDiscard->pTreeBlocks, uOffset);
1338
1339 if (pBlock)
1340 {
1341 int32_t idxStart, idxEnd;
1342
1343 Assert(!(cbThisRange % 512));
1344 Assert(!((uOffset - pBlock->Core.Key) % 512));
1345
1346 cbThisRange = RT_MIN(cbThisRange, pBlock->Core.KeyLast - uOffset + 1);
1347
1348 idxStart = (uOffset - pBlock->Core.Key) / 512;
1349 idxEnd = idxStart + (cbThisRange / 512);
1350 ASMBitSetRange(pBlock->pbmAllocated, idxStart, idxEnd);
1351 }
1352 else
1353 {
1354 pBlock = (PVDDISCARDBLOCK)RTAvlrU64GetBestFit(pDiscard->pTreeBlocks, uOffset, true);
1355 if (pBlock)
1356 cbThisRange = RT_MIN(cbThisRange, pBlock->Core.Key - uOffset);
1357 }
1358
1359 Assert(cbRange >= cbThisRange);
1360
1361 uOffset += cbThisRange;
1362 cbRange -= cbThisRange;
1363 } while (cbRange != 0);
1364 }
1365
1366 return rc;
1367}
1368
1369DECLINLINE(PVDIOCTX) vdIoCtxAlloc(PVBOXHDD pDisk, VDIOCTXTXDIR enmTxDir,
1370 uint64_t uOffset, size_t cbTransfer,
1371 PVDIMAGE pImageStart,
1372 PCRTSGBUF pcSgBuf, void *pvAllocation,
1373 PFNVDIOCTXTRANSFER pfnIoCtxTransfer)
1374{
1375 PVDIOCTX pIoCtx = NULL;
1376
1377 pIoCtx = (PVDIOCTX)RTMemCacheAlloc(pDisk->hMemCacheIoCtx);
1378 if (RT_LIKELY(pIoCtx))
1379 {
1380 pIoCtx->pDisk = pDisk;
1381 pIoCtx->enmTxDir = enmTxDir;
1382 pIoCtx->Req.Io.cbTransferLeft = cbTransfer;
1383 pIoCtx->Req.Io.uOffset = uOffset;
1384 pIoCtx->Req.Io.cbTransfer = cbTransfer;
1385 pIoCtx->Req.Io.pImageStart = pImageStart;
1386 pIoCtx->Req.Io.pImageCur = pImageStart;
1387 pIoCtx->cDataTransfersPending = 0;
1388 pIoCtx->cMetaTransfersPending = 0;
1389 pIoCtx->fComplete = false;
1390 pIoCtx->fBlocked = false;
1391 pIoCtx->pvAllocation = pvAllocation;
1392 pIoCtx->pfnIoCtxTransfer = pfnIoCtxTransfer;
1393 pIoCtx->pfnIoCtxTransferNext = NULL;
1394 pIoCtx->rcReq = VINF_SUCCESS;
1395
1396 /* There is no S/G list for a flush request. */
1397 if (enmTxDir != VDIOCTXTXDIR_FLUSH)
1398 RTSgBufClone(&pIoCtx->Req.Io.SgBuf, pcSgBuf);
1399 else
1400 memset(&pIoCtx->Req.Io.SgBuf, 0, sizeof(RTSGBUF));
1401 }
1402
1403 return pIoCtx;
1404}
1405
1406DECLINLINE(PVDIOCTX) vdIoCtxRootAlloc(PVBOXHDD pDisk, VDIOCTXTXDIR enmTxDir,
1407 uint64_t uOffset, size_t cbTransfer,
1408 PVDIMAGE pImageStart, PCRTSGBUF pcSgBuf,
1409 PFNVDASYNCTRANSFERCOMPLETE pfnComplete,
1410 void *pvUser1, void *pvUser2,
1411 void *pvAllocation,
1412 PFNVDIOCTXTRANSFER pfnIoCtxTransfer)
1413{
1414 PVDIOCTX pIoCtx = vdIoCtxAlloc(pDisk, enmTxDir, uOffset, cbTransfer, pImageStart,
1415 pcSgBuf, pvAllocation, pfnIoCtxTransfer);
1416
1417 if (RT_LIKELY(pIoCtx))
1418 {
1419 pIoCtx->pIoCtxParent = NULL;
1420 pIoCtx->Type.Root.pfnComplete = pfnComplete;
1421 pIoCtx->Type.Root.pvUser1 = pvUser1;
1422 pIoCtx->Type.Root.pvUser2 = pvUser2;
1423 }
1424
1425 LogFlow(("Allocated root I/O context %#p\n", pIoCtx));
1426 return pIoCtx;
1427}
1428
1429DECLINLINE(PVDIOCTX) vdIoCtxDiscardAlloc(PVBOXHDD pDisk, PCRTRANGE paRanges,
1430 unsigned cRanges,
1431 PFNVDASYNCTRANSFERCOMPLETE pfnComplete,
1432 void *pvUser1, void *pvUser2,
1433 void *pvAllocation,
1434 PFNVDIOCTXTRANSFER pfnIoCtxTransfer)
1435{
1436 PVDIOCTX pIoCtx = NULL;
1437
1438 pIoCtx = (PVDIOCTX)RTMemCacheAlloc(pDisk->hMemCacheIoCtx);
1439 if (RT_LIKELY(pIoCtx))
1440 {
1441 pIoCtx->pIoCtxNext = NULL;
1442 pIoCtx->pDisk = pDisk;
1443 pIoCtx->enmTxDir = VDIOCTXTXDIR_DISCARD;
1444 pIoCtx->cDataTransfersPending = 0;
1445 pIoCtx->cMetaTransfersPending = 0;
1446 pIoCtx->fComplete = false;
1447 pIoCtx->fBlocked = false;
1448 pIoCtx->pvAllocation = pvAllocation;
1449 pIoCtx->pfnIoCtxTransfer = pfnIoCtxTransfer;
1450 pIoCtx->pfnIoCtxTransferNext = NULL;
1451 pIoCtx->rcReq = VINF_SUCCESS;
1452 pIoCtx->Req.Discard.paRanges = paRanges;
1453 pIoCtx->Req.Discard.cRanges = cRanges;
1454 pIoCtx->Req.Discard.idxRange = 0;
1455 pIoCtx->Req.Discard.cbDiscardLeft = 0;
1456 pIoCtx->Req.Discard.offCur = 0;
1457 pIoCtx->Req.Discard.cbThisDiscard = 0;
1458
1459 pIoCtx->pIoCtxParent = NULL;
1460 pIoCtx->Type.Root.pfnComplete = pfnComplete;
1461 pIoCtx->Type.Root.pvUser1 = pvUser1;
1462 pIoCtx->Type.Root.pvUser2 = pvUser2;
1463 }
1464
1465 LogFlow(("Allocated discard I/O context %#p\n", pIoCtx));
1466 return pIoCtx;
1467}
1468
1469DECLINLINE(PVDIOCTX) vdIoCtxChildAlloc(PVBOXHDD pDisk, VDIOCTXTXDIR enmTxDir,
1470 uint64_t uOffset, size_t cbTransfer,
1471 PVDIMAGE pImageStart, PCRTSGBUF pcSgBuf,
1472 PVDIOCTX pIoCtxParent, size_t cbTransferParent,
1473 size_t cbWriteParent, void *pvAllocation,
1474 PFNVDIOCTXTRANSFER pfnIoCtxTransfer)
1475{
1476 PVDIOCTX pIoCtx = vdIoCtxAlloc(pDisk, enmTxDir, uOffset, cbTransfer, pImageStart,
1477 pcSgBuf, pvAllocation, pfnIoCtxTransfer);
1478
1479 AssertPtr(pIoCtxParent);
1480 Assert(!pIoCtxParent->pIoCtxParent);
1481
1482 if (RT_LIKELY(pIoCtx))
1483 {
1484 pIoCtx->pIoCtxParent = pIoCtxParent;
1485 pIoCtx->Type.Child.uOffsetSaved = uOffset;
1486 pIoCtx->Type.Child.cbTransferLeftSaved = cbTransfer;
1487 pIoCtx->Type.Child.cbTransferParent = cbTransferParent;
1488 pIoCtx->Type.Child.cbWriteParent = cbWriteParent;
1489 }
1490
1491 LogFlow(("Allocated child I/O context %#p\n", pIoCtx));
1492 return pIoCtx;
1493}
1494
1495DECLINLINE(PVDIOTASK) vdIoTaskUserAlloc(PVDIOSTORAGE pIoStorage, PFNVDXFERCOMPLETED pfnComplete, void *pvUser, PVDIOCTX pIoCtx, uint32_t cbTransfer)
1496{
1497 PVDIOTASK pIoTask = NULL;
1498
1499 pIoTask = (PVDIOTASK)RTMemCacheAlloc(pIoStorage->pVDIo->pDisk->hMemCacheIoTask);
1500 if (pIoTask)
1501 {
1502 pIoTask->pIoStorage = pIoStorage;
1503 pIoTask->pfnComplete = pfnComplete;
1504 pIoTask->pvUser = pvUser;
1505 pIoTask->fMeta = false;
1506 pIoTask->Type.User.cbTransfer = cbTransfer;
1507 pIoTask->Type.User.pIoCtx = pIoCtx;
1508 }
1509
1510 return pIoTask;
1511}
1512
1513DECLINLINE(PVDIOTASK) vdIoTaskMetaAlloc(PVDIOSTORAGE pIoStorage, PFNVDXFERCOMPLETED pfnComplete, void *pvUser, PVDMETAXFER pMetaXfer)
1514{
1515 PVDIOTASK pIoTask = NULL;
1516
1517 pIoTask = (PVDIOTASK)RTMemCacheAlloc(pIoStorage->pVDIo->pDisk->hMemCacheIoTask);
1518 if (pIoTask)
1519 {
1520 pIoTask->pIoStorage = pIoStorage;
1521 pIoTask->pfnComplete = pfnComplete;
1522 pIoTask->pvUser = pvUser;
1523 pIoTask->fMeta = true;
1524 pIoTask->Type.Meta.pMetaXfer = pMetaXfer;
1525 }
1526
1527 return pIoTask;
1528}
1529
1530DECLINLINE(void) vdIoCtxFree(PVBOXHDD pDisk, PVDIOCTX pIoCtx)
1531{
1532 LogFlow(("Freeing I/O context %#p\n", pIoCtx));
1533 if (pIoCtx->pvAllocation)
1534 RTMemFree(pIoCtx->pvAllocation);
1535#ifdef DEBUG
1536 memset(pIoCtx, 0xff, sizeof(VDIOCTX));
1537#endif
1538 RTMemCacheFree(pDisk->hMemCacheIoCtx, pIoCtx);
1539}
1540
1541DECLINLINE(void) vdIoTaskFree(PVBOXHDD pDisk, PVDIOTASK pIoTask)
1542{
1543 RTMemCacheFree(pDisk->hMemCacheIoTask, pIoTask);
1544}
1545
1546DECLINLINE(void) vdIoCtxChildReset(PVDIOCTX pIoCtx)
1547{
1548 AssertPtr(pIoCtx->pIoCtxParent);
1549
1550 RTSgBufReset(&pIoCtx->Req.Io.SgBuf);
1551 pIoCtx->Req.Io.uOffset = pIoCtx->Type.Child.uOffsetSaved;
1552 pIoCtx->Req.Io.cbTransferLeft = pIoCtx->Type.Child.cbTransferLeftSaved;
1553}
1554
1555DECLINLINE(PVDMETAXFER) vdMetaXferAlloc(PVDIOSTORAGE pIoStorage, uint64_t uOffset, size_t cb)
1556{
1557 PVDMETAXFER pMetaXfer = (PVDMETAXFER)RTMemAlloc(RT_OFFSETOF(VDMETAXFER, abData[cb]));
1558
1559 if (RT_LIKELY(pMetaXfer))
1560 {
1561 pMetaXfer->Core.Key = uOffset;
1562 pMetaXfer->Core.KeyLast = uOffset + cb - 1;
1563 pMetaXfer->fFlags = VDMETAXFER_TXDIR_NONE;
1564 pMetaXfer->cbMeta = cb;
1565 pMetaXfer->pIoStorage = pIoStorage;
1566 pMetaXfer->cRefs = 0;
1567 RTListInit(&pMetaXfer->ListIoCtxWaiting);
1568 }
1569 return pMetaXfer;
1570}
1571
1572DECLINLINE(int) vdIoCtxDefer(PVBOXHDD pDisk, PVDIOCTX pIoCtx)
1573{
1574 PVDIOCTXDEFERRED pDeferred = (PVDIOCTXDEFERRED)RTMemAllocZ(sizeof(VDIOCTXDEFERRED));
1575
1576 if (!pDeferred)
1577 return VERR_NO_MEMORY;
1578
1579 LogFlowFunc(("Deferring write pIoCtx=%#p\n", pIoCtx));
1580
1581 Assert(!pIoCtx->pIoCtxParent && !pIoCtx->fBlocked);
1582
1583 RTListInit(&pDeferred->NodeDeferred);
1584 pDeferred->pIoCtx = pIoCtx;
1585 RTListAppend(&pDisk->ListWriteLocked, &pDeferred->NodeDeferred);
1586 pIoCtx->fBlocked = true;
1587 return VINF_SUCCESS;
1588}
1589
1590static size_t vdIoCtxCopy(PVDIOCTX pIoCtxDst, PVDIOCTX pIoCtxSrc, size_t cbData)
1591{
1592 return RTSgBufCopy(&pIoCtxDst->Req.Io.SgBuf, &pIoCtxSrc->Req.Io.SgBuf, cbData);
1593}
1594
1595static int vdIoCtxCmp(PVDIOCTX pIoCtx1, PVDIOCTX pIoCtx2, size_t cbData)
1596{
1597 return RTSgBufCmp(&pIoCtx1->Req.Io.SgBuf, &pIoCtx2->Req.Io.SgBuf, cbData);
1598}
1599
1600static size_t vdIoCtxCopyTo(PVDIOCTX pIoCtx, uint8_t *pbData, size_t cbData)
1601{
1602 return RTSgBufCopyToBuf(&pIoCtx->Req.Io.SgBuf, pbData, cbData);
1603}
1604
1605
1606static size_t vdIoCtxCopyFrom(PVDIOCTX pIoCtx, uint8_t *pbData, size_t cbData)
1607{
1608 return RTSgBufCopyFromBuf(&pIoCtx->Req.Io.SgBuf, pbData, cbData);
1609}
1610
1611static size_t vdIoCtxSet(PVDIOCTX pIoCtx, uint8_t ch, size_t cbData)
1612{
1613 return RTSgBufSet(&pIoCtx->Req.Io.SgBuf, ch, cbData);
1614}
1615
1616/**
1617 * Process the I/O context, core method which assumes that the critsect is acquired
1618 * by the calling thread.
1619 *
1620 * @returns VBox status code.
1621 * @param pIoCtx I/O context to process.
1622 */
1623static int vdIoCtxProcessLocked(PVDIOCTX pIoCtx)
1624{
1625 int rc = VINF_SUCCESS;
1626
1627 VD_THREAD_IS_CRITSECT_OWNER(pIoCtx->pDisk);
1628
1629 LogFlowFunc(("pIoCtx=%#p\n", pIoCtx));
1630
1631 if ( !pIoCtx->cMetaTransfersPending
1632 && !pIoCtx->cDataTransfersPending
1633 && !pIoCtx->pfnIoCtxTransfer)
1634 {
1635 rc = VINF_VD_ASYNC_IO_FINISHED;
1636 goto out;
1637 }
1638
1639 /*
1640 * We complete the I/O context in case of an error
1641 * if there is no I/O task pending.
1642 */
1643 if ( RT_FAILURE(pIoCtx->rcReq)
1644 && !pIoCtx->cMetaTransfersPending
1645 && !pIoCtx->cDataTransfersPending)
1646 {
1647 rc = VINF_VD_ASYNC_IO_FINISHED;
1648 goto out;
1649 }
1650
1651 /* Don't change anything if there is a metadata transfer pending or we are blocked. */
1652 if ( pIoCtx->cMetaTransfersPending
1653 || pIoCtx->fBlocked)
1654 {
1655 rc = VERR_VD_ASYNC_IO_IN_PROGRESS;
1656 goto out;
1657 }
1658
1659 if (pIoCtx->pfnIoCtxTransfer)
1660 {
1661 /* Call the transfer function advancing to the next while there is no error. */
1662 while ( pIoCtx->pfnIoCtxTransfer
1663 && !pIoCtx->cMetaTransfersPending
1664 && RT_SUCCESS(rc))
1665 {
1666 LogFlowFunc(("calling transfer function %#p\n", pIoCtx->pfnIoCtxTransfer));
1667 rc = pIoCtx->pfnIoCtxTransfer(pIoCtx);
1668
1669 /* Advance to the next part of the transfer if the current one succeeded. */
1670 if (RT_SUCCESS(rc))
1671 {
1672 pIoCtx->pfnIoCtxTransfer = pIoCtx->pfnIoCtxTransferNext;
1673 pIoCtx->pfnIoCtxTransferNext = NULL;
1674 }
1675 }
1676 }
1677
1678 if ( RT_SUCCESS(rc)
1679 && !pIoCtx->cMetaTransfersPending
1680 && !pIoCtx->cDataTransfersPending)
1681 rc = VINF_VD_ASYNC_IO_FINISHED;
1682 else if ( RT_SUCCESS(rc)
1683 || rc == VERR_VD_NOT_ENOUGH_METADATA
1684 || rc == VERR_VD_IOCTX_HALT)
1685 rc = VERR_VD_ASYNC_IO_IN_PROGRESS;
1686 else if (RT_FAILURE(rc) && (rc != VERR_VD_ASYNC_IO_IN_PROGRESS))
1687 {
1688 ASMAtomicCmpXchgS32(&pIoCtx->rcReq, rc, VINF_SUCCESS);
1689 /*
1690 * The I/O context completed if we have an error and there is no data
1691 * or meta data transfer pending.
1692 */
1693 if ( !pIoCtx->cMetaTransfersPending
1694 && !pIoCtx->cDataTransfersPending)
1695 rc = VINF_VD_ASYNC_IO_FINISHED;
1696 else
1697 rc = VERR_VD_ASYNC_IO_IN_PROGRESS;
1698 }
1699
1700out:
1701 LogFlowFunc(("pIoCtx=%#p rc=%Rrc cDataTransfersPending=%u cMetaTransfersPending=%u fComplete=%RTbool\n",
1702 pIoCtx, rc, pIoCtx->cDataTransfersPending, pIoCtx->cMetaTransfersPending,
1703 pIoCtx->fComplete));
1704
1705 return rc;
1706}
1707
1708/**
1709 * Processes the list of waiting I/O contexts.
1710 *
1711 * @returns VBox status code.
1712 * @param pDisk The disk structure.
1713 * @param pIoCtxRc An I/O context handle which waits on the list. When processed
1714 * The status code is returned. NULL if there is no I/O context
1715 * to return the status code for.
1716 */
1717static int vdDiskProcessWaitingIoCtx(PVBOXHDD pDisk, PVDIOCTX pIoCtxRc)
1718{
1719 int rc = VINF_SUCCESS;
1720
1721 LogFlowFunc(("pDisk=%#p pIoCtxRc=%#p\n", pDisk, pIoCtxRc));
1722
1723 VD_THREAD_IS_CRITSECT_OWNER(pDisk);
1724
1725 /* Get the waiting list and process it in FIFO order. */
1726 PVDIOCTX pIoCtxHead = ASMAtomicXchgPtrT(&pDisk->pIoCtxHead, NULL, PVDIOCTX);
1727
1728 /* Reverse it. */
1729 PVDIOCTX pCur = pIoCtxHead;
1730 pIoCtxHead = NULL;
1731 while (pCur)
1732 {
1733 PVDIOCTX pInsert = pCur;
1734 pCur = pCur->pIoCtxNext;
1735 pInsert->pIoCtxNext = pIoCtxHead;
1736 pIoCtxHead = pInsert;
1737 }
1738
1739 /* Process now. */
1740 pCur = pIoCtxHead;
1741 while (pCur)
1742 {
1743 int rcTmp;
1744 PVDIOCTX pTmp = pCur;
1745
1746 pCur = pCur->pIoCtxNext;
1747 pTmp->pIoCtxNext = NULL;
1748
1749 rcTmp = vdIoCtxProcessLocked(pTmp);
1750 if (pTmp == pIoCtxRc)
1751 {
1752 /* The given I/O context was processed, pass the return code to the caller. */
1753 rc = rcTmp;
1754 }
1755 else if ( rcTmp == VINF_VD_ASYNC_IO_FINISHED
1756 && ASMAtomicCmpXchgBool(&pTmp->fComplete, true, false))
1757 {
1758 LogFlowFunc(("Waiting I/O context completed pTmp=%#p\n", pTmp));
1759 vdThreadFinishWrite(pDisk);
1760 pTmp->Type.Root.pfnComplete(pTmp->Type.Root.pvUser1,
1761 pTmp->Type.Root.pvUser2,
1762 pTmp->rcReq);
1763 vdIoCtxFree(pDisk, pTmp);
1764 }
1765 }
1766
1767 LogFlowFunc(("returns rc=%Rrc\n", rc));
1768 return rc;
1769}
1770
1771/**
1772 * Leaves the critical section of the disk processing waiting I/O contexts.
1773 *
1774 * @returns VBox status code.
1775 * @param pDisk The disk to unlock.
1776 * @param pIoCtxRc An I/O context handle which waits on the list. When processed
1777 * The status code is returned. NULL if there is no I/O context
1778 * to return the status code for.
1779 */
1780static int vdDiskCritSectLeave(PVBOXHDD pDisk, PVDIOCTX pIoCtxRc)
1781{
1782 int rc = VINF_SUCCESS;
1783
1784 LogFlowFunc(("pDisk=%#p pIoCtxRc=%#p\n", pDisk, pIoCtxRc));
1785
1786 VD_THREAD_IS_CRITSECT_OWNER(pDisk);
1787
1788 rc = vdDiskProcessWaitingIoCtx(pDisk, pIoCtxRc);
1789 RTCritSectLeave(&pDisk->CritSect);
1790
1791 /*
1792 * We have to check for new waiting contexts here. It is possible that
1793 * another thread has queued another one while process waiting contexts
1794 * and because we still held the lock it was appended to the waiting list.
1795 *
1796 * @note Don't overwrite rc here because this might result in loosing
1797 * the status code of the given I/O context.
1798 */
1799 while (ASMAtomicReadPtrT(&pDisk->pIoCtxHead, PVDIOCTX) != NULL)
1800 {
1801 int rc2 = RTCritSectTryEnter(&pDisk->CritSect);
1802
1803 if (RT_SUCCESS(rc2))
1804 {
1805 /*
1806 * Don't pass status codes for any I/O context here. The context must hae been
1807 * in the first run.
1808 */
1809 vdDiskProcessWaitingIoCtx(pDisk, NULL);
1810 RTCritSectLeave(&pDisk->CritSect);
1811 }
1812 else
1813 {
1814 /*
1815 * Another thread is holding the lock already and will process the list
1816 * whewn leaving the lock, nothing left to do for us.
1817 */
1818 Assert(rc2 == VERR_SEM_BUSY);
1819 break;
1820 }
1821 }
1822
1823 LogFlowFunc(("returns rc=%Rrc\n", rc));
1824 return rc;
1825}
1826
1827/**
1828 * Processes the I/O context trying to lock the criticial section.
1829 * The context is deferred if the critical section is busy.
1830 *
1831 * @returns VBox status code.
1832 * @param pIoCtx The I/O context to process.
1833 */
1834static int vdIoCtxProcessTryLockDefer(PVDIOCTX pIoCtx)
1835{
1836 int rc = VINF_SUCCESS;
1837 PVBOXHDD pDisk = pIoCtx->pDisk;
1838
1839 LogFlowFunc(("pIoCtx=%#p\n", pIoCtx));
1840
1841 /* Put it on the waiting list first. */
1842 PVDIOCTX pNext = ASMAtomicUoReadPtrT(&pDisk->pIoCtxHead, PVDIOCTX);
1843 PVDIOCTX pHeadOld;
1844 pIoCtx->pIoCtxNext = pNext;
1845 while (!ASMAtomicCmpXchgExPtr(&pDisk->pIoCtxHead, pIoCtx, pNext, &pHeadOld))
1846 {
1847 pNext = pHeadOld;
1848 Assert(pNext != pIoCtx);
1849 pIoCtx->pIoCtxNext = pNext;
1850 ASMNopPause();
1851 }
1852
1853 rc = RTCritSectTryEnter(&pDisk->CritSect);
1854 if (RT_SUCCESS(rc))
1855 {
1856 /* Leave it again, the context will be processed just before leaving the lock. */
1857 LogFlowFunc(("Successfully acquired the critical section\n"));
1858 rc = vdDiskCritSectLeave(pDisk, pIoCtx);
1859 }
1860 else
1861 {
1862 AssertMsg(rc == VERR_SEM_BUSY, ("Invalid return code %Rrc\n", rc));
1863 LogFlowFunc(("Critical section is busy\n"));
1864 rc = VERR_VD_ASYNC_IO_IN_PROGRESS;
1865 }
1866
1867 return rc;
1868}
1869
1870/**
1871 * Wrapper for vdIoCtxProcessLocked() which acquires the lock before.
1872 *
1873 * @returns VBox status code.
1874 * @param pIoCtx I/O context to process.
1875 */
1876static int vdIoCtxProcess(PVDIOCTX pIoCtx)
1877{
1878 int rc = VINF_SUCCESS;
1879 PVBOXHDD pDisk = pIoCtx->pDisk;
1880
1881 LogFlowFunc(("pIoCtx=%#p\n", pIoCtx));
1882
1883 RTCritSectEnter(&pDisk->CritSect);
1884 rc = vdIoCtxProcessLocked(pIoCtx);
1885 vdDiskCritSectLeave(pDisk, NULL);
1886
1887 return rc;
1888}
1889
1890DECLINLINE(bool) vdIoCtxIsDiskLockOwner(PVBOXHDD pDisk, PVDIOCTX pIoCtx)
1891{
1892 return pDisk->fLocked
1893 && pDisk->pIoCtxLockOwner == pIoCtx;
1894}
1895
1896static int vdIoCtxLockDisk(PVBOXHDD pDisk, PVDIOCTX pIoCtx)
1897{
1898 int rc = VINF_SUCCESS;
1899
1900 LogFlowFunc(("pDisk=%#p pIoCtx=%#p\n", pDisk, pIoCtx));
1901
1902 if (!ASMAtomicCmpXchgBool(&pDisk->fLocked, true, false))
1903 {
1904 Assert(pDisk->pIoCtxLockOwner != pIoCtx); /* No nesting allowed. */
1905
1906 rc = vdIoCtxDefer(pDisk, pIoCtx);
1907 if (RT_SUCCESS(rc))
1908 rc = VERR_VD_ASYNC_IO_IN_PROGRESS;
1909 }
1910 else
1911 {
1912 Assert(!pDisk->pIoCtxLockOwner);
1913 pDisk->pIoCtxLockOwner = pIoCtx;
1914 }
1915
1916 LogFlowFunc(("returns -> %Rrc\n", rc));
1917 return rc;
1918}
1919
1920static void vdIoCtxUnlockDisk(PVBOXHDD pDisk, PVDIOCTX pIoCtx, bool fProcessDeferredReqs)
1921{
1922 LogFlowFunc(("pDisk=%#p pIoCtx=%#p fProcessDeferredReqs=%RTbool\n",
1923 pDisk, pIoCtx, fProcessDeferredReqs));
1924
1925 LogFlow(("Unlocking disk lock owner is %#p\n", pDisk->pIoCtxLockOwner));
1926 Assert(pDisk->fLocked);
1927 Assert(pDisk->pIoCtxLockOwner == pIoCtx);
1928 pDisk->pIoCtxLockOwner = NULL;
1929 ASMAtomicXchgBool(&pDisk->fLocked, false);
1930
1931 if (fProcessDeferredReqs)
1932 {
1933 /* Process any pending writes if the current request didn't caused another growing. */
1934 RTCritSectEnter(&pDisk->CritSect);
1935
1936 if (!RTListIsEmpty(&pDisk->ListWriteLocked))
1937 {
1938 RTLISTNODE ListTmp;
1939
1940 RTListMove(&ListTmp, &pDisk->ListWriteLocked);
1941 vdDiskCritSectLeave(pDisk, NULL);
1942
1943 /* Process the list. */
1944 do
1945 {
1946 int rc;
1947 PVDIOCTXDEFERRED pDeferred = RTListGetFirst(&ListTmp, VDIOCTXDEFERRED, NodeDeferred);
1948 PVDIOCTX pIoCtxWait = pDeferred->pIoCtx;
1949
1950 AssertPtr(pIoCtxWait);
1951
1952 RTListNodeRemove(&pDeferred->NodeDeferred);
1953 RTMemFree(pDeferred);
1954
1955 Assert(!pIoCtxWait->pIoCtxParent);
1956
1957 pIoCtxWait->fBlocked = false;
1958 LogFlowFunc(("Processing waiting I/O context pIoCtxWait=%#p\n", pIoCtxWait));
1959
1960 rc = vdIoCtxProcess(pIoCtxWait);
1961 if ( rc == VINF_VD_ASYNC_IO_FINISHED
1962 && ASMAtomicCmpXchgBool(&pIoCtxWait->fComplete, true, false))
1963 {
1964 LogFlowFunc(("Waiting I/O context completed pIoCtxWait=%#p\n", pIoCtxWait));
1965 vdThreadFinishWrite(pDisk);
1966 pIoCtxWait->Type.Root.pfnComplete(pIoCtxWait->Type.Root.pvUser1,
1967 pIoCtxWait->Type.Root.pvUser2,
1968 pIoCtxWait->rcReq);
1969 vdIoCtxFree(pDisk, pIoCtxWait);
1970 }
1971 } while (!RTListIsEmpty(&ListTmp));
1972 }
1973 else
1974 vdDiskCritSectLeave(pDisk, NULL);
1975 }
1976
1977 LogFlowFunc(("returns\n"));
1978}
1979
1980/**
1981 * internal: read the specified amount of data in whatever blocks the backend
1982 * will give us - async version.
1983 */
1984static int vdReadHelperAsync(PVDIOCTX pIoCtx)
1985{
1986 int rc;
1987 size_t cbToRead = pIoCtx->Req.Io.cbTransfer;
1988 uint64_t uOffset = pIoCtx->Req.Io.uOffset;
1989 PVDIMAGE pCurrImage = pIoCtx->Req.Io.pImageCur;;
1990 size_t cbThisRead;
1991
1992 /* Loop until all reads started or we have a backend which needs to read metadata. */
1993 do
1994 {
1995 /* Search for image with allocated block. Do not attempt to read more
1996 * than the previous reads marked as valid. Otherwise this would return
1997 * stale data when different block sizes are used for the images. */
1998 cbThisRead = cbToRead;
1999
2000 /*
2001 * Try to read from the given image.
2002 * If the block is not allocated read from override chain if present.
2003 */
2004 rc = pCurrImage->Backend->pfnAsyncRead(pCurrImage->pBackendData,
2005 uOffset, cbThisRead,
2006 pIoCtx, &cbThisRead);
2007
2008 if (rc == VERR_VD_BLOCK_FREE)
2009 {
2010 while ( pCurrImage->pPrev != NULL
2011 && rc == VERR_VD_BLOCK_FREE)
2012 {
2013 pCurrImage = pCurrImage->pPrev;
2014 rc = pCurrImage->Backend->pfnAsyncRead(pCurrImage->pBackendData,
2015 uOffset, cbThisRead,
2016 pIoCtx, &cbThisRead);
2017 }
2018 }
2019
2020 /* The task state will be updated on success already, don't do it here!. */
2021 if (rc == VERR_VD_BLOCK_FREE)
2022 {
2023 /* No image in the chain contains the data for the block. */
2024 vdIoCtxSet(pIoCtx, '\0', cbThisRead);
2025 ASMAtomicSubU32(&pIoCtx->Req.Io.cbTransferLeft, cbThisRead);
2026 rc = VINF_SUCCESS;
2027 }
2028 else if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
2029 rc = VINF_SUCCESS;
2030 else if (rc == VERR_VD_IOCTX_HALT)
2031 {
2032 uOffset += cbThisRead;
2033 cbToRead -= cbThisRead;
2034 pIoCtx->fBlocked = true;
2035 }
2036
2037 if (RT_FAILURE(rc))
2038 break;
2039
2040 cbToRead -= cbThisRead;
2041 uOffset += cbThisRead;
2042 pCurrImage = pIoCtx->Req.Io.pImageStart; /* Start with the highest image in the chain. */
2043 } while (cbToRead != 0 && RT_SUCCESS(rc));
2044
2045 if ( rc == VERR_VD_NOT_ENOUGH_METADATA
2046 || rc == VERR_VD_IOCTX_HALT)
2047 {
2048 /* Save the current state. */
2049 pIoCtx->Req.Io.uOffset = uOffset;
2050 pIoCtx->Req.Io.cbTransfer = cbToRead;
2051 pIoCtx->Req.Io.pImageCur = pCurrImage ? pCurrImage : pIoCtx->Req.Io.pImageStart;
2052 }
2053
2054 return rc;
2055}
2056
2057/**
2058 * internal: parent image read wrapper for compacting.
2059 */
2060static int vdParentRead(void *pvUser, uint64_t uOffset, void *pvBuf,
2061 size_t cbRead)
2062{
2063 PVDPARENTSTATEDESC pParentState = (PVDPARENTSTATEDESC)pvUser;
2064 return vdReadHelper(pParentState->pDisk, pParentState->pImage, uOffset,
2065 pvBuf, cbRead, false /* fUpdateCache */);
2066}
2067
2068/**
2069 * internal: mark the disk as not modified.
2070 */
2071static void vdResetModifiedFlag(PVBOXHDD pDisk)
2072{
2073 if (pDisk->uModified & VD_IMAGE_MODIFIED_FLAG)
2074 {
2075 /* generate new last-modified uuid */
2076 if (!(pDisk->uModified & VD_IMAGE_MODIFIED_DISABLE_UUID_UPDATE))
2077 {
2078 RTUUID Uuid;
2079
2080 RTUuidCreate(&Uuid);
2081 pDisk->pLast->Backend->pfnSetModificationUuid(pDisk->pLast->pBackendData,
2082 &Uuid);
2083
2084 if (pDisk->pCache)
2085 pDisk->pCache->Backend->pfnSetModificationUuid(pDisk->pCache->pBackendData,
2086 &Uuid);
2087 }
2088
2089 pDisk->uModified &= ~VD_IMAGE_MODIFIED_FLAG;
2090 }
2091}
2092
2093/**
2094 * internal: mark the disk as modified.
2095 */
2096static void vdSetModifiedFlag(PVBOXHDD pDisk)
2097{
2098 pDisk->uModified |= VD_IMAGE_MODIFIED_FLAG;
2099 if (pDisk->uModified & VD_IMAGE_MODIFIED_FIRST)
2100 {
2101 pDisk->uModified &= ~VD_IMAGE_MODIFIED_FIRST;
2102
2103 /* First modify, so create a UUID and ensure it's written to disk. */
2104 vdResetModifiedFlag(pDisk);
2105
2106 if (!(pDisk->uModified & VD_IMAGE_MODIFIED_DISABLE_UUID_UPDATE))
2107 pDisk->pLast->Backend->pfnFlush(pDisk->pLast->pBackendData);
2108 }
2109}
2110
2111/**
2112 * internal: write a complete block (only used for diff images), taking the
2113 * remaining data from parent images. This implementation does not optimize
2114 * anything (except that it tries to read only that portions from parent
2115 * images that are really needed).
2116 */
2117static int vdWriteHelperStandard(PVBOXHDD pDisk, PVDIMAGE pImage,
2118 PVDIMAGE pImageParentOverride,
2119 uint64_t uOffset, size_t cbWrite,
2120 size_t cbThisWrite, size_t cbPreRead,
2121 size_t cbPostRead, const void *pvBuf,
2122 void *pvTmp)
2123{
2124 int rc = VINF_SUCCESS;
2125
2126 /* Read the data that goes before the write to fill the block. */
2127 if (cbPreRead)
2128 {
2129 /*
2130 * Updating the cache doesn't make sense here because
2131 * this will be done after the complete block was written.
2132 */
2133 rc = vdReadHelperEx(pDisk, pImage, pImageParentOverride,
2134 uOffset - cbPreRead, pvTmp, cbPreRead,
2135 true /* fZeroFreeBlocks*/,
2136 false /* fUpdateCache */, 0);
2137 if (RT_FAILURE(rc))
2138 return rc;
2139 }
2140
2141 /* Copy the data to the right place in the buffer. */
2142 memcpy((char *)pvTmp + cbPreRead, pvBuf, cbThisWrite);
2143
2144 /* Read the data that goes after the write to fill the block. */
2145 if (cbPostRead)
2146 {
2147 /* If we have data to be written, use that instead of reading
2148 * data from the image. */
2149 size_t cbWriteCopy;
2150 if (cbWrite > cbThisWrite)
2151 cbWriteCopy = RT_MIN(cbWrite - cbThisWrite, cbPostRead);
2152 else
2153 cbWriteCopy = 0;
2154 /* Figure out how much we cannot read from the image, because
2155 * the last block to write might exceed the nominal size of the
2156 * image for technical reasons. */
2157 size_t cbFill;
2158 if (uOffset + cbThisWrite + cbPostRead > pDisk->cbSize)
2159 cbFill = uOffset + cbThisWrite + cbPostRead - pDisk->cbSize;
2160 else
2161 cbFill = 0;
2162 /* The rest must be read from the image. */
2163 size_t cbReadImage = cbPostRead - cbWriteCopy - cbFill;
2164
2165 /* Now assemble the remaining data. */
2166 if (cbWriteCopy)
2167 memcpy((char *)pvTmp + cbPreRead + cbThisWrite,
2168 (char *)pvBuf + cbThisWrite, cbWriteCopy);
2169 if (cbReadImage)
2170 rc = vdReadHelperEx(pDisk, pImage, pImageParentOverride,
2171 uOffset + cbThisWrite + cbWriteCopy,
2172 (char *)pvTmp + cbPreRead + cbThisWrite + cbWriteCopy,
2173 cbReadImage, true /* fZeroFreeBlocks */,
2174 false /* fUpdateCache */, 0);
2175 if (RT_FAILURE(rc))
2176 return rc;
2177 /* Zero out the remainder of this block. Will never be visible, as this
2178 * is beyond the limit of the image. */
2179 if (cbFill)
2180 memset((char *)pvTmp + cbPreRead + cbThisWrite + cbWriteCopy + cbReadImage,
2181 '\0', cbFill);
2182 }
2183
2184 /* Write the full block to the virtual disk. */
2185 rc = pImage->Backend->pfnWrite(pImage->pBackendData,
2186 uOffset - cbPreRead, pvTmp,
2187 cbPreRead + cbThisWrite + cbPostRead,
2188 NULL, &cbPreRead, &cbPostRead, 0);
2189 Assert(rc != VERR_VD_BLOCK_FREE);
2190 Assert(cbPreRead == 0);
2191 Assert(cbPostRead == 0);
2192
2193 return rc;
2194}
2195
2196/**
2197 * internal: write a complete block (only used for diff images), taking the
2198 * remaining data from parent images. This implementation optimizes out writes
2199 * that do not change the data relative to the state as of the parent images.
2200 * All backends which support differential/growing images support this.
2201 */
2202static int vdWriteHelperOptimized(PVBOXHDD pDisk, PVDIMAGE pImage,
2203 PVDIMAGE pImageParentOverride,
2204 uint64_t uOffset, size_t cbWrite,
2205 size_t cbThisWrite, size_t cbPreRead,
2206 size_t cbPostRead, const void *pvBuf,
2207 void *pvTmp, unsigned cImagesRead)
2208{
2209 size_t cbFill = 0;
2210 size_t cbWriteCopy = 0;
2211 size_t cbReadImage = 0;
2212 int rc;
2213
2214 if (cbPostRead)
2215 {
2216 /* Figure out how much we cannot read from the image, because
2217 * the last block to write might exceed the nominal size of the
2218 * image for technical reasons. */
2219 if (uOffset + cbThisWrite + cbPostRead > pDisk->cbSize)
2220 cbFill = uOffset + cbThisWrite + cbPostRead - pDisk->cbSize;
2221
2222 /* If we have data to be written, use that instead of reading
2223 * data from the image. */
2224 if (cbWrite > cbThisWrite)
2225 cbWriteCopy = RT_MIN(cbWrite - cbThisWrite, cbPostRead);
2226
2227 /* The rest must be read from the image. */
2228 cbReadImage = cbPostRead - cbWriteCopy - cbFill;
2229 }
2230
2231 /* Read the entire data of the block so that we can compare whether it will
2232 * be modified by the write or not. */
2233 rc = vdReadHelperEx(pDisk, pImage, pImageParentOverride, uOffset - cbPreRead, pvTmp,
2234 cbPreRead + cbThisWrite + cbPostRead - cbFill,
2235 true /* fZeroFreeBlocks */, false /* fUpdateCache */,
2236 cImagesRead);
2237 if (RT_FAILURE(rc))
2238 return rc;
2239
2240 /* Check if the write would modify anything in this block. */
2241 if ( !memcmp((char *)pvTmp + cbPreRead, pvBuf, cbThisWrite)
2242 && (!cbWriteCopy || !memcmp((char *)pvTmp + cbPreRead + cbThisWrite,
2243 (char *)pvBuf + cbThisWrite, cbWriteCopy)))
2244 {
2245 /* Block is completely unchanged, so no need to write anything. */
2246 return VINF_SUCCESS;
2247 }
2248
2249 /* Copy the data to the right place in the buffer. */
2250 memcpy((char *)pvTmp + cbPreRead, pvBuf, cbThisWrite);
2251
2252 /* Handle the data that goes after the write to fill the block. */
2253 if (cbPostRead)
2254 {
2255 /* Now assemble the remaining data. */
2256 if (cbWriteCopy)
2257 memcpy((char *)pvTmp + cbPreRead + cbThisWrite,
2258 (char *)pvBuf + cbThisWrite, cbWriteCopy);
2259 /* Zero out the remainder of this block. Will never be visible, as this
2260 * is beyond the limit of the image. */
2261 if (cbFill)
2262 memset((char *)pvTmp + cbPreRead + cbThisWrite + cbWriteCopy + cbReadImage,
2263 '\0', cbFill);
2264 }
2265
2266 /* Write the full block to the virtual disk. */
2267 rc = pImage->Backend->pfnWrite(pImage->pBackendData,
2268 uOffset - cbPreRead, pvTmp,
2269 cbPreRead + cbThisWrite + cbPostRead,
2270 NULL, &cbPreRead, &cbPostRead, 0);
2271 Assert(rc != VERR_VD_BLOCK_FREE);
2272 Assert(cbPreRead == 0);
2273 Assert(cbPostRead == 0);
2274
2275 return rc;
2276}
2277
2278/**
2279 * internal: write buffer to the image, taking care of block boundaries and
2280 * write optimizations.
2281 */
2282static int vdWriteHelperEx(PVBOXHDD pDisk, PVDIMAGE pImage,
2283 PVDIMAGE pImageParentOverride, uint64_t uOffset,
2284 const void *pvBuf, size_t cbWrite,
2285 bool fUpdateCache, unsigned cImagesRead)
2286{
2287 int rc;
2288 unsigned fWrite;
2289 size_t cbThisWrite;
2290 size_t cbPreRead, cbPostRead;
2291 uint64_t uOffsetCur = uOffset;
2292 size_t cbWriteCur = cbWrite;
2293 const void *pcvBufCur = pvBuf;
2294
2295 /* Loop until all written. */
2296 do
2297 {
2298 /* Try to write the possibly partial block to the last opened image.
2299 * This works when the block is already allocated in this image or
2300 * if it is a full-block write (and allocation isn't suppressed below).
2301 * For image formats which don't support zero blocks, it's beneficial
2302 * to avoid unnecessarily allocating unchanged blocks. This prevents
2303 * unwanted expanding of images. VMDK is an example. */
2304 cbThisWrite = cbWriteCur;
2305 fWrite = (pImage->uOpenFlags & VD_OPEN_FLAGS_HONOR_SAME)
2306 ? 0 : VD_WRITE_NO_ALLOC;
2307 rc = pImage->Backend->pfnWrite(pImage->pBackendData, uOffsetCur, pcvBufCur,
2308 cbThisWrite, &cbThisWrite, &cbPreRead,
2309 &cbPostRead, fWrite);
2310 if (rc == VERR_VD_BLOCK_FREE)
2311 {
2312 void *pvTmp = RTMemTmpAlloc(cbPreRead + cbThisWrite + cbPostRead);
2313 AssertBreakStmt(VALID_PTR(pvTmp), rc = VERR_NO_MEMORY);
2314
2315 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_HONOR_SAME))
2316 {
2317 /* Optimized write, suppress writing to a so far unallocated
2318 * block if the data is in fact not changed. */
2319 rc = vdWriteHelperOptimized(pDisk, pImage, pImageParentOverride,
2320 uOffsetCur, cbWriteCur,
2321 cbThisWrite, cbPreRead, cbPostRead,
2322 pcvBufCur, pvTmp, cImagesRead);
2323 }
2324 else
2325 {
2326 /* Normal write, not optimized in any way. The block will
2327 * be written no matter what. This will usually (unless the
2328 * backend has some further optimization enabled) cause the
2329 * block to be allocated. */
2330 rc = vdWriteHelperStandard(pDisk, pImage, pImageParentOverride,
2331 uOffsetCur, cbWriteCur,
2332 cbThisWrite, cbPreRead, cbPostRead,
2333 pcvBufCur, pvTmp);
2334 }
2335 RTMemTmpFree(pvTmp);
2336 if (RT_FAILURE(rc))
2337 break;
2338 }
2339
2340 cbWriteCur -= cbThisWrite;
2341 uOffsetCur += cbThisWrite;
2342 pcvBufCur = (char *)pcvBufCur + cbThisWrite;
2343 } while (cbWriteCur != 0 && RT_SUCCESS(rc));
2344
2345 /* Update the cache on success */
2346 if ( RT_SUCCESS(rc)
2347 && pDisk->pCache
2348 && fUpdateCache)
2349 rc = vdCacheWriteHelper(pDisk->pCache, uOffset, pvBuf, cbWrite, NULL);
2350
2351 if (RT_SUCCESS(rc))
2352 rc = vdDiscardSetRangeAllocated(pDisk, uOffset, cbWrite);
2353
2354 return rc;
2355}
2356
2357/**
2358 * internal: write buffer to the image, taking care of block boundaries and
2359 * write optimizations.
2360 */
2361static int vdWriteHelper(PVBOXHDD pDisk, PVDIMAGE pImage, uint64_t uOffset,
2362 const void *pvBuf, size_t cbWrite, bool fUpdateCache)
2363{
2364 return vdWriteHelperEx(pDisk, pImage, NULL, uOffset, pvBuf, cbWrite,
2365 fUpdateCache, 0);
2366}
2367
2368/**
2369 * Internal: Copies the content of one disk to another one applying optimizations
2370 * to speed up the copy process if possible.
2371 */
2372static int vdCopyHelper(PVBOXHDD pDiskFrom, PVDIMAGE pImageFrom, PVBOXHDD pDiskTo,
2373 uint64_t cbSize, unsigned cImagesFromRead, unsigned cImagesToRead,
2374 bool fSuppressRedundantIo, PVDINTERFACEPROGRESS pIfProgress,
2375 PVDINTERFACEPROGRESS pDstIfProgress)
2376{
2377 int rc = VINF_SUCCESS;
2378 int rc2;
2379 uint64_t uOffset = 0;
2380 uint64_t cbRemaining = cbSize;
2381 void *pvBuf = NULL;
2382 bool fLockReadFrom = false;
2383 bool fLockWriteTo = false;
2384 bool fBlockwiseCopy = fSuppressRedundantIo || (cImagesFromRead > 0);
2385 unsigned uProgressOld = 0;
2386
2387 LogFlowFunc(("pDiskFrom=%#p pImageFrom=%#p pDiskTo=%#p cbSize=%llu cImagesFromRead=%u cImagesToRead=%u fSuppressRedundantIo=%RTbool pIfProgress=%#p pDstIfProgress=%#p\n",
2388 pDiskFrom, pImageFrom, pDiskTo, cbSize, cImagesFromRead, cImagesToRead, fSuppressRedundantIo, pDstIfProgress, pDstIfProgress));
2389
2390 /* Allocate tmp buffer. */
2391 pvBuf = RTMemTmpAlloc(VD_MERGE_BUFFER_SIZE);
2392 if (!pvBuf)
2393 return rc;
2394
2395 do
2396 {
2397 size_t cbThisRead = RT_MIN(VD_MERGE_BUFFER_SIZE, cbRemaining);
2398
2399 /* Note that we don't attempt to synchronize cross-disk accesses.
2400 * It wouldn't be very difficult to do, just the lock order would
2401 * need to be defined somehow to prevent deadlocks. Postpone such
2402 * magic as there is no use case for this. */
2403
2404 rc2 = vdThreadStartRead(pDiskFrom);
2405 AssertRC(rc2);
2406 fLockReadFrom = true;
2407
2408 if (fBlockwiseCopy)
2409 {
2410 /* Read the source data. */
2411 rc = pImageFrom->Backend->pfnRead(pImageFrom->pBackendData,
2412 uOffset, pvBuf, cbThisRead,
2413 &cbThisRead);
2414
2415 if ( rc == VERR_VD_BLOCK_FREE
2416 && cImagesFromRead != 1)
2417 {
2418 unsigned cImagesToProcess = cImagesFromRead;
2419
2420 for (PVDIMAGE pCurrImage = pImageFrom->pPrev;
2421 pCurrImage != NULL && rc == VERR_VD_BLOCK_FREE;
2422 pCurrImage = pCurrImage->pPrev)
2423 {
2424 rc = pCurrImage->Backend->pfnRead(pCurrImage->pBackendData,
2425 uOffset, pvBuf, cbThisRead,
2426 &cbThisRead);
2427 if (cImagesToProcess == 1)
2428 break;
2429 else if (cImagesToProcess > 0)
2430 cImagesToProcess--;
2431 }
2432 }
2433 }
2434 else
2435 rc = vdReadHelper(pDiskFrom, pImageFrom, uOffset, pvBuf, cbThisRead,
2436 false /* fUpdateCache */);
2437
2438 if (RT_FAILURE(rc) && rc != VERR_VD_BLOCK_FREE)
2439 break;
2440
2441 rc2 = vdThreadFinishRead(pDiskFrom);
2442 AssertRC(rc2);
2443 fLockReadFrom = false;
2444
2445 if (rc != VERR_VD_BLOCK_FREE)
2446 {
2447 rc2 = vdThreadStartWrite(pDiskTo);
2448 AssertRC(rc2);
2449 fLockWriteTo = true;
2450
2451 /* Only do collapsed I/O if we are copying the data blockwise. */
2452 rc = vdWriteHelperEx(pDiskTo, pDiskTo->pLast, NULL, uOffset, pvBuf,
2453 cbThisRead, false /* fUpdateCache */,
2454 fBlockwiseCopy ? cImagesToRead : 0);
2455 if (RT_FAILURE(rc))
2456 break;
2457
2458 rc2 = vdThreadFinishWrite(pDiskTo);
2459 AssertRC(rc2);
2460 fLockWriteTo = false;
2461 }
2462 else /* Don't propagate the error to the outside */
2463 rc = VINF_SUCCESS;
2464
2465 uOffset += cbThisRead;
2466 cbRemaining -= cbThisRead;
2467
2468 unsigned uProgressNew = uOffset * 99 / cbSize;
2469 if (uProgressNew != uProgressOld)
2470 {
2471 uProgressOld = uProgressNew;
2472
2473 if (pIfProgress && pIfProgress->pfnProgress)
2474 {
2475 rc = pIfProgress->pfnProgress(pIfProgress->Core.pvUser,
2476 uProgressOld);
2477 if (RT_FAILURE(rc))
2478 break;
2479 }
2480 if (pDstIfProgress && pDstIfProgress->pfnProgress)
2481 {
2482 rc = pDstIfProgress->pfnProgress(pDstIfProgress->Core.pvUser,
2483 uProgressOld);
2484 if (RT_FAILURE(rc))
2485 break;
2486 }
2487 }
2488 } while (uOffset < cbSize);
2489
2490 RTMemFree(pvBuf);
2491
2492 if (fLockReadFrom)
2493 {
2494 rc2 = vdThreadFinishRead(pDiskFrom);
2495 AssertRC(rc2);
2496 }
2497
2498 if (fLockWriteTo)
2499 {
2500 rc2 = vdThreadFinishWrite(pDiskTo);
2501 AssertRC(rc2);
2502 }
2503
2504 LogFlowFunc(("returns rc=%Rrc\n", rc));
2505 return rc;
2506}
2507
2508/**
2509 * Flush helper async version.
2510 */
2511static int vdSetModifiedHelperAsync(PVDIOCTX pIoCtx)
2512{
2513 int rc = VINF_SUCCESS;
2514 PVBOXHDD pDisk = pIoCtx->pDisk;
2515 PVDIMAGE pImage = pIoCtx->Req.Io.pImageCur;
2516
2517 rc = pImage->Backend->pfnAsyncFlush(pImage->pBackendData, pIoCtx);
2518 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
2519 rc = VINF_SUCCESS;
2520
2521 return rc;
2522}
2523
2524/**
2525 * internal: mark the disk as modified - async version.
2526 */
2527static int vdSetModifiedFlagAsync(PVBOXHDD pDisk, PVDIOCTX pIoCtx)
2528{
2529 int rc = VINF_SUCCESS;
2530
2531 pDisk->uModified |= VD_IMAGE_MODIFIED_FLAG;
2532 if (pDisk->uModified & VD_IMAGE_MODIFIED_FIRST)
2533 {
2534 rc = vdIoCtxLockDisk(pDisk, pIoCtx);
2535 if (RT_SUCCESS(rc))
2536 {
2537 pDisk->uModified &= ~VD_IMAGE_MODIFIED_FIRST;
2538
2539 /* First modify, so create a UUID and ensure it's written to disk. */
2540 vdResetModifiedFlag(pDisk);
2541
2542 if (!(pDisk->uModified & VD_IMAGE_MODIFIED_DISABLE_UUID_UPDATE))
2543 {
2544 PVDIOCTX pIoCtxFlush = vdIoCtxChildAlloc(pDisk, VDIOCTXTXDIR_FLUSH,
2545 0, 0, pDisk->pLast,
2546 NULL, pIoCtx, 0, 0, NULL,
2547 vdSetModifiedHelperAsync);
2548
2549 if (pIoCtxFlush)
2550 {
2551 rc = vdIoCtxProcess(pIoCtxFlush);
2552 if (rc == VINF_VD_ASYNC_IO_FINISHED)
2553 {
2554 vdIoCtxUnlockDisk(pDisk, pIoCtx, false /* fProcessDeferredReqs */);
2555 vdIoCtxFree(pDisk, pIoCtxFlush);
2556 }
2557 else if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
2558 {
2559 ASMAtomicIncU32(&pIoCtx->cDataTransfersPending);
2560 pIoCtx->fBlocked = true;
2561 }
2562 else /* Another error */
2563 vdIoCtxFree(pDisk, pIoCtxFlush);
2564 }
2565 else
2566 rc = VERR_NO_MEMORY;
2567 }
2568 }
2569 }
2570
2571 return rc;
2572}
2573
2574/**
2575 * internal: write a complete block (only used for diff images), taking the
2576 * remaining data from parent images. This implementation does not optimize
2577 * anything (except that it tries to read only that portions from parent
2578 * images that are really needed) - async version.
2579 */
2580static int vdWriteHelperStandardAsync(PVDIOCTX pIoCtx)
2581{
2582 int rc = VINF_SUCCESS;
2583
2584#if 0
2585
2586 /* Read the data that goes before the write to fill the block. */
2587 if (cbPreRead)
2588 {
2589 rc = vdReadHelperAsync(pIoCtxDst);
2590 if (RT_FAILURE(rc))
2591 return rc;
2592 }
2593
2594 /* Copy the data to the right place in the buffer. */
2595 vdIoCtxCopy(pIoCtxDst, pIoCtxSrc, cbThisWrite);
2596
2597 /* Read the data that goes after the write to fill the block. */
2598 if (cbPostRead)
2599 {
2600 /* If we have data to be written, use that instead of reading
2601 * data from the image. */
2602 size_t cbWriteCopy;
2603 if (cbWrite > cbThisWrite)
2604 cbWriteCopy = RT_MIN(cbWrite - cbThisWrite, cbPostRead);
2605 else
2606 cbWriteCopy = 0;
2607 /* Figure out how much we cannot read from the image, because
2608 * the last block to write might exceed the nominal size of the
2609 * image for technical reasons. */
2610 size_t cbFill;
2611 if (uOffset + cbThisWrite + cbPostRead > pDisk->cbSize)
2612 cbFill = uOffset + cbThisWrite + cbPostRead - pDisk->cbSize;
2613 else
2614 cbFill = 0;
2615 /* The rest must be read from the image. */
2616 size_t cbReadImage = cbPostRead - cbWriteCopy - cbFill;
2617
2618 /* Now assemble the remaining data. */
2619 if (cbWriteCopy)
2620 {
2621 vdIoCtxCopy(pIoCtxDst, pIoCtxSrc, cbWriteCopy);
2622 ASMAtomicSubU32(&pIoCtxDst->cbTransferLeft, cbWriteCopy);
2623 }
2624
2625 if (cbReadImage)
2626 rc = vdReadHelperAsync(pDisk, pImage, pImageParentOverride, pIoCtxDst,
2627 uOffset + cbThisWrite + cbWriteCopy,
2628 cbReadImage);
2629 if (RT_FAILURE(rc))
2630 return rc;
2631 /* Zero out the remainder of this block. Will never be visible, as this
2632 * is beyond the limit of the image. */
2633 if (cbFill)
2634 {
2635 vdIoCtxSet(pIoCtxDst, '\0', cbFill);
2636 ASMAtomicSubU32(&pIoCtxDst->cbTransferLeft, cbFill);
2637 }
2638 }
2639
2640 if ( !pIoCtxDst->cbTransferLeft
2641 && !pIoCtxDst->cMetaTransfersPending
2642 && ASMAtomicCmpXchgBool(&pIoCtxDst->fComplete, true, false))
2643 {
2644 /* Write the full block to the virtual disk. */
2645 vdIoCtxChildReset(pIoCtxDst);
2646 rc = pImage->Backend->pfnAsyncWrite(pImage->pBackendData,
2647 uOffset - cbPreRead,
2648 cbPreRead + cbThisWrite + cbPostRead,
2649 pIoCtxDst,
2650 NULL, &cbPreRead, &cbPostRead, 0);
2651 Assert(rc != VERR_VD_BLOCK_FREE);
2652 Assert(cbPreRead == 0);
2653 Assert(cbPostRead == 0);
2654 }
2655 else
2656 {
2657 LogFlow(("cbTransferLeft=%u cMetaTransfersPending=%u fComplete=%RTbool\n",
2658 pIoCtxDst->cbTransferLeft, pIoCtxDst->cMetaTransfersPending,
2659 pIoCtxDst->fComplete));
2660 rc = VERR_VD_ASYNC_IO_IN_PROGRESS;
2661 }
2662
2663 return rc;
2664#endif
2665 return VERR_NOT_IMPLEMENTED;
2666}
2667
2668static int vdWriteHelperOptimizedCommitAsync(PVDIOCTX pIoCtx)
2669{
2670 int rc = VINF_SUCCESS;
2671 PVDIMAGE pImage = pIoCtx->Req.Io.pImageStart;
2672 size_t cbPreRead = pIoCtx->Type.Child.cbPreRead;
2673 size_t cbPostRead = pIoCtx->Type.Child.cbPostRead;
2674 size_t cbThisWrite = pIoCtx->Type.Child.cbTransferParent;
2675
2676 LogFlowFunc(("pIoCtx=%#p\n", pIoCtx));
2677 rc = pImage->Backend->pfnAsyncWrite(pImage->pBackendData,
2678 pIoCtx->Req.Io.uOffset - cbPreRead,
2679 cbPreRead + cbThisWrite + cbPostRead,
2680 pIoCtx, NULL, &cbPreRead, &cbPostRead, 0);
2681 Assert(rc != VERR_VD_BLOCK_FREE);
2682 Assert(rc == VERR_VD_NOT_ENOUGH_METADATA || cbPreRead == 0);
2683 Assert(rc == VERR_VD_NOT_ENOUGH_METADATA || cbPostRead == 0);
2684 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
2685 rc = VINF_SUCCESS;
2686 else if (rc == VERR_VD_IOCTX_HALT)
2687 {
2688 pIoCtx->fBlocked = true;
2689 rc = VINF_SUCCESS;
2690 }
2691
2692 LogFlowFunc(("returns rc=%Rrc\n", rc));
2693 return rc;
2694}
2695
2696static int vdWriteHelperOptimizedCmpAndWriteAsync(PVDIOCTX pIoCtx)
2697{
2698 int rc = VINF_SUCCESS;
2699 PVDIMAGE pImage = pIoCtx->Req.Io.pImageCur;
2700 size_t cbThisWrite = 0;
2701 size_t cbPreRead = pIoCtx->Type.Child.cbPreRead;
2702 size_t cbPostRead = pIoCtx->Type.Child.cbPostRead;
2703 size_t cbWriteCopy = pIoCtx->Type.Child.Write.Optimized.cbWriteCopy;
2704 size_t cbFill = pIoCtx->Type.Child.Write.Optimized.cbFill;
2705 size_t cbReadImage = pIoCtx->Type.Child.Write.Optimized.cbReadImage;
2706 PVDIOCTX pIoCtxParent = pIoCtx->pIoCtxParent;
2707
2708 LogFlowFunc(("pIoCtx=%#p\n", pIoCtx));
2709
2710 AssertPtr(pIoCtxParent);
2711 Assert(!pIoCtxParent->pIoCtxParent);
2712 Assert(!pIoCtx->Req.Io.cbTransferLeft && !pIoCtx->cMetaTransfersPending);
2713
2714 vdIoCtxChildReset(pIoCtx);
2715 cbThisWrite = pIoCtx->Type.Child.cbTransferParent;
2716 RTSgBufAdvance(&pIoCtx->Req.Io.SgBuf, cbPreRead);
2717
2718 /* Check if the write would modify anything in this block. */
2719 if (!RTSgBufCmp(&pIoCtx->Req.Io.SgBuf, &pIoCtxParent->Req.Io.SgBuf, cbThisWrite))
2720 {
2721 RTSGBUF SgBufSrcTmp;
2722
2723 RTSgBufClone(&SgBufSrcTmp, &pIoCtxParent->Req.Io.SgBuf);
2724 RTSgBufAdvance(&SgBufSrcTmp, cbThisWrite);
2725 RTSgBufAdvance(&pIoCtx->Req.Io.SgBuf, cbThisWrite);
2726
2727 if (!cbWriteCopy || !RTSgBufCmp(&pIoCtx->Req.Io.SgBuf, &SgBufSrcTmp, cbWriteCopy))
2728 {
2729 /* Block is completely unchanged, so no need to write anything. */
2730 LogFlowFunc(("Block didn't changed\n"));
2731 ASMAtomicWriteU32(&pIoCtx->Req.Io.cbTransferLeft, 0);
2732 RTSgBufAdvance(&pIoCtxParent->Req.Io.SgBuf, cbThisWrite);
2733 return VINF_VD_ASYNC_IO_FINISHED;
2734 }
2735 }
2736
2737 /* Copy the data to the right place in the buffer. */
2738 RTSgBufReset(&pIoCtx->Req.Io.SgBuf);
2739 RTSgBufAdvance(&pIoCtx->Req.Io.SgBuf, cbPreRead);
2740 vdIoCtxCopy(pIoCtx, pIoCtxParent, cbThisWrite);
2741
2742 /* Handle the data that goes after the write to fill the block. */
2743 if (cbPostRead)
2744 {
2745 /* Now assemble the remaining data. */
2746 if (cbWriteCopy)
2747 {
2748 /*
2749 * The S/G buffer of the parent needs to be cloned because
2750 * it is not allowed to modify the state.
2751 */
2752 RTSGBUF SgBufParentTmp;
2753
2754 RTSgBufClone(&SgBufParentTmp, &pIoCtxParent->Req.Io.SgBuf);
2755 RTSgBufCopy(&pIoCtx->Req.Io.SgBuf, &SgBufParentTmp, cbWriteCopy);
2756 }
2757
2758 /* Zero out the remainder of this block. Will never be visible, as this
2759 * is beyond the limit of the image. */
2760 if (cbFill)
2761 {
2762 RTSgBufAdvance(&pIoCtx->Req.Io.SgBuf, cbReadImage);
2763 vdIoCtxSet(pIoCtx, '\0', cbFill);
2764 }
2765 }
2766
2767 /* Write the full block to the virtual disk. */
2768 RTSgBufReset(&pIoCtx->Req.Io.SgBuf);
2769 pIoCtx->pfnIoCtxTransferNext = vdWriteHelperOptimizedCommitAsync;
2770
2771 return rc;
2772}
2773
2774static int vdWriteHelperOptimizedPreReadAsync(PVDIOCTX pIoCtx)
2775{
2776 int rc = VINF_SUCCESS;
2777
2778 LogFlowFunc(("pIoCtx=%#p\n", pIoCtx));
2779
2780 if (pIoCtx->Req.Io.cbTransferLeft)
2781 rc = vdReadHelperAsync(pIoCtx);
2782
2783 if ( RT_SUCCESS(rc)
2784 && ( pIoCtx->Req.Io.cbTransferLeft
2785 || pIoCtx->cMetaTransfersPending))
2786 rc = VERR_VD_ASYNC_IO_IN_PROGRESS;
2787 else
2788 pIoCtx->pfnIoCtxTransferNext = vdWriteHelperOptimizedCmpAndWriteAsync;
2789
2790 return rc;
2791}
2792
2793/**
2794 * internal: write a complete block (only used for diff images), taking the
2795 * remaining data from parent images. This implementation optimizes out writes
2796 * that do not change the data relative to the state as of the parent images.
2797 * All backends which support differential/growing images support this - async version.
2798 */
2799static int vdWriteHelperOptimizedAsync(PVDIOCTX pIoCtx)
2800{
2801 PVBOXHDD pDisk = pIoCtx->pDisk;
2802 uint64_t uOffset = pIoCtx->Type.Child.uOffsetSaved;
2803 size_t cbThisWrite = pIoCtx->Type.Child.cbTransferParent;
2804 size_t cbPreRead = pIoCtx->Type.Child.cbPreRead;
2805 size_t cbPostRead = pIoCtx->Type.Child.cbPostRead;
2806 size_t cbWrite = pIoCtx->Type.Child.cbWriteParent;
2807 size_t cbFill = 0;
2808 size_t cbWriteCopy = 0;
2809 size_t cbReadImage = 0;
2810
2811 LogFlowFunc(("pIoCtx=%#p\n", pIoCtx));
2812
2813 AssertPtr(pIoCtx->pIoCtxParent);
2814 Assert(!pIoCtx->pIoCtxParent->pIoCtxParent);
2815
2816 if (cbPostRead)
2817 {
2818 /* Figure out how much we cannot read from the image, because
2819 * the last block to write might exceed the nominal size of the
2820 * image for technical reasons. */
2821 if (uOffset + cbThisWrite + cbPostRead > pDisk->cbSize)
2822 cbFill = uOffset + cbThisWrite + cbPostRead - pDisk->cbSize;
2823
2824 /* If we have data to be written, use that instead of reading
2825 * data from the image. */
2826 if (cbWrite > cbThisWrite)
2827 cbWriteCopy = RT_MIN(cbWrite - cbThisWrite, cbPostRead);
2828
2829 /* The rest must be read from the image. */
2830 cbReadImage = cbPostRead - cbWriteCopy - cbFill;
2831 }
2832
2833 pIoCtx->Type.Child.Write.Optimized.cbFill = cbFill;
2834 pIoCtx->Type.Child.Write.Optimized.cbWriteCopy = cbWriteCopy;
2835 pIoCtx->Type.Child.Write.Optimized.cbReadImage = cbReadImage;
2836
2837 /* Read the entire data of the block so that we can compare whether it will
2838 * be modified by the write or not. */
2839 pIoCtx->Req.Io.cbTransferLeft = cbPreRead + cbThisWrite + cbPostRead - cbFill;
2840 pIoCtx->Req.Io.cbTransfer = pIoCtx->Req.Io.cbTransferLeft;
2841 pIoCtx->Req.Io.uOffset -= cbPreRead;
2842
2843 /* Next step */
2844 pIoCtx->pfnIoCtxTransferNext = vdWriteHelperOptimizedPreReadAsync;
2845 return VINF_SUCCESS;
2846}
2847
2848/**
2849 * internal: write buffer to the image, taking care of block boundaries and
2850 * write optimizations - async version.
2851 */
2852static int vdWriteHelperAsync(PVDIOCTX pIoCtx)
2853{
2854 int rc;
2855 size_t cbWrite = pIoCtx->Req.Io.cbTransfer;
2856 uint64_t uOffset = pIoCtx->Req.Io.uOffset;
2857 PVDIMAGE pImage = pIoCtx->Req.Io.pImageCur;
2858 PVBOXHDD pDisk = pIoCtx->pDisk;
2859 unsigned fWrite;
2860 size_t cbThisWrite;
2861 size_t cbPreRead, cbPostRead;
2862
2863 rc = vdSetModifiedFlagAsync(pDisk, pIoCtx);
2864 if (RT_FAILURE(rc)) /* Includes I/O in progress. */
2865 return rc;
2866
2867 rc = vdDiscardSetRangeAllocated(pDisk, uOffset, cbWrite);
2868 if (RT_FAILURE(rc))
2869 return rc;
2870
2871 /* Loop until all written. */
2872 do
2873 {
2874 /* Try to write the possibly partial block to the last opened image.
2875 * This works when the block is already allocated in this image or
2876 * if it is a full-block write (and allocation isn't suppressed below).
2877 * For image formats which don't support zero blocks, it's beneficial
2878 * to avoid unnecessarily allocating unchanged blocks. This prevents
2879 * unwanted expanding of images. VMDK is an example. */
2880 cbThisWrite = cbWrite;
2881 fWrite = (pImage->uOpenFlags & VD_OPEN_FLAGS_HONOR_SAME)
2882 ? 0 : VD_WRITE_NO_ALLOC;
2883 rc = pImage->Backend->pfnAsyncWrite(pImage->pBackendData, uOffset,
2884 cbThisWrite, pIoCtx,
2885 &cbThisWrite, &cbPreRead,
2886 &cbPostRead, fWrite);
2887 if (rc == VERR_VD_BLOCK_FREE)
2888 {
2889 /* Lock the disk .*/
2890 rc = vdIoCtxLockDisk(pDisk, pIoCtx);
2891 if (RT_SUCCESS(rc))
2892 {
2893 /*
2894 * Allocate segment and buffer in one go.
2895 * A bit hackish but avoids the need to allocate memory twice.
2896 */
2897 PRTSGBUF pTmp = (PRTSGBUF)RTMemAlloc(cbPreRead + cbThisWrite + cbPostRead + sizeof(RTSGSEG) + sizeof(RTSGBUF));
2898 AssertBreakStmt(VALID_PTR(pTmp), rc = VERR_NO_MEMORY);
2899 PRTSGSEG pSeg = (PRTSGSEG)(pTmp + 1);
2900
2901 pSeg->pvSeg = pSeg + 1;
2902 pSeg->cbSeg = cbPreRead + cbThisWrite + cbPostRead;
2903 RTSgBufInit(pTmp, pSeg, 1);
2904
2905 PVDIOCTX pIoCtxWrite = vdIoCtxChildAlloc(pDisk, VDIOCTXTXDIR_WRITE,
2906 uOffset, pSeg->cbSeg, pImage,
2907 pTmp,
2908 pIoCtx, cbThisWrite,
2909 cbWrite,
2910 pTmp,
2911 (pImage->uOpenFlags & VD_OPEN_FLAGS_HONOR_SAME)
2912 ? vdWriteHelperStandardAsync
2913 : vdWriteHelperOptimizedAsync);
2914 if (!VALID_PTR(pIoCtxWrite))
2915 {
2916 RTMemTmpFree(pTmp);
2917 rc = VERR_NO_MEMORY;
2918 break;
2919 }
2920
2921 LogFlowFunc(("Disk is growing because of pIoCtx=%#p pIoCtxWrite=%#p\n",
2922 pIoCtx, pIoCtxWrite));
2923
2924 pIoCtxWrite->Type.Child.cbPreRead = cbPreRead;
2925 pIoCtxWrite->Type.Child.cbPostRead = cbPostRead;
2926
2927 /* Process the write request */
2928 rc = vdIoCtxProcess(pIoCtxWrite);
2929
2930 if (RT_FAILURE(rc) && (rc != VERR_VD_ASYNC_IO_IN_PROGRESS))
2931 {
2932 vdIoCtxFree(pDisk, pIoCtxWrite);
2933 break;
2934 }
2935 else if ( rc == VINF_VD_ASYNC_IO_FINISHED
2936 && ASMAtomicCmpXchgBool(&pIoCtxWrite->fComplete, true, false))
2937 {
2938 LogFlow(("Child write request completed\n"));
2939 Assert(pIoCtx->Req.Io.cbTransferLeft >= cbThisWrite);
2940 ASMAtomicSubU32(&pIoCtx->Req.Io.cbTransferLeft, cbThisWrite);
2941 vdIoCtxUnlockDisk(pDisk, pIoCtx, false /* fProcessDeferredReqs*/ );
2942 vdIoCtxFree(pDisk, pIoCtxWrite);
2943
2944 rc = VINF_SUCCESS;
2945 }
2946 else
2947 {
2948 LogFlow(("Child write pending\n"));
2949 ASMAtomicIncU32(&pIoCtx->cDataTransfersPending);
2950 pIoCtx->fBlocked = true;
2951 rc = VERR_VD_ASYNC_IO_IN_PROGRESS;
2952 cbWrite -= cbThisWrite;
2953 uOffset += cbThisWrite;
2954 break;
2955 }
2956 }
2957 else
2958 {
2959 rc = VERR_VD_ASYNC_IO_IN_PROGRESS;
2960 break;
2961 }
2962 }
2963
2964 if (rc == VERR_VD_IOCTX_HALT)
2965 {
2966 cbWrite -= cbThisWrite;
2967 uOffset += cbThisWrite;
2968 pIoCtx->fBlocked = true;
2969 break;
2970 }
2971 else if (rc == VERR_VD_NOT_ENOUGH_METADATA)
2972 break;
2973
2974 cbWrite -= cbThisWrite;
2975 uOffset += cbThisWrite;
2976 } while (cbWrite != 0 && (RT_SUCCESS(rc) || rc == VERR_VD_ASYNC_IO_IN_PROGRESS));
2977
2978 if ( rc == VERR_VD_ASYNC_IO_IN_PROGRESS
2979 || rc == VERR_VD_NOT_ENOUGH_METADATA
2980 || rc == VERR_VD_IOCTX_HALT)
2981 {
2982 /*
2983 * Tell the caller that we don't need to go back here because all
2984 * writes are initiated.
2985 */
2986 if ( !cbWrite
2987 && rc != VERR_VD_IOCTX_HALT)
2988 rc = VINF_SUCCESS;
2989
2990 pIoCtx->Req.Io.uOffset = uOffset;
2991 pIoCtx->Req.Io.cbTransfer = cbWrite;
2992 }
2993
2994 return rc;
2995}
2996
2997/**
2998 * Flush helper async version.
2999 */
3000static int vdFlushHelperAsync(PVDIOCTX pIoCtx)
3001{
3002 int rc = VINF_SUCCESS;
3003 PVBOXHDD pDisk = pIoCtx->pDisk;
3004 PVDIMAGE pImage = pIoCtx->Req.Io.pImageCur;
3005
3006 rc = vdIoCtxLockDisk(pDisk, pIoCtx);
3007 if (RT_SUCCESS(rc))
3008 {
3009 vdResetModifiedFlag(pDisk);
3010 rc = pImage->Backend->pfnAsyncFlush(pImage->pBackendData, pIoCtx);
3011 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
3012 rc = VINF_SUCCESS;
3013 else if (rc == VINF_VD_ASYNC_IO_FINISHED)
3014 vdIoCtxUnlockDisk(pDisk, pIoCtx, true /* fProcessDeferredReqs */);
3015 }
3016
3017 return rc;
3018}
3019
3020/**
3021 * Async discard helper - discards a whole block which is recorded in the block
3022 * tree.
3023 *
3024 * @returns VBox status code.
3025 * @param pIoCtx The I/O context to operate on.
3026 */
3027static int vdDiscardWholeBlockAsync(PVDIOCTX pIoCtx)
3028{
3029 int rc = VINF_SUCCESS;
3030 PVBOXHDD pDisk = pIoCtx->pDisk;
3031 PVDDISCARDSTATE pDiscard = pDisk->pDiscard;
3032 PVDDISCARDBLOCK pBlock = pIoCtx->Req.Discard.pBlock;
3033 size_t cbPreAllocated, cbPostAllocated, cbActuallyDiscarded;
3034
3035 LogFlowFunc(("pIoCtx=%#p\n", pIoCtx));
3036
3037 AssertPtr(pBlock);
3038
3039 rc = pDisk->pLast->Backend->pfnAsyncDiscard(pDisk->pLast->pBackendData, pIoCtx,
3040 pBlock->Core.Key, pBlock->cbDiscard,
3041 &cbPreAllocated, &cbPostAllocated,
3042 &cbActuallyDiscarded, NULL, 0);
3043 Assert(rc != VERR_VD_DISCARD_ALIGNMENT_NOT_MET);
3044 Assert(!cbPreAllocated);
3045 Assert(!cbPostAllocated);
3046 Assert(cbActuallyDiscarded == pBlock->cbDiscard || RT_FAILURE(rc));
3047
3048 /* Remove the block on success. */
3049 if ( RT_SUCCESS(rc)
3050 || rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
3051 {
3052 PVDDISCARDBLOCK pBlockRemove = (PVDDISCARDBLOCK)RTAvlrU64RangeRemove(pDiscard->pTreeBlocks, pBlock->Core.Key);
3053 Assert(pBlockRemove == pBlock);
3054
3055 pDiscard->cbDiscarding -= pBlock->cbDiscard;
3056 RTListNodeRemove(&pBlock->NodeLru);
3057 RTMemFree(pBlock->pbmAllocated);
3058 RTMemFree(pBlock);
3059 pIoCtx->Req.Discard.pBlock = NULL;/* Safety precaution. */
3060 pIoCtx->pfnIoCtxTransferNext = vdDiscardHelperAsync; /* Next part. */
3061 rc = VINF_SUCCESS;
3062 }
3063
3064 LogFlowFunc(("returns rc=%Rrc\n", rc));
3065 return rc;
3066}
3067
3068/**
3069 * Removes the least recently used blocks from the waiting list until
3070 * the new value is reached - version for async I/O.
3071 *
3072 * @returns VBox status code.
3073 * @param pDisk VD disk container.
3074 * @param pDiscard The discard state.
3075 * @param cbDiscardingNew How many bytes should be waiting on success.
3076 * The number of bytes waiting can be less.
3077 */
3078static int vdDiscardRemoveBlocksAsync(PVBOXHDD pDisk, PVDIOCTX pIoCtx, size_t cbDiscardingNew)
3079{
3080 int rc = VINF_SUCCESS;
3081 PVDDISCARDSTATE pDiscard = pDisk->pDiscard;
3082
3083 LogFlowFunc(("pDisk=%#p pDiscard=%#p cbDiscardingNew=%zu\n",
3084 pDisk, pDiscard, cbDiscardingNew));
3085
3086 while (pDiscard->cbDiscarding > cbDiscardingNew)
3087 {
3088 PVDDISCARDBLOCK pBlock = RTListGetLast(&pDiscard->ListLru, VDDISCARDBLOCK, NodeLru);
3089
3090 Assert(!RTListIsEmpty(&pDiscard->ListLru));
3091
3092 /* Go over the allocation bitmap and mark all discarded sectors as unused. */
3093 uint64_t offStart = pBlock->Core.Key;
3094 uint32_t idxStart = 0;
3095 size_t cbLeft = pBlock->cbDiscard;
3096 bool fAllocated = ASMBitTest(pBlock->pbmAllocated, idxStart);
3097 uint32_t cSectors = pBlock->cbDiscard / 512;
3098
3099 while (cbLeft > 0)
3100 {
3101 int32_t idxEnd;
3102 size_t cbThis = cbLeft;
3103
3104 if (fAllocated)
3105 {
3106 /* Check for the first unallocated bit. */
3107 idxEnd = ASMBitNextClear(pBlock->pbmAllocated, cSectors, idxStart);
3108 if (idxEnd != -1)
3109 {
3110 cbThis = (idxEnd - idxStart) * 512;
3111 fAllocated = false;
3112 }
3113 }
3114 else
3115 {
3116 /* Mark as unused and check for the first set bit. */
3117 idxEnd = ASMBitNextSet(pBlock->pbmAllocated, cSectors, idxStart);
3118 if (idxEnd != -1)
3119 cbThis = (idxEnd - idxStart) * 512;
3120
3121 rc = pDisk->pLast->Backend->pfnAsyncDiscard(pDisk->pLast->pBackendData, pIoCtx,
3122 offStart, cbThis, NULL, NULL, &cbThis,
3123 NULL, VD_DISCARD_MARK_UNUSED);
3124 if ( RT_FAILURE(rc)
3125 && rc != VERR_VD_ASYNC_IO_IN_PROGRESS)
3126 break;
3127
3128 fAllocated = true;
3129 }
3130
3131 idxStart = idxEnd;
3132 offStart += cbThis;
3133 cbLeft -= cbThis;
3134 }
3135
3136 if ( RT_FAILURE(rc)
3137 && rc != VERR_VD_ASYNC_IO_IN_PROGRESS)
3138 break;
3139
3140 PVDDISCARDBLOCK pBlockRemove = (PVDDISCARDBLOCK)RTAvlrU64RangeRemove(pDiscard->pTreeBlocks, pBlock->Core.Key);
3141 Assert(pBlockRemove == pBlock);
3142 RTListNodeRemove(&pBlock->NodeLru);
3143
3144 pDiscard->cbDiscarding -= pBlock->cbDiscard;
3145 RTMemFree(pBlock->pbmAllocated);
3146 RTMemFree(pBlock);
3147 }
3148
3149 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
3150 rc = VINF_SUCCESS;
3151
3152 Assert(RT_FAILURE(rc) || pDiscard->cbDiscarding <= cbDiscardingNew);
3153
3154 LogFlowFunc(("returns rc=%Rrc\n", rc));
3155 return rc;
3156}
3157
3158/**
3159 * Async discard helper - discards the current range if there is no matching
3160 * block in the tree.
3161 *
3162 * @returns VBox status code.
3163 * @param pIoCtx The I/O context to operate on.
3164 */
3165static int vdDiscardCurrentRangeAsync(PVDIOCTX pIoCtx)
3166{
3167 PVBOXHDD pDisk = pIoCtx->pDisk;
3168 PVDDISCARDSTATE pDiscard = pDisk->pDiscard;
3169 uint64_t offStart = pIoCtx->Req.Discard.offCur;
3170 size_t cbThisDiscard = pIoCtx->Req.Discard.cbThisDiscard;
3171 void *pbmAllocated = NULL;
3172 size_t cbPreAllocated, cbPostAllocated;
3173 int rc = VINF_SUCCESS;
3174
3175 LogFlowFunc(("pIoCtx=%#p\n", pIoCtx));
3176
3177 /* No block found, try to discard using the backend first. */
3178 rc = pDisk->pLast->Backend->pfnAsyncDiscard(pDisk->pLast->pBackendData, pIoCtx,
3179 offStart, cbThisDiscard, &cbPreAllocated,
3180 &cbPostAllocated, &cbThisDiscard,
3181 &pbmAllocated, 0);
3182 if (rc == VERR_VD_DISCARD_ALIGNMENT_NOT_MET)
3183 {
3184 /* Create new discard block. */
3185 PVDDISCARDBLOCK pBlock = (PVDDISCARDBLOCK)RTMemAllocZ(sizeof(VDDISCARDBLOCK));
3186 if (pBlock)
3187 {
3188 pBlock->Core.Key = offStart - cbPreAllocated;
3189 pBlock->Core.KeyLast = offStart + cbThisDiscard + cbPostAllocated - 1;
3190 pBlock->cbDiscard = cbPreAllocated + cbThisDiscard + cbPostAllocated;
3191 pBlock->pbmAllocated = pbmAllocated;
3192 bool fInserted = RTAvlrU64Insert(pDiscard->pTreeBlocks, &pBlock->Core);
3193 Assert(fInserted);
3194
3195 RTListPrepend(&pDiscard->ListLru, &pBlock->NodeLru);
3196 pDiscard->cbDiscarding += pBlock->cbDiscard;
3197
3198 Assert(pIoCtx->Req.Discard.cbDiscardLeft >= cbThisDiscard);
3199 pIoCtx->Req.Discard.cbDiscardLeft -= cbThisDiscard;
3200 pIoCtx->Req.Discard.offCur += cbThisDiscard;
3201 pIoCtx->Req.Discard.cbThisDiscard = cbThisDiscard;
3202
3203 if (pDiscard->cbDiscarding > VD_DISCARD_REMOVE_THRESHOLD)
3204 rc = vdDiscardRemoveBlocksAsync(pDisk, pIoCtx, VD_DISCARD_REMOVE_THRESHOLD);
3205 else
3206 rc = VINF_SUCCESS;
3207
3208 if (RT_SUCCESS(rc))
3209 pIoCtx->pfnIoCtxTransferNext = vdDiscardHelperAsync; /* Next part. */
3210 }
3211 else
3212 {
3213 RTMemFree(pbmAllocated);
3214 rc = VERR_NO_MEMORY;
3215 }
3216 }
3217 else if ( RT_SUCCESS(rc)
3218 || rc == VERR_VD_ASYNC_IO_IN_PROGRESS) /* Save state and andvance to next range. */
3219 {
3220 Assert(pIoCtx->Req.Discard.cbDiscardLeft >= cbThisDiscard);
3221 pIoCtx->Req.Discard.cbDiscardLeft -= cbThisDiscard;
3222 pIoCtx->Req.Discard.offCur += cbThisDiscard;
3223 pIoCtx->Req.Discard.cbThisDiscard = cbThisDiscard;
3224 pIoCtx->pfnIoCtxTransferNext = vdDiscardHelperAsync;
3225 rc = VINF_SUCCESS;
3226 }
3227
3228 LogFlowFunc(("returns rc=%Rrc\n", rc));
3229 return rc;
3230}
3231
3232/**
3233 * Async discard helper - entry point.
3234 *
3235 * @returns VBox status code.
3236 * @param pIoCtx The I/O context to operate on.
3237 */
3238static int vdDiscardHelperAsync(PVDIOCTX pIoCtx)
3239{
3240 int rc = VINF_SUCCESS;
3241 PVBOXHDD pDisk = pIoCtx->pDisk;
3242 PCRTRANGE paRanges = pIoCtx->Req.Discard.paRanges;
3243 unsigned cRanges = pIoCtx->Req.Discard.cRanges;
3244 PVDDISCARDSTATE pDiscard = pDisk->pDiscard;
3245
3246 LogFlowFunc(("pIoCtx=%#p\n", pIoCtx));
3247
3248 /* Check if the I/O context processed all ranges. */
3249 if ( pIoCtx->Req.Discard.idxRange == cRanges
3250 && !pIoCtx->Req.Discard.cbDiscardLeft)
3251 {
3252 LogFlowFunc(("All ranges discarded, completing\n"));
3253 vdIoCtxUnlockDisk(pDisk, pIoCtx, true /* fProcessDeferredReqs*/);
3254 return VINF_SUCCESS;
3255 }
3256
3257 if (pDisk->pIoCtxLockOwner != pIoCtx)
3258 rc = vdIoCtxLockDisk(pDisk, pIoCtx);
3259
3260 if (RT_SUCCESS(rc))
3261 {
3262 uint64_t offStart = pIoCtx->Req.Discard.offCur;
3263 size_t cbDiscardLeft = pIoCtx->Req.Discard.cbDiscardLeft;
3264 size_t cbThisDiscard;
3265
3266 if (RT_UNLIKELY(!pDiscard))
3267 {
3268 pDiscard = vdDiscardStateCreate();
3269 if (!pDiscard)
3270 return VERR_NO_MEMORY;
3271
3272 pDisk->pDiscard = pDiscard;
3273 }
3274
3275 if (!pIoCtx->Req.Discard.cbDiscardLeft)
3276 {
3277 offStart = paRanges[pIoCtx->Req.Discard.idxRange].offStart;
3278 cbDiscardLeft = paRanges[pIoCtx->Req.Discard.idxRange].cbRange;
3279 LogFlowFunc(("New range descriptor loaded (%u) offStart=%llu cbDiscard=%zu\n",
3280 pIoCtx->Req.Discard.idxRange, offStart, cbDiscardLeft));
3281 pIoCtx->Req.Discard.idxRange++;
3282 }
3283
3284 /* Look for a matching block in the AVL tree first. */
3285 PVDDISCARDBLOCK pBlock = (PVDDISCARDBLOCK)RTAvlrU64GetBestFit(pDiscard->pTreeBlocks, offStart, false);
3286 if (!pBlock || pBlock->Core.KeyLast < offStart)
3287 {
3288 PVDDISCARDBLOCK pBlockAbove = (PVDDISCARDBLOCK)RTAvlrU64GetBestFit(pDiscard->pTreeBlocks, offStart, true);
3289
3290 /* Clip range to remain in the current block. */
3291 if (pBlockAbove)
3292 cbThisDiscard = RT_MIN(cbDiscardLeft, pBlockAbove->Core.KeyLast - offStart + 1);
3293 else
3294 cbThisDiscard = cbDiscardLeft;
3295
3296 Assert(!(cbThisDiscard % 512));
3297 pIoCtx->Req.Discard.pBlock = NULL;
3298 pIoCtx->pfnIoCtxTransferNext = vdDiscardCurrentRangeAsync;
3299 }
3300 else
3301 {
3302 /* Range lies partly in the block, update allocation bitmap. */
3303 int32_t idxStart, idxEnd;
3304
3305 cbThisDiscard = RT_MIN(cbDiscardLeft, pBlock->Core.KeyLast - offStart + 1);
3306
3307 AssertPtr(pBlock);
3308
3309 Assert(!(cbThisDiscard % 512));
3310 Assert(!((offStart - pBlock->Core.Key) % 512));
3311
3312 idxStart = (offStart - pBlock->Core.Key) / 512;
3313 idxEnd = idxStart + (cbThisDiscard / 512);
3314
3315 ASMBitClearRange(pBlock->pbmAllocated, idxStart, idxEnd);
3316
3317 cbDiscardLeft -= cbThisDiscard;
3318 offStart += cbThisDiscard;
3319
3320 /* Call the backend to discard the block if it is completely unallocated now. */
3321 if (ASMBitFirstSet((volatile void *)pBlock->pbmAllocated, pBlock->cbDiscard / 512) == -1)
3322 {
3323 pIoCtx->Req.Discard.pBlock = pBlock;
3324 pIoCtx->pfnIoCtxTransferNext = vdDiscardWholeBlockAsync;
3325 rc = VINF_SUCCESS;
3326 }
3327 else
3328 {
3329 RTListNodeRemove(&pBlock->NodeLru);
3330 RTListPrepend(&pDiscard->ListLru, &pBlock->NodeLru);
3331
3332 /* Start with next range. */
3333 pIoCtx->pfnIoCtxTransferNext = vdDiscardHelperAsync;
3334 rc = VINF_SUCCESS;
3335 }
3336 }
3337
3338 /* Save state in the context. */
3339 pIoCtx->Req.Discard.offCur = offStart;
3340 pIoCtx->Req.Discard.cbDiscardLeft = cbDiscardLeft;
3341 pIoCtx->Req.Discard.cbThisDiscard = cbThisDiscard;
3342 }
3343
3344 LogFlowFunc(("returns rc=%Rrc\n", rc));
3345 return rc;
3346}
3347
3348/**
3349 * internal: scans plugin directory and loads the backends have been found.
3350 */
3351static int vdLoadDynamicBackends()
3352{
3353#ifndef VBOX_HDD_NO_DYNAMIC_BACKENDS
3354 int rc = VINF_SUCCESS;
3355 PRTDIR pPluginDir = NULL;
3356
3357 /* Enumerate plugin backends. */
3358 char szPath[RTPATH_MAX];
3359 rc = RTPathAppPrivateArch(szPath, sizeof(szPath));
3360 if (RT_FAILURE(rc))
3361 return rc;
3362
3363 /* To get all entries with VBoxHDD as prefix. */
3364 char *pszPluginFilter = RTPathJoinA(szPath, VBOX_HDDFORMAT_PLUGIN_PREFIX "*");
3365 if (!pszPluginFilter)
3366 return VERR_NO_STR_MEMORY;
3367
3368 PRTDIRENTRYEX pPluginDirEntry = NULL;
3369 size_t cbPluginDirEntry = sizeof(RTDIRENTRYEX);
3370 /* The plugins are in the same directory as the other shared libs. */
3371 rc = RTDirOpenFiltered(&pPluginDir, pszPluginFilter, RTDIRFILTER_WINNT, 0);
3372 if (RT_FAILURE(rc))
3373 {
3374 /* On Windows the above immediately signals that there are no
3375 * files matching, while on other platforms enumerating the
3376 * files below fails. Either way: no plugins. */
3377 goto out;
3378 }
3379
3380 pPluginDirEntry = (PRTDIRENTRYEX)RTMemAllocZ(sizeof(RTDIRENTRYEX));
3381 if (!pPluginDirEntry)
3382 {
3383 rc = VERR_NO_MEMORY;
3384 goto out;
3385 }
3386
3387 while ((rc = RTDirReadEx(pPluginDir, pPluginDirEntry, &cbPluginDirEntry, RTFSOBJATTRADD_NOTHING, RTPATH_F_ON_LINK)) != VERR_NO_MORE_FILES)
3388 {
3389 RTLDRMOD hPlugin = NIL_RTLDRMOD;
3390 PFNVBOXHDDFORMATLOAD pfnHDDFormatLoad = NULL;
3391 PVBOXHDDBACKEND pBackend = NULL;
3392 char *pszPluginPath = NULL;
3393
3394 if (rc == VERR_BUFFER_OVERFLOW)
3395 {
3396 /* allocate new buffer. */
3397 RTMemFree(pPluginDirEntry);
3398 pPluginDirEntry = (PRTDIRENTRYEX)RTMemAllocZ(cbPluginDirEntry);
3399 if (!pPluginDirEntry)
3400 {
3401 rc = VERR_NO_MEMORY;
3402 break;
3403 }
3404 /* Retry. */
3405 rc = RTDirReadEx(pPluginDir, pPluginDirEntry, &cbPluginDirEntry, RTFSOBJATTRADD_NOTHING, RTPATH_F_ON_LINK);
3406 if (RT_FAILURE(rc))
3407 break;
3408 }
3409 else if (RT_FAILURE(rc))
3410 break;
3411
3412 /* We got the new entry. */
3413 if (!RTFS_IS_FILE(pPluginDirEntry->Info.Attr.fMode))
3414 continue;
3415
3416 /* Prepend the path to the libraries. */
3417 pszPluginPath = RTPathJoinA(szPath, pPluginDirEntry->szName);
3418 if (!pszPluginPath)
3419 {
3420 rc = VERR_NO_STR_MEMORY;
3421 break;
3422 }
3423
3424 rc = SUPR3HardenedLdrLoadPlugIn(pszPluginPath, &hPlugin, NULL);
3425 if (RT_SUCCESS(rc))
3426 {
3427 rc = RTLdrGetSymbol(hPlugin, VBOX_HDDFORMAT_LOAD_NAME, (void**)&pfnHDDFormatLoad);
3428 if (RT_FAILURE(rc) || !pfnHDDFormatLoad)
3429 {
3430 LogFunc(("error resolving the entry point %s in plugin %s, rc=%Rrc, pfnHDDFormat=%#p\n", VBOX_HDDFORMAT_LOAD_NAME, pPluginDirEntry->szName, rc, pfnHDDFormatLoad));
3431 if (RT_SUCCESS(rc))
3432 rc = VERR_SYMBOL_NOT_FOUND;
3433 }
3434
3435 if (RT_SUCCESS(rc))
3436 {
3437 /* Get the function table. */
3438 rc = pfnHDDFormatLoad(&pBackend);
3439 if (RT_SUCCESS(rc) && pBackend->cbSize == sizeof(VBOXHDDBACKEND))
3440 {
3441 pBackend->hPlugin = hPlugin;
3442 vdAddBackend(pBackend);
3443 }
3444 else
3445 LogFunc(("ignored plugin '%s': pBackend->cbSize=%d rc=%Rrc\n", pszPluginPath, pBackend->cbSize, rc));
3446 }
3447 else
3448 LogFunc(("ignored plugin '%s': rc=%Rrc\n", pszPluginPath, rc));
3449
3450 if (RT_FAILURE(rc))
3451 RTLdrClose(hPlugin);
3452 }
3453 RTStrFree(pszPluginPath);
3454 }
3455out:
3456 if (rc == VERR_NO_MORE_FILES)
3457 rc = VINF_SUCCESS;
3458 RTStrFree(pszPluginFilter);
3459 if (pPluginDirEntry)
3460 RTMemFree(pPluginDirEntry);
3461 if (pPluginDir)
3462 RTDirClose(pPluginDir);
3463 return rc;
3464#else
3465 return VINF_SUCCESS;
3466#endif
3467}
3468
3469/**
3470 * internal: scans plugin directory and loads the cache backends have been found.
3471 */
3472static int vdLoadDynamicCacheBackends()
3473{
3474#ifndef VBOX_HDD_NO_DYNAMIC_BACKENDS
3475 int rc = VINF_SUCCESS;
3476 PRTDIR pPluginDir = NULL;
3477
3478 /* Enumerate plugin backends. */
3479 char szPath[RTPATH_MAX];
3480 rc = RTPathAppPrivateArch(szPath, sizeof(szPath));
3481 if (RT_FAILURE(rc))
3482 return rc;
3483
3484 /* To get all entries with VBoxHDD as prefix. */
3485 char *pszPluginFilter = RTPathJoinA(szPath, VD_CACHEFORMAT_PLUGIN_PREFIX "*");
3486 if (!pszPluginFilter)
3487 {
3488 rc = VERR_NO_STR_MEMORY;
3489 return rc;
3490 }
3491
3492 PRTDIRENTRYEX pPluginDirEntry = NULL;
3493 size_t cbPluginDirEntry = sizeof(RTDIRENTRYEX);
3494 /* The plugins are in the same directory as the other shared libs. */
3495 rc = RTDirOpenFiltered(&pPluginDir, pszPluginFilter, RTDIRFILTER_WINNT, 0);
3496 if (RT_FAILURE(rc))
3497 {
3498 /* On Windows the above immediately signals that there are no
3499 * files matching, while on other platforms enumerating the
3500 * files below fails. Either way: no plugins. */
3501 goto out;
3502 }
3503
3504 pPluginDirEntry = (PRTDIRENTRYEX)RTMemAllocZ(sizeof(RTDIRENTRYEX));
3505 if (!pPluginDirEntry)
3506 {
3507 rc = VERR_NO_MEMORY;
3508 goto out;
3509 }
3510
3511 while ((rc = RTDirReadEx(pPluginDir, pPluginDirEntry, &cbPluginDirEntry, RTFSOBJATTRADD_NOTHING, RTPATH_F_ON_LINK)) != VERR_NO_MORE_FILES)
3512 {
3513 RTLDRMOD hPlugin = NIL_RTLDRMOD;
3514 PFNVDCACHEFORMATLOAD pfnVDCacheLoad = NULL;
3515 PVDCACHEBACKEND pBackend = NULL;
3516 char *pszPluginPath = NULL;
3517
3518 if (rc == VERR_BUFFER_OVERFLOW)
3519 {
3520 /* allocate new buffer. */
3521 RTMemFree(pPluginDirEntry);
3522 pPluginDirEntry = (PRTDIRENTRYEX)RTMemAllocZ(cbPluginDirEntry);
3523 if (!pPluginDirEntry)
3524 {
3525 rc = VERR_NO_MEMORY;
3526 break;
3527 }
3528 /* Retry. */
3529 rc = RTDirReadEx(pPluginDir, pPluginDirEntry, &cbPluginDirEntry, RTFSOBJATTRADD_NOTHING, RTPATH_F_ON_LINK);
3530 if (RT_FAILURE(rc))
3531 break;
3532 }
3533 else if (RT_FAILURE(rc))
3534 break;
3535
3536 /* We got the new entry. */
3537 if (!RTFS_IS_FILE(pPluginDirEntry->Info.Attr.fMode))
3538 continue;
3539
3540 /* Prepend the path to the libraries. */
3541 pszPluginPath = RTPathJoinA(szPath, pPluginDirEntry->szName);
3542 if (!pszPluginPath)
3543 {
3544 rc = VERR_NO_STR_MEMORY;
3545 break;
3546 }
3547
3548 rc = SUPR3HardenedLdrLoadPlugIn(pszPluginPath, &hPlugin, NULL);
3549 if (RT_SUCCESS(rc))
3550 {
3551 rc = RTLdrGetSymbol(hPlugin, VD_CACHEFORMAT_LOAD_NAME, (void**)&pfnVDCacheLoad);
3552 if (RT_FAILURE(rc) || !pfnVDCacheLoad)
3553 {
3554 LogFunc(("error resolving the entry point %s in plugin %s, rc=%Rrc, pfnVDCacheLoad=%#p\n",
3555 VD_CACHEFORMAT_LOAD_NAME, pPluginDirEntry->szName, rc, pfnVDCacheLoad));
3556 if (RT_SUCCESS(rc))
3557 rc = VERR_SYMBOL_NOT_FOUND;
3558 }
3559
3560 if (RT_SUCCESS(rc))
3561 {
3562 /* Get the function table. */
3563 rc = pfnVDCacheLoad(&pBackend);
3564 if (RT_SUCCESS(rc) && pBackend->cbSize == sizeof(VDCACHEBACKEND))
3565 {
3566 pBackend->hPlugin = hPlugin;
3567 vdAddCacheBackend(pBackend);
3568 }
3569 else
3570 LogFunc(("ignored plugin '%s': pBackend->cbSize=%d rc=%Rrc\n", pszPluginPath, pBackend->cbSize, rc));
3571 }
3572 else
3573 LogFunc(("ignored plugin '%s': rc=%Rrc\n", pszPluginPath, rc));
3574
3575 if (RT_FAILURE(rc))
3576 RTLdrClose(hPlugin);
3577 }
3578 RTStrFree(pszPluginPath);
3579 }
3580out:
3581 if (rc == VERR_NO_MORE_FILES)
3582 rc = VINF_SUCCESS;
3583 RTStrFree(pszPluginFilter);
3584 if (pPluginDirEntry)
3585 RTMemFree(pPluginDirEntry);
3586 if (pPluginDir)
3587 RTDirClose(pPluginDir);
3588 return rc;
3589#else
3590 return VINF_SUCCESS;
3591#endif
3592}
3593
3594/**
3595 * VD async I/O interface open callback.
3596 */
3597static int vdIOOpenFallback(void *pvUser, const char *pszLocation,
3598 uint32_t fOpen, PFNVDCOMPLETED pfnCompleted,
3599 void **ppStorage)
3600{
3601 PVDIIOFALLBACKSTORAGE pStorage = (PVDIIOFALLBACKSTORAGE)RTMemAllocZ(sizeof(VDIIOFALLBACKSTORAGE));
3602
3603 if (!pStorage)
3604 return VERR_NO_MEMORY;
3605
3606 pStorage->pfnCompleted = pfnCompleted;
3607
3608 /* Open the file. */
3609 int rc = RTFileOpen(&pStorage->File, pszLocation, fOpen);
3610 if (RT_SUCCESS(rc))
3611 {
3612 *ppStorage = pStorage;
3613 return VINF_SUCCESS;
3614 }
3615
3616 RTMemFree(pStorage);
3617 return rc;
3618}
3619
3620/**
3621 * VD async I/O interface close callback.
3622 */
3623static int vdIOCloseFallback(void *pvUser, void *pvStorage)
3624{
3625 PVDIIOFALLBACKSTORAGE pStorage = (PVDIIOFALLBACKSTORAGE)pvStorage;
3626
3627 RTFileClose(pStorage->File);
3628 RTMemFree(pStorage);
3629 return VINF_SUCCESS;
3630}
3631
3632static int vdIODeleteFallback(void *pvUser, const char *pcszFilename)
3633{
3634 return RTFileDelete(pcszFilename);
3635}
3636
3637static int vdIOMoveFallback(void *pvUser, const char *pcszSrc, const char *pcszDst, unsigned fMove)
3638{
3639 return RTFileMove(pcszSrc, pcszDst, fMove);
3640}
3641
3642static int vdIOGetFreeSpaceFallback(void *pvUser, const char *pcszFilename, int64_t *pcbFreeSpace)
3643{
3644 return RTFsQuerySizes(pcszFilename, NULL, pcbFreeSpace, NULL, NULL);
3645}
3646
3647static int vdIOGetModificationTimeFallback(void *pvUser, const char *pcszFilename, PRTTIMESPEC pModificationTime)
3648{
3649 RTFSOBJINFO info;
3650 int rc = RTPathQueryInfo(pcszFilename, &info, RTFSOBJATTRADD_NOTHING);
3651 if (RT_SUCCESS(rc))
3652 *pModificationTime = info.ModificationTime;
3653 return rc;
3654}
3655
3656/**
3657 * VD async I/O interface callback for retrieving the file size.
3658 */
3659static int vdIOGetSizeFallback(void *pvUser, void *pvStorage, uint64_t *pcbSize)
3660{
3661 PVDIIOFALLBACKSTORAGE pStorage = (PVDIIOFALLBACKSTORAGE)pvStorage;
3662
3663 return RTFileGetSize(pStorage->File, pcbSize);
3664}
3665
3666/**
3667 * VD async I/O interface callback for setting the file size.
3668 */
3669static int vdIOSetSizeFallback(void *pvUser, void *pvStorage, uint64_t cbSize)
3670{
3671 PVDIIOFALLBACKSTORAGE pStorage = (PVDIIOFALLBACKSTORAGE)pvStorage;
3672
3673 return RTFileSetSize(pStorage->File, cbSize);
3674}
3675
3676/**
3677 * VD async I/O interface callback for a synchronous write to the file.
3678 */
3679static int vdIOWriteSyncFallback(void *pvUser, void *pvStorage, uint64_t uOffset,
3680 const void *pvBuf, size_t cbWrite, size_t *pcbWritten)
3681{
3682 PVDIIOFALLBACKSTORAGE pStorage = (PVDIIOFALLBACKSTORAGE)pvStorage;
3683
3684 return RTFileWriteAt(pStorage->File, uOffset, pvBuf, cbWrite, pcbWritten);
3685}
3686
3687/**
3688 * VD async I/O interface callback for a synchronous read from the file.
3689 */
3690static int vdIOReadSyncFallback(void *pvUser, void *pvStorage, uint64_t uOffset,
3691 void *pvBuf, size_t cbRead, size_t *pcbRead)
3692{
3693 PVDIIOFALLBACKSTORAGE pStorage = (PVDIIOFALLBACKSTORAGE)pvStorage;
3694
3695 return RTFileReadAt(pStorage->File, uOffset, pvBuf, cbRead, pcbRead);
3696}
3697
3698/**
3699 * VD async I/O interface callback for a synchronous flush of the file data.
3700 */
3701static int vdIOFlushSyncFallback(void *pvUser, void *pvStorage)
3702{
3703 PVDIIOFALLBACKSTORAGE pStorage = (PVDIIOFALLBACKSTORAGE)pvStorage;
3704
3705 return RTFileFlush(pStorage->File);
3706}
3707
3708/**
3709 * VD async I/O interface callback for a asynchronous read from the file.
3710 */
3711static int vdIOReadAsyncFallback(void *pvUser, void *pStorage, uint64_t uOffset,
3712 PCRTSGSEG paSegments, size_t cSegments,
3713 size_t cbRead, void *pvCompletion,
3714 void **ppTask)
3715{
3716 return VERR_NOT_IMPLEMENTED;
3717}
3718
3719/**
3720 * VD async I/O interface callback for a asynchronous write to the file.
3721 */
3722static int vdIOWriteAsyncFallback(void *pvUser, void *pStorage, uint64_t uOffset,
3723 PCRTSGSEG paSegments, size_t cSegments,
3724 size_t cbWrite, void *pvCompletion,
3725 void **ppTask)
3726{
3727 return VERR_NOT_IMPLEMENTED;
3728}
3729
3730/**
3731 * VD async I/O interface callback for a asynchronous flush of the file data.
3732 */
3733static int vdIOFlushAsyncFallback(void *pvUser, void *pStorage,
3734 void *pvCompletion, void **ppTask)
3735{
3736 return VERR_NOT_IMPLEMENTED;
3737}
3738
3739/**
3740 * Internal - Continues an I/O context after
3741 * it was halted because of an active transfer.
3742 */
3743static int vdIoCtxContinue(PVDIOCTX pIoCtx, int rcReq)
3744{
3745 PVBOXHDD pDisk = pIoCtx->pDisk;
3746 int rc = VINF_SUCCESS;
3747
3748 VD_THREAD_IS_CRITSECT_OWNER(pDisk);
3749
3750 if (RT_FAILURE(rcReq))
3751 ASMAtomicCmpXchgS32(&pIoCtx->rcReq, rcReq, VINF_SUCCESS);
3752
3753 if (!pIoCtx->fBlocked)
3754 {
3755 /* Continue the transfer */
3756 rc = vdIoCtxProcess(pIoCtx);
3757
3758 if ( rc == VINF_VD_ASYNC_IO_FINISHED
3759 && ASMAtomicCmpXchgBool(&pIoCtx->fComplete, true, false))
3760 {
3761 LogFlowFunc(("I/O context completed pIoCtx=%#p\n", pIoCtx));
3762 if (pIoCtx->pIoCtxParent)
3763 {
3764 PVDIOCTX pIoCtxParent = pIoCtx->pIoCtxParent;
3765
3766 Assert(!pIoCtxParent->pIoCtxParent);
3767 if (RT_FAILURE(pIoCtx->rcReq))
3768 ASMAtomicCmpXchgS32(&pIoCtxParent->rcReq, pIoCtx->rcReq, VINF_SUCCESS);
3769
3770 ASMAtomicDecU32(&pIoCtxParent->cDataTransfersPending);
3771
3772 if (pIoCtx->enmTxDir == VDIOCTXTXDIR_WRITE)
3773 {
3774 LogFlowFunc(("I/O context transferred %u bytes for the parent pIoCtxParent=%p\n",
3775 pIoCtx->Type.Child.cbTransferParent, pIoCtxParent));
3776
3777 /* Update the parent state. */
3778 Assert(pIoCtxParent->Req.Io.cbTransferLeft >= pIoCtx->Type.Child.cbTransferParent);
3779 ASMAtomicSubU32(&pIoCtxParent->Req.Io.cbTransferLeft, pIoCtx->Type.Child.cbTransferParent);
3780 }
3781 else
3782 Assert(pIoCtx->enmTxDir == VDIOCTXTXDIR_FLUSH);
3783
3784 /*
3785 * A completed child write means that we finished growing the image.
3786 * We have to process any pending writes now.
3787 */
3788 vdIoCtxUnlockDisk(pDisk, pIoCtxParent, false /* fProcessDeferredReqs */);
3789
3790 /* Unblock the parent */
3791 pIoCtxParent->fBlocked = false;
3792
3793 rc = vdIoCtxProcess(pIoCtxParent);
3794
3795 if ( rc == VINF_VD_ASYNC_IO_FINISHED
3796 && ASMAtomicCmpXchgBool(&pIoCtxParent->fComplete, true, false))
3797 {
3798 RTCritSectLeave(&pDisk->CritSect);
3799 LogFlowFunc(("Parent I/O context completed pIoCtxParent=%#p rcReq=%Rrc\n", pIoCtxParent, pIoCtxParent->rcReq));
3800 pIoCtxParent->Type.Root.pfnComplete(pIoCtxParent->Type.Root.pvUser1,
3801 pIoCtxParent->Type.Root.pvUser2,
3802 pIoCtxParent->rcReq);
3803 vdThreadFinishWrite(pDisk);
3804 vdIoCtxFree(pDisk, pIoCtxParent);
3805 RTCritSectEnter(&pDisk->CritSect);
3806 }
3807
3808 /* Process any pending writes if the current request didn't caused another growing. */
3809 if ( !RTListIsEmpty(&pDisk->ListWriteLocked)
3810 && !vdIoCtxIsDiskLockOwner(pDisk, pIoCtx))
3811 {
3812 RTLISTNODE ListTmp;
3813
3814 LogFlowFunc(("Before: pNext=%#p pPrev=%#p\n", pDisk->ListWriteLocked.pNext,
3815 pDisk->ListWriteLocked.pPrev));
3816
3817 RTListMove(&ListTmp, &pDisk->ListWriteLocked);
3818
3819 LogFlowFunc(("After: pNext=%#p pPrev=%#p\n", pDisk->ListWriteLocked.pNext,
3820 pDisk->ListWriteLocked.pPrev));
3821
3822 RTCritSectLeave(&pDisk->CritSect);
3823
3824 /* Process the list. */
3825 do
3826 {
3827 PVDIOCTXDEFERRED pDeferred = RTListGetFirst(&ListTmp, VDIOCTXDEFERRED, NodeDeferred);
3828 PVDIOCTX pIoCtxWait = pDeferred->pIoCtx;
3829
3830 AssertPtr(pIoCtxWait);
3831
3832 RTListNodeRemove(&pDeferred->NodeDeferred);
3833 RTMemFree(pDeferred);
3834
3835 Assert(!pIoCtxWait->pIoCtxParent);
3836
3837 pIoCtxWait->fBlocked = false;
3838 LogFlowFunc(("Processing waiting I/O context pIoCtxWait=%#p\n", pIoCtxWait));
3839
3840 rc = vdIoCtxProcess(pIoCtxWait);
3841 if ( rc == VINF_VD_ASYNC_IO_FINISHED
3842 && ASMAtomicCmpXchgBool(&pIoCtxWait->fComplete, true, false))
3843 {
3844 LogFlowFunc(("Waiting I/O context completed pIoCtxWait=%#p\n", pIoCtxWait));
3845 vdThreadFinishWrite(pDisk);
3846 pIoCtxWait->Type.Root.pfnComplete(pIoCtxWait->Type.Root.pvUser1,
3847 pIoCtxWait->Type.Root.pvUser2,
3848 pIoCtxWait->rcReq);
3849 vdIoCtxFree(pDisk, pIoCtxWait);
3850 }
3851 } while (!RTListIsEmpty(&ListTmp));
3852
3853 RTCritSectEnter(&pDisk->CritSect);
3854 }
3855 }
3856 else
3857 {
3858 RTCritSectLeave(&pDisk->CritSect);
3859
3860 if (pIoCtx->enmTxDir == VDIOCTXTXDIR_FLUSH)
3861 {
3862 vdIoCtxUnlockDisk(pDisk, pIoCtx, true /* fProcessDerredReqs */);
3863 vdThreadFinishWrite(pDisk);
3864 }
3865 else if ( pIoCtx->enmTxDir == VDIOCTXTXDIR_WRITE
3866 || pIoCtx->enmTxDir == VDIOCTXTXDIR_DISCARD)
3867 vdThreadFinishWrite(pDisk);
3868 else
3869 {
3870 Assert(pIoCtx->enmTxDir == VDIOCTXTXDIR_READ);
3871 vdThreadFinishRead(pDisk);
3872 }
3873
3874 LogFlowFunc(("I/O context completed pIoCtx=%#p rcReq=%Rrc\n", pIoCtx, pIoCtx->rcReq));
3875 pIoCtx->Type.Root.pfnComplete(pIoCtx->Type.Root.pvUser1,
3876 pIoCtx->Type.Root.pvUser2,
3877 pIoCtx->rcReq);
3878 RTCritSectEnter(&pDisk->CritSect);
3879 }
3880
3881 vdIoCtxFree(pDisk, pIoCtx);
3882 }
3883 }
3884
3885 return VINF_SUCCESS;
3886}
3887
3888/**
3889 * Internal - Called when user transfer completed.
3890 */
3891static int vdUserXferCompleted(PVDIOSTORAGE pIoStorage, PVDIOCTX pIoCtx,
3892 PFNVDXFERCOMPLETED pfnComplete, void *pvUser,
3893 size_t cbTransfer, int rcReq)
3894{
3895 int rc = VINF_SUCCESS;
3896 bool fIoCtxContinue = true;
3897 PVBOXHDD pDisk = pIoCtx->pDisk;
3898
3899 LogFlowFunc(("pIoStorage=%#p pIoCtx=%#p pfnComplete=%#p pvUser=%#p cbTransfer=%zu rcReq=%Rrc\n",
3900 pIoStorage, pIoCtx, pfnComplete, pvUser, cbTransfer, rcReq));
3901
3902 RTCritSectEnter(&pDisk->CritSect);
3903 Assert(pIoCtx->Req.Io.cbTransferLeft >= cbTransfer);
3904 ASMAtomicSubU32(&pIoCtx->Req.Io.cbTransferLeft, cbTransfer);
3905 ASMAtomicDecU32(&pIoCtx->cDataTransfersPending);
3906
3907 if (pfnComplete)
3908 rc = pfnComplete(pIoStorage->pVDIo->pBackendData, pIoCtx, pvUser, rcReq);
3909
3910 if (RT_SUCCESS(rc))
3911 rc = vdIoCtxContinue(pIoCtx, rcReq);
3912 else if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
3913 rc = VINF_SUCCESS;
3914
3915 vdDiskCritSectLeave(pDisk, NULL);
3916
3917 return rc;
3918}
3919
3920/**
3921 * Internal - Called when a meta transfer completed.
3922 */
3923static int vdMetaXferCompleted(PVDIOSTORAGE pIoStorage, PFNVDXFERCOMPLETED pfnComplete, void *pvUser,
3924 PVDMETAXFER pMetaXfer, int rcReq)
3925{
3926 PVBOXHDD pDisk = pIoStorage->pVDIo->pDisk;
3927 RTLISTNODE ListIoCtxWaiting;
3928 bool fFlush;
3929
3930 LogFlowFunc(("pIoStorage=%#p pfnComplete=%#p pvUser=%#p pMetaXfer=%#p rcReq=%Rrc\n",
3931 pIoStorage, pfnComplete, pvUser, pMetaXfer, rcReq));
3932
3933 RTCritSectEnter(&pDisk->CritSect);
3934 fFlush = VDMETAXFER_TXDIR_GET(pMetaXfer->fFlags) == VDMETAXFER_TXDIR_FLUSH;
3935 VDMETAXFER_TXDIR_SET(pMetaXfer->fFlags, VDMETAXFER_TXDIR_NONE);
3936
3937 if (!fFlush)
3938 {
3939 RTListMove(&ListIoCtxWaiting, &pMetaXfer->ListIoCtxWaiting);
3940
3941 if (RT_FAILURE(rcReq))
3942 {
3943 /* Remove from the AVL tree. */
3944 LogFlow(("Removing meta xfer=%#p\n", pMetaXfer));
3945 bool fRemoved = RTAvlrFileOffsetRemove(pIoStorage->pTreeMetaXfers, pMetaXfer->Core.Key) != NULL;
3946 Assert(fRemoved);
3947 RTMemFree(pMetaXfer);
3948 }
3949 else
3950 {
3951 /* Increase the reference counter to make sure it doesn't go away before the last context is processed. */
3952 pMetaXfer->cRefs++;
3953 }
3954 }
3955 else
3956 RTListMove(&ListIoCtxWaiting, &pMetaXfer->ListIoCtxWaiting);
3957
3958 /* Go through the waiting list and continue the I/O contexts. */
3959 while (!RTListIsEmpty(&ListIoCtxWaiting))
3960 {
3961 int rc = VINF_SUCCESS;
3962 bool fContinue = true;
3963 PVDIOCTXDEFERRED pDeferred = RTListGetFirst(&ListIoCtxWaiting, VDIOCTXDEFERRED, NodeDeferred);
3964 PVDIOCTX pIoCtx = pDeferred->pIoCtx;
3965 RTListNodeRemove(&pDeferred->NodeDeferred);
3966
3967 RTMemFree(pDeferred);
3968 ASMAtomicDecU32(&pIoCtx->cMetaTransfersPending);
3969
3970 if (pfnComplete)
3971 rc = pfnComplete(pIoStorage->pVDIo->pBackendData, pIoCtx, pvUser, rcReq);
3972
3973 LogFlow(("Completion callback for I/O context %#p returned %Rrc\n", pIoCtx, rc));
3974
3975 if (RT_SUCCESS(rc))
3976 {
3977 rc = vdIoCtxContinue(pIoCtx, rcReq);
3978 AssertRC(rc);
3979 }
3980 else
3981 Assert(rc == VERR_VD_ASYNC_IO_IN_PROGRESS);
3982 }
3983
3984 /* Remove if not used anymore. */
3985 if (RT_SUCCESS(rcReq) && !fFlush)
3986 {
3987 pMetaXfer->cRefs--;
3988 if (!pMetaXfer->cRefs && RTListIsEmpty(&pMetaXfer->ListIoCtxWaiting))
3989 {
3990 /* Remove from the AVL tree. */
3991 LogFlow(("Removing meta xfer=%#p\n", pMetaXfer));
3992 bool fRemoved = RTAvlrFileOffsetRemove(pIoStorage->pTreeMetaXfers, pMetaXfer->Core.Key) != NULL;
3993 Assert(fRemoved);
3994 RTMemFree(pMetaXfer);
3995 }
3996 }
3997 else if (fFlush)
3998 RTMemFree(pMetaXfer);
3999
4000 vdDiskCritSectLeave(pDisk, NULL);
4001
4002 return VINF_SUCCESS;
4003}
4004
4005static int vdIOIntReqCompleted(void *pvUser, int rcReq)
4006{
4007 int rc = VINF_SUCCESS;
4008 PVDIOTASK pIoTask = (PVDIOTASK)pvUser;
4009 PVDIOSTORAGE pIoStorage = pIoTask->pIoStorage;
4010
4011 LogFlowFunc(("Task completed pIoTask=%#p\n", pIoTask));
4012
4013 if (!pIoTask->fMeta)
4014 rc = vdUserXferCompleted(pIoStorage, pIoTask->Type.User.pIoCtx,
4015 pIoTask->pfnComplete, pIoTask->pvUser,
4016 pIoTask->Type.User.cbTransfer, rcReq);
4017 else
4018 rc = vdMetaXferCompleted(pIoStorage, pIoTask->pfnComplete, pIoTask->pvUser,
4019 pIoTask->Type.Meta.pMetaXfer, rcReq);
4020
4021 vdIoTaskFree(pIoStorage->pVDIo->pDisk, pIoTask);
4022
4023 return rc;
4024}
4025
4026/**
4027 * VD I/O interface callback for opening a file.
4028 */
4029static int vdIOIntOpen(void *pvUser, const char *pszLocation,
4030 unsigned uOpenFlags, PPVDIOSTORAGE ppIoStorage)
4031{
4032 int rc = VINF_SUCCESS;
4033 PVDIO pVDIo = (PVDIO)pvUser;
4034 PVDIOSTORAGE pIoStorage = (PVDIOSTORAGE)RTMemAllocZ(sizeof(VDIOSTORAGE));
4035
4036 if (!pIoStorage)
4037 return VERR_NO_MEMORY;
4038
4039 /* Create the AVl tree. */
4040 pIoStorage->pTreeMetaXfers = (PAVLRFOFFTREE)RTMemAllocZ(sizeof(AVLRFOFFTREE));
4041 if (pIoStorage->pTreeMetaXfers)
4042 {
4043 rc = pVDIo->pInterfaceIo->pfnOpen(pVDIo->pInterfaceIo->Core.pvUser,
4044 pszLocation, uOpenFlags,
4045 vdIOIntReqCompleted,
4046 &pIoStorage->pStorage);
4047 if (RT_SUCCESS(rc))
4048 {
4049 pIoStorage->pVDIo = pVDIo;
4050 *ppIoStorage = pIoStorage;
4051 return VINF_SUCCESS;
4052 }
4053
4054 RTMemFree(pIoStorage->pTreeMetaXfers);
4055 }
4056 else
4057 rc = VERR_NO_MEMORY;
4058
4059 RTMemFree(pIoStorage);
4060 return rc;
4061}
4062
4063static int vdIOIntTreeMetaXferDestroy(PAVLRFOFFNODECORE pNode, void *pvUser)
4064{
4065 AssertMsgFailed(("Tree should be empty at this point!\n"));
4066 return VINF_SUCCESS;
4067}
4068
4069static int vdIOIntClose(void *pvUser, PVDIOSTORAGE pIoStorage)
4070{
4071 PVDIO pVDIo = (PVDIO)pvUser;
4072
4073 int rc = pVDIo->pInterfaceIo->pfnClose(pVDIo->pInterfaceIo->Core.pvUser,
4074 pIoStorage->pStorage);
4075 AssertRC(rc);
4076
4077 RTAvlrFileOffsetDestroy(pIoStorage->pTreeMetaXfers, vdIOIntTreeMetaXferDestroy, NULL);
4078 RTMemFree(pIoStorage->pTreeMetaXfers);
4079 RTMemFree(pIoStorage);
4080 return VINF_SUCCESS;
4081}
4082
4083static int vdIOIntDelete(void *pvUser, const char *pcszFilename)
4084{
4085 PVDIO pVDIo = (PVDIO)pvUser;
4086 return pVDIo->pInterfaceIo->pfnDelete(pVDIo->pInterfaceIo->Core.pvUser,
4087 pcszFilename);
4088}
4089
4090static int vdIOIntMove(void *pvUser, const char *pcszSrc, const char *pcszDst,
4091 unsigned fMove)
4092{
4093 PVDIO pVDIo = (PVDIO)pvUser;
4094 return pVDIo->pInterfaceIo->pfnMove(pVDIo->pInterfaceIo->Core.pvUser,
4095 pcszSrc, pcszDst, fMove);
4096}
4097
4098static int vdIOIntGetFreeSpace(void *pvUser, const char *pcszFilename,
4099 int64_t *pcbFreeSpace)
4100{
4101 PVDIO pVDIo = (PVDIO)pvUser;
4102 return pVDIo->pInterfaceIo->pfnGetFreeSpace(pVDIo->pInterfaceIo->Core.pvUser,
4103 pcszFilename, pcbFreeSpace);
4104}
4105
4106static int vdIOIntGetModificationTime(void *pvUser, const char *pcszFilename,
4107 PRTTIMESPEC pModificationTime)
4108{
4109 PVDIO pVDIo = (PVDIO)pvUser;
4110 return pVDIo->pInterfaceIo->pfnGetModificationTime(pVDIo->pInterfaceIo->Core.pvUser,
4111 pcszFilename, pModificationTime);
4112}
4113
4114static int vdIOIntGetSize(void *pvUser, PVDIOSTORAGE pIoStorage,
4115 uint64_t *pcbSize)
4116{
4117 PVDIO pVDIo = (PVDIO)pvUser;
4118 return pVDIo->pInterfaceIo->pfnGetSize(pVDIo->pInterfaceIo->Core.pvUser,
4119 pIoStorage->pStorage, pcbSize);
4120}
4121
4122static int vdIOIntSetSize(void *pvUser, PVDIOSTORAGE pIoStorage,
4123 uint64_t cbSize)
4124{
4125 PVDIO pVDIo = (PVDIO)pvUser;
4126 return pVDIo->pInterfaceIo->pfnSetSize(pVDIo->pInterfaceIo->Core.pvUser,
4127 pIoStorage->pStorage, cbSize);
4128}
4129
4130static int vdIOIntWriteSync(void *pvUser, PVDIOSTORAGE pIoStorage,
4131 uint64_t uOffset, const void *pvBuf,
4132 size_t cbWrite, size_t *pcbWritten)
4133{
4134 PVDIO pVDIo = (PVDIO)pvUser;
4135 return pVDIo->pInterfaceIo->pfnWriteSync(pVDIo->pInterfaceIo->Core.pvUser,
4136 pIoStorage->pStorage, uOffset,
4137 pvBuf, cbWrite, pcbWritten);
4138}
4139
4140static int vdIOIntReadSync(void *pvUser, PVDIOSTORAGE pIoStorage,
4141 uint64_t uOffset, void *pvBuf, size_t cbRead,
4142 size_t *pcbRead)
4143{
4144 PVDIO pVDIo = (PVDIO)pvUser;
4145 return pVDIo->pInterfaceIo->pfnReadSync(pVDIo->pInterfaceIo->Core.pvUser,
4146 pIoStorage->pStorage, uOffset,
4147 pvBuf, cbRead, pcbRead);
4148}
4149
4150static int vdIOIntFlushSync(void *pvUser, PVDIOSTORAGE pIoStorage)
4151{
4152 int rc = VINF_SUCCESS;
4153 PVDIO pVDIo = (PVDIO)pvUser;
4154
4155 if (!pVDIo->fIgnoreFlush)
4156 rc = pVDIo->pInterfaceIo->pfnFlushSync(pVDIo->pInterfaceIo->Core.pvUser,
4157 pIoStorage->pStorage);
4158
4159 return rc;
4160}
4161
4162static int vdIOIntReadUserAsync(void *pvUser, PVDIOSTORAGE pIoStorage,
4163 uint64_t uOffset, PVDIOCTX pIoCtx,
4164 size_t cbRead)
4165{
4166 int rc = VINF_SUCCESS;
4167 PVDIO pVDIo = (PVDIO)pvUser;
4168 PVBOXHDD pDisk = pVDIo->pDisk;
4169
4170 LogFlowFunc(("pvUser=%#p pIoStorage=%#p uOffset=%llu pIoCtx=%#p cbRead=%u\n",
4171 pvUser, pIoStorage, uOffset, pIoCtx, cbRead));
4172
4173 VD_THREAD_IS_CRITSECT_OWNER(pDisk);
4174
4175 Assert(cbRead > 0);
4176
4177 /* Build the S/G array and spawn a new I/O task */
4178 while (cbRead)
4179 {
4180 RTSGSEG aSeg[VD_IO_TASK_SEGMENTS_MAX];
4181 unsigned cSegments = VD_IO_TASK_SEGMENTS_MAX;
4182 size_t cbTaskRead = 0;
4183
4184 cbTaskRead = RTSgBufSegArrayCreate(&pIoCtx->Req.Io.SgBuf, aSeg, &cSegments, cbRead);
4185
4186 Assert(cSegments > 0);
4187 Assert(cbTaskRead > 0);
4188 AssertMsg(cbTaskRead <= cbRead, ("Invalid number of bytes to read\n"));
4189
4190 LogFlow(("Reading %u bytes into %u segments\n", cbTaskRead, cSegments));
4191
4192#ifdef RT_STRICT
4193 for (unsigned i = 0; i < cSegments; i++)
4194 AssertMsg(aSeg[i].pvSeg && !(aSeg[i].cbSeg % 512),
4195 ("Segment %u is invalid\n", i));
4196#endif
4197
4198 PVDIOTASK pIoTask = vdIoTaskUserAlloc(pIoStorage, NULL, NULL, pIoCtx, cbTaskRead);
4199
4200 if (!pIoTask)
4201 return VERR_NO_MEMORY;
4202
4203 ASMAtomicIncU32(&pIoCtx->cDataTransfersPending);
4204
4205 void *pvTask;
4206 rc = pVDIo->pInterfaceIo->pfnReadAsync(pVDIo->pInterfaceIo->Core.pvUser,
4207 pIoStorage->pStorage, uOffset,
4208 aSeg, cSegments, cbTaskRead, pIoTask,
4209 &pvTask);
4210 if (RT_SUCCESS(rc))
4211 {
4212 AssertMsg(cbTaskRead <= pIoCtx->Req.Io.cbTransferLeft, ("Impossible!\n"));
4213 ASMAtomicSubU32(&pIoCtx->Req.Io.cbTransferLeft, cbTaskRead);
4214 ASMAtomicDecU32(&pIoCtx->cDataTransfersPending);
4215 vdIoTaskFree(pDisk, pIoTask);
4216 }
4217 else if (rc != VERR_VD_ASYNC_IO_IN_PROGRESS)
4218 {
4219 ASMAtomicDecU32(&pIoCtx->cDataTransfersPending);
4220 vdIoTaskFree(pDisk, pIoTask);
4221 break;
4222 }
4223
4224 uOffset += cbTaskRead;
4225 cbRead -= cbTaskRead;
4226 }
4227
4228 LogFlowFunc(("returns rc=%Rrc\n", rc));
4229 return rc;
4230}
4231
4232static int vdIOIntWriteUserAsync(void *pvUser, PVDIOSTORAGE pIoStorage,
4233 uint64_t uOffset, PVDIOCTX pIoCtx,
4234 size_t cbWrite,
4235 PFNVDXFERCOMPLETED pfnComplete,
4236 void *pvCompleteUser)
4237{
4238 int rc = VINF_SUCCESS;
4239 PVDIO pVDIo = (PVDIO)pvUser;
4240 PVBOXHDD pDisk = pVDIo->pDisk;
4241
4242 LogFlowFunc(("pvUser=%#p pIoStorage=%#p uOffset=%llu pIoCtx=%#p cbWrite=%u\n",
4243 pvUser, pIoStorage, uOffset, pIoCtx, cbWrite));
4244
4245 VD_THREAD_IS_CRITSECT_OWNER(pDisk);
4246
4247 Assert(cbWrite > 0);
4248
4249 /* Build the S/G array and spawn a new I/O task */
4250 while (cbWrite)
4251 {
4252 RTSGSEG aSeg[VD_IO_TASK_SEGMENTS_MAX];
4253 unsigned cSegments = VD_IO_TASK_SEGMENTS_MAX;
4254 size_t cbTaskWrite = 0;
4255
4256 cbTaskWrite = RTSgBufSegArrayCreate(&pIoCtx->Req.Io.SgBuf, aSeg, &cSegments, cbWrite);
4257
4258 Assert(cSegments > 0);
4259 Assert(cbTaskWrite > 0);
4260 AssertMsg(cbTaskWrite <= cbWrite, ("Invalid number of bytes to write\n"));
4261
4262 LogFlow(("Writing %u bytes from %u segments\n", cbTaskWrite, cSegments));
4263
4264#ifdef DEBUG
4265 for (unsigned i = 0; i < cSegments; i++)
4266 AssertMsg(aSeg[i].pvSeg && !(aSeg[i].cbSeg % 512),
4267 ("Segment %u is invalid\n", i));
4268#endif
4269
4270 PVDIOTASK pIoTask = vdIoTaskUserAlloc(pIoStorage, pfnComplete, pvCompleteUser, pIoCtx, cbTaskWrite);
4271
4272 if (!pIoTask)
4273 return VERR_NO_MEMORY;
4274
4275 ASMAtomicIncU32(&pIoCtx->cDataTransfersPending);
4276
4277 void *pvTask;
4278 rc = pVDIo->pInterfaceIo->pfnWriteAsync(pVDIo->pInterfaceIo->Core.pvUser,
4279 pIoStorage->pStorage,
4280 uOffset, aSeg, cSegments,
4281 cbTaskWrite, pIoTask, &pvTask);
4282 if (RT_SUCCESS(rc))
4283 {
4284 AssertMsg(cbTaskWrite <= pIoCtx->Req.Io.cbTransferLeft, ("Impossible!\n"));
4285 ASMAtomicSubU32(&pIoCtx->Req.Io.cbTransferLeft, cbTaskWrite);
4286 ASMAtomicDecU32(&pIoCtx->cDataTransfersPending);
4287 vdIoTaskFree(pDisk, pIoTask);
4288 }
4289 else if (rc != VERR_VD_ASYNC_IO_IN_PROGRESS)
4290 {
4291 ASMAtomicDecU32(&pIoCtx->cDataTransfersPending);
4292 vdIoTaskFree(pDisk, pIoTask);
4293 break;
4294 }
4295
4296 uOffset += cbTaskWrite;
4297 cbWrite -= cbTaskWrite;
4298 }
4299
4300 return rc;
4301}
4302
4303static int vdIOIntReadMetaAsync(void *pvUser, PVDIOSTORAGE pIoStorage,
4304 uint64_t uOffset, void *pvBuf,
4305 size_t cbRead, PVDIOCTX pIoCtx,
4306 PPVDMETAXFER ppMetaXfer,
4307 PFNVDXFERCOMPLETED pfnComplete,
4308 void *pvCompleteUser)
4309{
4310 PVDIO pVDIo = (PVDIO)pvUser;
4311 PVBOXHDD pDisk = pVDIo->pDisk;
4312 int rc = VINF_SUCCESS;
4313 RTSGSEG Seg;
4314 PVDIOTASK pIoTask;
4315 PVDMETAXFER pMetaXfer = NULL;
4316 void *pvTask = NULL;
4317
4318 LogFlowFunc(("pvUser=%#p pIoStorage=%#p uOffset=%llu pvBuf=%#p cbRead=%u\n",
4319 pvUser, pIoStorage, uOffset, pvBuf, cbRead));
4320
4321 VD_THREAD_IS_CRITSECT_OWNER(pDisk);
4322
4323 pMetaXfer = (PVDMETAXFER)RTAvlrFileOffsetGet(pIoStorage->pTreeMetaXfers, uOffset);
4324 if (!pMetaXfer)
4325 {
4326#ifdef RT_STRICT
4327 pMetaXfer = (PVDMETAXFER)RTAvlrFileOffsetGetBestFit(pIoStorage->pTreeMetaXfers, uOffset, false /* fAbove */);
4328 AssertMsg(!pMetaXfer || (pMetaXfer->Core.Key + (RTFOFF)pMetaXfer->cbMeta <= (RTFOFF)uOffset),
4329 ("Overlapping meta transfers!\n"));
4330#endif
4331
4332 /* Allocate a new meta transfer. */
4333 pMetaXfer = vdMetaXferAlloc(pIoStorage, uOffset, cbRead);
4334 if (!pMetaXfer)
4335 return VERR_NO_MEMORY;
4336
4337 pIoTask = vdIoTaskMetaAlloc(pIoStorage, pfnComplete, pvCompleteUser, pMetaXfer);
4338 if (!pIoTask)
4339 {
4340 RTMemFree(pMetaXfer);
4341 return VERR_NO_MEMORY;
4342 }
4343
4344 Seg.cbSeg = cbRead;
4345 Seg.pvSeg = pMetaXfer->abData;
4346
4347 VDMETAXFER_TXDIR_SET(pMetaXfer->fFlags, VDMETAXFER_TXDIR_READ);
4348 rc = pVDIo->pInterfaceIo->pfnReadAsync(pVDIo->pInterfaceIo->Core.pvUser,
4349 pIoStorage->pStorage,
4350 uOffset, &Seg, 1,
4351 cbRead, pIoTask, &pvTask);
4352
4353 if (RT_SUCCESS(rc) || rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
4354 {
4355 bool fInserted = RTAvlrFileOffsetInsert(pIoStorage->pTreeMetaXfers, &pMetaXfer->Core);
4356 Assert(fInserted);
4357 }
4358 else
4359 RTMemFree(pMetaXfer);
4360
4361 if (RT_SUCCESS(rc))
4362 {
4363 VDMETAXFER_TXDIR_SET(pMetaXfer->fFlags, VDMETAXFER_TXDIR_NONE);
4364 vdIoTaskFree(pDisk, pIoTask);
4365 }
4366 else if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS && !pfnComplete)
4367 rc = VERR_VD_NOT_ENOUGH_METADATA;
4368 }
4369
4370 Assert(VALID_PTR(pMetaXfer) || RT_FAILURE(rc));
4371
4372 if (RT_SUCCESS(rc) || rc == VERR_VD_NOT_ENOUGH_METADATA || rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
4373 {
4374 /* If it is pending add the request to the list. */
4375 if (VDMETAXFER_TXDIR_GET(pMetaXfer->fFlags) == VDMETAXFER_TXDIR_READ)
4376 {
4377 PVDIOCTXDEFERRED pDeferred = (PVDIOCTXDEFERRED)RTMemAllocZ(sizeof(VDIOCTXDEFERRED));
4378 AssertPtr(pDeferred);
4379
4380 RTListInit(&pDeferred->NodeDeferred);
4381 pDeferred->pIoCtx = pIoCtx;
4382
4383 ASMAtomicIncU32(&pIoCtx->cMetaTransfersPending);
4384 RTListAppend(&pMetaXfer->ListIoCtxWaiting, &pDeferred->NodeDeferred);
4385 rc = VERR_VD_NOT_ENOUGH_METADATA;
4386 }
4387 else
4388 {
4389 /* Transfer the data. */
4390 pMetaXfer->cRefs++;
4391 Assert(pMetaXfer->cbMeta >= cbRead);
4392 Assert(pMetaXfer->Core.Key == (RTFOFF)uOffset);
4393 memcpy(pvBuf, pMetaXfer->abData, cbRead);
4394 *ppMetaXfer = pMetaXfer;
4395 }
4396 }
4397
4398 return rc;
4399}
4400
4401static int vdIOIntWriteMetaAsync(void *pvUser, PVDIOSTORAGE pIoStorage,
4402 uint64_t uOffset, void *pvBuf,
4403 size_t cbWrite, PVDIOCTX pIoCtx,
4404 PFNVDXFERCOMPLETED pfnComplete,
4405 void *pvCompleteUser)
4406{
4407 PVDIO pVDIo = (PVDIO)pvUser;
4408 PVBOXHDD pDisk = pVDIo->pDisk;
4409 int rc = VINF_SUCCESS;
4410 RTSGSEG Seg;
4411 PVDIOTASK pIoTask;
4412 PVDMETAXFER pMetaXfer = NULL;
4413 bool fInTree = false;
4414 void *pvTask = NULL;
4415
4416 LogFlowFunc(("pvUser=%#p pIoStorage=%#p uOffset=%llu pvBuf=%#p cbWrite=%u\n",
4417 pvUser, pIoStorage, uOffset, pvBuf, cbWrite));
4418
4419 VD_THREAD_IS_CRITSECT_OWNER(pDisk);
4420
4421 pMetaXfer = (PVDMETAXFER)RTAvlrFileOffsetGet(pIoStorage->pTreeMetaXfers, uOffset);
4422 if (!pMetaXfer)
4423 {
4424 /* Allocate a new meta transfer. */
4425 pMetaXfer = vdMetaXferAlloc(pIoStorage, uOffset, cbWrite);
4426 if (!pMetaXfer)
4427 return VERR_NO_MEMORY;
4428 }
4429 else
4430 {
4431 Assert(pMetaXfer->cbMeta >= cbWrite);
4432 Assert(pMetaXfer->Core.Key == (RTFOFF)uOffset);
4433 fInTree = true;
4434 }
4435
4436 Assert(VDMETAXFER_TXDIR_GET(pMetaXfer->fFlags) == VDMETAXFER_TXDIR_NONE);
4437
4438 pIoTask = vdIoTaskMetaAlloc(pIoStorage, pfnComplete, pvCompleteUser, pMetaXfer);
4439 if (!pIoTask)
4440 {
4441 RTMemFree(pMetaXfer);
4442 return VERR_NO_MEMORY;
4443 }
4444
4445 memcpy(pMetaXfer->abData, pvBuf, cbWrite);
4446 Seg.cbSeg = cbWrite;
4447 Seg.pvSeg = pMetaXfer->abData;
4448
4449 ASMAtomicIncU32(&pIoCtx->cMetaTransfersPending);
4450
4451 VDMETAXFER_TXDIR_SET(pMetaXfer->fFlags, VDMETAXFER_TXDIR_WRITE);
4452 rc = pVDIo->pInterfaceIo->pfnWriteAsync(pVDIo->pInterfaceIo->Core.pvUser,
4453 pIoStorage->pStorage,
4454 uOffset, &Seg, 1, cbWrite, pIoTask,
4455 &pvTask);
4456 if (RT_SUCCESS(rc))
4457 {
4458 VDMETAXFER_TXDIR_SET(pMetaXfer->fFlags, VDMETAXFER_TXDIR_NONE);
4459 ASMAtomicDecU32(&pIoCtx->cMetaTransfersPending);
4460 vdIoTaskFree(pDisk, pIoTask);
4461 if (fInTree && !pMetaXfer->cRefs)
4462 {
4463 LogFlow(("Removing meta xfer=%#p\n", pMetaXfer));
4464 bool fRemoved = RTAvlrFileOffsetRemove(pIoStorage->pTreeMetaXfers, pMetaXfer->Core.Key) != NULL;
4465 AssertMsg(fRemoved, ("Metadata transfer wasn't removed\n"));
4466 RTMemFree(pMetaXfer);
4467 pMetaXfer = NULL;
4468 }
4469 }
4470 else if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
4471 {
4472 PVDIOCTXDEFERRED pDeferred = (PVDIOCTXDEFERRED)RTMemAllocZ(sizeof(VDIOCTXDEFERRED));
4473 AssertPtr(pDeferred);
4474
4475 RTListInit(&pDeferred->NodeDeferred);
4476 pDeferred->pIoCtx = pIoCtx;
4477
4478 if (!fInTree)
4479 {
4480 bool fInserted = RTAvlrFileOffsetInsert(pIoStorage->pTreeMetaXfers, &pMetaXfer->Core);
4481 Assert(fInserted);
4482 }
4483
4484 RTListAppend(&pMetaXfer->ListIoCtxWaiting, &pDeferred->NodeDeferred);
4485 }
4486 else
4487 {
4488 RTMemFree(pMetaXfer);
4489 pMetaXfer = NULL;
4490 }
4491
4492 return rc;
4493}
4494
4495static void vdIOIntMetaXferRelease(void *pvUser, PVDMETAXFER pMetaXfer)
4496{
4497 PVDIO pVDIo = (PVDIO)pvUser;
4498 PVBOXHDD pDisk = pVDIo->pDisk;
4499 PVDIOSTORAGE pIoStorage = pMetaXfer->pIoStorage;
4500
4501 VD_THREAD_IS_CRITSECT_OWNER(pDisk);
4502
4503 Assert( VDMETAXFER_TXDIR_GET(pMetaXfer->fFlags) == VDMETAXFER_TXDIR_NONE
4504 || VDMETAXFER_TXDIR_GET(pMetaXfer->fFlags) == VDMETAXFER_TXDIR_WRITE);
4505 Assert(pMetaXfer->cRefs > 0);
4506
4507 pMetaXfer->cRefs--;
4508 if ( !pMetaXfer->cRefs
4509 && RTListIsEmpty(&pMetaXfer->ListIoCtxWaiting)
4510 && VDMETAXFER_TXDIR_GET(pMetaXfer->fFlags) == VDMETAXFER_TXDIR_NONE)
4511 {
4512 /* Free the meta data entry. */
4513 LogFlow(("Removing meta xfer=%#p\n", pMetaXfer));
4514 bool fRemoved = RTAvlrFileOffsetRemove(pIoStorage->pTreeMetaXfers, pMetaXfer->Core.Key) != NULL;
4515 AssertMsg(fRemoved, ("Metadata transfer wasn't removed\n"));
4516
4517 RTMemFree(pMetaXfer);
4518 }
4519}
4520
4521static int vdIOIntFlushAsync(void *pvUser, PVDIOSTORAGE pIoStorage,
4522 PVDIOCTX pIoCtx, PFNVDXFERCOMPLETED pfnComplete,
4523 void *pvCompleteUser)
4524{
4525 PVDIO pVDIo = (PVDIO)pvUser;
4526 PVBOXHDD pDisk = pVDIo->pDisk;
4527 int rc = VINF_SUCCESS;
4528 PVDIOTASK pIoTask;
4529 PVDMETAXFER pMetaXfer = NULL;
4530 void *pvTask = NULL;
4531
4532 VD_THREAD_IS_CRITSECT_OWNER(pDisk);
4533
4534 LogFlowFunc(("pvUser=%#p pIoStorage=%#p pIoCtx=%#p\n",
4535 pvUser, pIoStorage, pIoCtx));
4536
4537 if (pVDIo->fIgnoreFlush)
4538 return VINF_SUCCESS;
4539
4540 /* Allocate a new meta transfer. */
4541 pMetaXfer = vdMetaXferAlloc(pIoStorage, 0, 0);
4542 if (!pMetaXfer)
4543 return VERR_NO_MEMORY;
4544
4545 pIoTask = vdIoTaskMetaAlloc(pIoStorage, pfnComplete, pvUser, pMetaXfer);
4546 if (!pIoTask)
4547 {
4548 RTMemFree(pMetaXfer);
4549 return VERR_NO_MEMORY;
4550 }
4551
4552 ASMAtomicIncU32(&pIoCtx->cMetaTransfersPending);
4553
4554 PVDIOCTXDEFERRED pDeferred = (PVDIOCTXDEFERRED)RTMemAllocZ(sizeof(VDIOCTXDEFERRED));
4555 AssertPtr(pDeferred);
4556
4557 RTListInit(&pDeferred->NodeDeferred);
4558 pDeferred->pIoCtx = pIoCtx;
4559
4560 RTListAppend(&pMetaXfer->ListIoCtxWaiting, &pDeferred->NodeDeferred);
4561 VDMETAXFER_TXDIR_SET(pMetaXfer->fFlags, VDMETAXFER_TXDIR_FLUSH);
4562 rc = pVDIo->pInterfaceIo->pfnFlushAsync(pVDIo->pInterfaceIo->Core.pvUser,
4563 pIoStorage->pStorage,
4564 pIoTask, &pvTask);
4565 if (RT_SUCCESS(rc))
4566 {
4567 VDMETAXFER_TXDIR_SET(pMetaXfer->fFlags, VDMETAXFER_TXDIR_NONE);
4568 ASMAtomicDecU32(&pIoCtx->cMetaTransfersPending);
4569 vdIoTaskFree(pDisk, pIoTask);
4570 RTMemFree(pDeferred);
4571 RTMemFree(pMetaXfer);
4572 }
4573 else if (rc != VERR_VD_ASYNC_IO_IN_PROGRESS)
4574 RTMemFree(pMetaXfer);
4575
4576 return rc;
4577}
4578
4579static size_t vdIOIntIoCtxCopyTo(void *pvUser, PVDIOCTX pIoCtx,
4580 void *pvBuf, size_t cbBuf)
4581{
4582 PVDIO pVDIo = (PVDIO)pvUser;
4583 PVBOXHDD pDisk = pVDIo->pDisk;
4584 size_t cbCopied = 0;
4585
4586 VD_THREAD_IS_CRITSECT_OWNER(pDisk);
4587
4588 cbCopied = vdIoCtxCopyTo(pIoCtx, (uint8_t *)pvBuf, cbBuf);
4589 Assert(cbCopied == cbBuf);
4590
4591 ASMAtomicSubU32(&pIoCtx->Req.Io.cbTransferLeft, cbCopied);
4592
4593 return cbCopied;
4594}
4595
4596static size_t vdIOIntIoCtxCopyFrom(void *pvUser, PVDIOCTX pIoCtx,
4597 void *pvBuf, size_t cbBuf)
4598{
4599 PVDIO pVDIo = (PVDIO)pvUser;
4600 PVBOXHDD pDisk = pVDIo->pDisk;
4601 size_t cbCopied = 0;
4602
4603 VD_THREAD_IS_CRITSECT_OWNER(pDisk);
4604
4605 cbCopied = vdIoCtxCopyFrom(pIoCtx, (uint8_t *)pvBuf, cbBuf);
4606 Assert(cbCopied == cbBuf);
4607
4608 ASMAtomicSubU32(&pIoCtx->Req.Io.cbTransferLeft, cbCopied);
4609
4610 return cbCopied;
4611}
4612
4613static size_t vdIOIntIoCtxSet(void *pvUser, PVDIOCTX pIoCtx, int ch, size_t cb)
4614{
4615 PVDIO pVDIo = (PVDIO)pvUser;
4616 PVBOXHDD pDisk = pVDIo->pDisk;
4617 size_t cbSet = 0;
4618
4619 VD_THREAD_IS_CRITSECT_OWNER(pDisk);
4620
4621 cbSet = vdIoCtxSet(pIoCtx, ch, cb);
4622 Assert(cbSet == cb);
4623
4624 ASMAtomicSubU32(&pIoCtx->Req.Io.cbTransferLeft, cbSet);
4625
4626 return cbSet;
4627}
4628
4629static size_t vdIOIntIoCtxSegArrayCreate(void *pvUser, PVDIOCTX pIoCtx,
4630 PRTSGSEG paSeg, unsigned *pcSeg,
4631 size_t cbData)
4632{
4633 PVDIO pVDIo = (PVDIO)pvUser;
4634 PVBOXHDD pDisk = pVDIo->pDisk;
4635 size_t cbCreated = 0;
4636
4637 VD_THREAD_IS_CRITSECT_OWNER(pDisk);
4638
4639 cbCreated = RTSgBufSegArrayCreate(&pIoCtx->Req.Io.SgBuf, paSeg, pcSeg, cbData);
4640 Assert(!paSeg || cbData == cbCreated);
4641
4642 return cbCreated;
4643}
4644
4645static void vdIOIntIoCtxCompleted(void *pvUser, PVDIOCTX pIoCtx, int rcReq,
4646 size_t cbCompleted)
4647{
4648 PVDIO pVDIo = (PVDIO)pvUser;
4649 PVBOXHDD pDisk = pVDIo->pDisk;
4650
4651 /*
4652 * Grab the disk critical section to avoid races with other threads which
4653 * might still modify the I/O context.
4654 * Example is that iSCSI is doing an asynchronous write but calls us already
4655 * while the other thread is still hanging in vdWriteHelperAsync and couldn't update
4656 * the fBlocked state yet.
4657 * It can overwrite the state to true before we call vdIoCtxContinue and the
4658 * the request would hang indefinite.
4659 */
4660 int rc = RTCritSectEnter(&pDisk->CritSect);
4661 AssertRC(rc);
4662
4663 /* Continue */
4664 pIoCtx->fBlocked = false;
4665 ASMAtomicSubU32(&pIoCtx->Req.Io.cbTransferLeft, cbCompleted);
4666
4667 /* Clear the pointer to next transfer function in case we have nothing to transfer anymore.
4668 * @todo: Find a better way to prevent vdIoCtxContinue from calling the read/write helper again. */
4669 if (!pIoCtx->Req.Io.cbTransferLeft)
4670 pIoCtx->pfnIoCtxTransfer = NULL;
4671
4672 vdIoCtxContinue(pIoCtx, rcReq);
4673
4674 vdDiskCritSectLeave(pDisk, NULL);
4675}
4676
4677/**
4678 * VD I/O interface callback for opening a file (limited version for VDGetFormat).
4679 */
4680static int vdIOIntOpenLimited(void *pvUser, const char *pszLocation,
4681 uint32_t fOpen, PPVDIOSTORAGE ppIoStorage)
4682{
4683 int rc = VINF_SUCCESS;
4684 PVDINTERFACEIO pInterfaceIo = (PVDINTERFACEIO)pvUser;
4685 PVDIOSTORAGE pIoStorage = (PVDIOSTORAGE)RTMemAllocZ(sizeof(VDIOSTORAGE));
4686
4687 if (!pIoStorage)
4688 return VERR_NO_MEMORY;
4689
4690 rc = pInterfaceIo->pfnOpen(NULL, pszLocation, fOpen, NULL, &pIoStorage->pStorage);
4691 if (RT_SUCCESS(rc))
4692 *ppIoStorage = pIoStorage;
4693 else
4694 RTMemFree(pIoStorage);
4695
4696 return rc;
4697}
4698
4699static int vdIOIntCloseLimited(void *pvUser, PVDIOSTORAGE pIoStorage)
4700{
4701 PVDINTERFACEIO pInterfaceIo = (PVDINTERFACEIO)pvUser;
4702 int rc = pInterfaceIo->pfnClose(NULL, pIoStorage->pStorage);
4703 AssertRC(rc);
4704
4705 RTMemFree(pIoStorage);
4706 return VINF_SUCCESS;
4707}
4708
4709static int vdIOIntDeleteLimited(void *pvUser, const char *pcszFilename)
4710{
4711 PVDINTERFACEIO pInterfaceIo = (PVDINTERFACEIO)pvUser;
4712 return pInterfaceIo->pfnDelete(NULL, pcszFilename);
4713}
4714
4715static int vdIOIntMoveLimited(void *pvUser, const char *pcszSrc,
4716 const char *pcszDst, unsigned fMove)
4717{
4718 PVDINTERFACEIO pInterfaceIo = (PVDINTERFACEIO)pvUser;
4719 return pInterfaceIo->pfnMove(NULL, pcszSrc, pcszDst, fMove);
4720}
4721
4722static int vdIOIntGetFreeSpaceLimited(void *pvUser, const char *pcszFilename,
4723 int64_t *pcbFreeSpace)
4724{
4725 PVDINTERFACEIO pInterfaceIo = (PVDINTERFACEIO)pvUser;
4726 return pInterfaceIo->pfnGetFreeSpace(NULL, pcszFilename, pcbFreeSpace);
4727}
4728
4729static int vdIOIntGetModificationTimeLimited(void *pvUser,
4730 const char *pcszFilename,
4731 PRTTIMESPEC pModificationTime)
4732{
4733 PVDINTERFACEIO pInterfaceIo = (PVDINTERFACEIO)pvUser;
4734 return pInterfaceIo->pfnGetModificationTime(NULL, pcszFilename, pModificationTime);
4735}
4736
4737static int vdIOIntGetSizeLimited(void *pvUser, PVDIOSTORAGE pIoStorage,
4738 uint64_t *pcbSize)
4739{
4740 PVDINTERFACEIO pInterfaceIo = (PVDINTERFACEIO)pvUser;
4741 return pInterfaceIo->pfnGetSize(NULL, pIoStorage->pStorage, pcbSize);
4742}
4743
4744static int vdIOIntSetSizeLimited(void *pvUser, PVDIOSTORAGE pIoStorage,
4745 uint64_t cbSize)
4746{
4747 PVDINTERFACEIO pInterfaceIo = (PVDINTERFACEIO)pvUser;
4748 return pInterfaceIo->pfnSetSize(NULL, pIoStorage->pStorage, cbSize);
4749}
4750
4751static int vdIOIntWriteSyncLimited(void *pvUser, PVDIOSTORAGE pIoStorage,
4752 uint64_t uOffset, const void *pvBuf,
4753 size_t cbWrite, size_t *pcbWritten)
4754{
4755 PVDINTERFACEIO pInterfaceIo = (PVDINTERFACEIO)pvUser;
4756 return pInterfaceIo->pfnWriteSync(NULL, pIoStorage->pStorage, uOffset, pvBuf, cbWrite, pcbWritten);
4757}
4758
4759static int vdIOIntReadSyncLimited(void *pvUser, PVDIOSTORAGE pIoStorage,
4760 uint64_t uOffset, void *pvBuf, size_t cbRead,
4761 size_t *pcbRead)
4762{
4763 PVDINTERFACEIO pInterfaceIo = (PVDINTERFACEIO)pvUser;
4764 return pInterfaceIo->pfnReadSync(NULL, pIoStorage->pStorage, uOffset, pvBuf, cbRead, pcbRead);
4765}
4766
4767static int vdIOIntFlushSyncLimited(void *pvUser, PVDIOSTORAGE pIoStorage)
4768{
4769 PVDINTERFACEIO pInterfaceIo = (PVDINTERFACEIO)pvUser;
4770 return pInterfaceIo->pfnFlushSync(NULL, pIoStorage->pStorage);
4771}
4772
4773/**
4774 * internal: send output to the log (unconditionally).
4775 */
4776int vdLogMessage(void *pvUser, const char *pszFormat, va_list args)
4777{
4778 NOREF(pvUser);
4779 RTLogPrintfV(pszFormat, args);
4780 return VINF_SUCCESS;
4781}
4782
4783DECLINLINE(int) vdMessageWrapper(PVBOXHDD pDisk, const char *pszFormat, ...)
4784{
4785 va_list va;
4786 va_start(va, pszFormat);
4787 int rc = pDisk->pInterfaceError->pfnMessage(pDisk->pInterfaceError->Core.pvUser,
4788 pszFormat, va);
4789 va_end(va);
4790 return rc;
4791}
4792
4793
4794/**
4795 * internal: adjust PCHS geometry
4796 */
4797static void vdFixupPCHSGeometry(PVDGEOMETRY pPCHS, uint64_t cbSize)
4798{
4799 /* Fix broken PCHS geometry. Can happen for two reasons: either the backend
4800 * mixes up PCHS and LCHS, or the application used to create the source
4801 * image has put garbage in it. Additionally, if the PCHS geometry covers
4802 * more than the image size, set it back to the default. */
4803 if ( pPCHS->cHeads > 16
4804 || pPCHS->cSectors > 63
4805 || pPCHS->cCylinders == 0
4806 || (uint64_t)pPCHS->cHeads * pPCHS->cSectors * pPCHS->cCylinders * 512 > cbSize)
4807 {
4808 Assert(!(RT_MIN(cbSize / 512 / 16 / 63, 16383) - (uint32_t)RT_MIN(cbSize / 512 / 16 / 63, 16383)));
4809 pPCHS->cCylinders = (uint32_t)RT_MIN(cbSize / 512 / 16 / 63, 16383);
4810 pPCHS->cHeads = 16;
4811 pPCHS->cSectors = 63;
4812 }
4813}
4814
4815/**
4816 * internal: adjust PCHS geometry
4817 */
4818static void vdFixupLCHSGeometry(PVDGEOMETRY pLCHS, uint64_t cbSize)
4819{
4820 /* Fix broken LCHS geometry. Can happen for two reasons: either the backend
4821 * mixes up PCHS and LCHS, or the application used to create the source
4822 * image has put garbage in it. The fix in this case is to clear the LCHS
4823 * geometry to trigger autodetection when it is used next. If the geometry
4824 * already says "please autodetect" (cylinders=0) keep it. */
4825 if ( ( pLCHS->cHeads > 255
4826 || pLCHS->cHeads == 0
4827 || pLCHS->cSectors > 63
4828 || pLCHS->cSectors == 0)
4829 && pLCHS->cCylinders != 0)
4830 {
4831 pLCHS->cCylinders = 0;
4832 pLCHS->cHeads = 0;
4833 pLCHS->cSectors = 0;
4834 }
4835 /* Always recompute the number of cylinders stored in the LCHS
4836 * geometry if it isn't set to "autotedetect" at the moment.
4837 * This is very useful if the destination image size is
4838 * larger or smaller than the source image size. Do not modify
4839 * the number of heads and sectors. Windows guests hate it. */
4840 if ( pLCHS->cCylinders != 0
4841 && pLCHS->cHeads != 0 /* paranoia */
4842 && pLCHS->cSectors != 0 /* paranoia */)
4843 {
4844 Assert(!(RT_MIN(cbSize / 512 / pLCHS->cHeads / pLCHS->cSectors, 1024) - (uint32_t)RT_MIN(cbSize / 512 / pLCHS->cHeads / pLCHS->cSectors, 1024)));
4845 pLCHS->cCylinders = (uint32_t)RT_MIN(cbSize / 512 / pLCHS->cHeads / pLCHS->cSectors, 1024);
4846 }
4847}
4848
4849/**
4850 * Sets the I/O callbacks of the given interface to the fallback methods
4851 *
4852 * @returns nothing.
4853 * @param pIfIo The I/O interface to setup.
4854 */
4855static void vdIfIoFallbackCallbacksSetup(PVDINTERFACEIO pIfIo)
4856{
4857 pIfIo->pfnOpen = vdIOOpenFallback;
4858 pIfIo->pfnClose = vdIOCloseFallback;
4859 pIfIo->pfnDelete = vdIODeleteFallback;
4860 pIfIo->pfnMove = vdIOMoveFallback;
4861 pIfIo->pfnGetFreeSpace = vdIOGetFreeSpaceFallback;
4862 pIfIo->pfnGetModificationTime = vdIOGetModificationTimeFallback;
4863 pIfIo->pfnGetSize = vdIOGetSizeFallback;
4864 pIfIo->pfnSetSize = vdIOSetSizeFallback;
4865 pIfIo->pfnReadSync = vdIOReadSyncFallback;
4866 pIfIo->pfnWriteSync = vdIOWriteSyncFallback;
4867 pIfIo->pfnFlushSync = vdIOFlushSyncFallback;
4868 pIfIo->pfnReadAsync = vdIOReadAsyncFallback;
4869 pIfIo->pfnWriteAsync = vdIOWriteAsyncFallback;
4870 pIfIo->pfnFlushAsync = vdIOFlushAsyncFallback;
4871}
4872
4873/**
4874 * Sets the internal I/O callbacks of the given interface.
4875 *
4876 * @returns nothing.
4877 * @param pIfIoInt The internal I/O interface to setup.
4878 */
4879static void vdIfIoIntCallbacksSetup(PVDINTERFACEIOINT pIfIoInt)
4880{
4881 pIfIoInt->pfnOpen = vdIOIntOpen;
4882 pIfIoInt->pfnClose = vdIOIntClose;
4883 pIfIoInt->pfnDelete = vdIOIntDelete;
4884 pIfIoInt->pfnMove = vdIOIntMove;
4885 pIfIoInt->pfnGetFreeSpace = vdIOIntGetFreeSpace;
4886 pIfIoInt->pfnGetModificationTime = vdIOIntGetModificationTime;
4887 pIfIoInt->pfnGetSize = vdIOIntGetSize;
4888 pIfIoInt->pfnSetSize = vdIOIntSetSize;
4889 pIfIoInt->pfnReadSync = vdIOIntReadSync;
4890 pIfIoInt->pfnWriteSync = vdIOIntWriteSync;
4891 pIfIoInt->pfnFlushSync = vdIOIntFlushSync;
4892 pIfIoInt->pfnReadUserAsync = vdIOIntReadUserAsync;
4893 pIfIoInt->pfnWriteUserAsync = vdIOIntWriteUserAsync;
4894 pIfIoInt->pfnReadMetaAsync = vdIOIntReadMetaAsync;
4895 pIfIoInt->pfnWriteMetaAsync = vdIOIntWriteMetaAsync;
4896 pIfIoInt->pfnMetaXferRelease = vdIOIntMetaXferRelease;
4897 pIfIoInt->pfnFlushAsync = vdIOIntFlushAsync;
4898 pIfIoInt->pfnIoCtxCopyFrom = vdIOIntIoCtxCopyFrom;
4899 pIfIoInt->pfnIoCtxCopyTo = vdIOIntIoCtxCopyTo;
4900 pIfIoInt->pfnIoCtxSet = vdIOIntIoCtxSet;
4901 pIfIoInt->pfnIoCtxSegArrayCreate = vdIOIntIoCtxSegArrayCreate;
4902 pIfIoInt->pfnIoCtxCompleted = vdIOIntIoCtxCompleted;
4903}
4904
4905/**
4906 * Initializes HDD backends.
4907 *
4908 * @returns VBox status code.
4909 */
4910VBOXDDU_DECL(int) VDInit(void)
4911{
4912 int rc = vdAddBackends(aStaticBackends, RT_ELEMENTS(aStaticBackends));
4913 if (RT_SUCCESS(rc))
4914 {
4915 rc = vdAddCacheBackends(aStaticCacheBackends, RT_ELEMENTS(aStaticCacheBackends));
4916 if (RT_SUCCESS(rc))
4917 {
4918 rc = vdLoadDynamicBackends();
4919 if (RT_SUCCESS(rc))
4920 rc = vdLoadDynamicCacheBackends();
4921 }
4922 }
4923 LogRel(("VDInit finished\n"));
4924 return rc;
4925}
4926
4927/**
4928 * Destroys loaded HDD backends.
4929 *
4930 * @returns VBox status code.
4931 */
4932VBOXDDU_DECL(int) VDShutdown(void)
4933{
4934 PVBOXHDDBACKEND *pBackends = g_apBackends;
4935 PVDCACHEBACKEND *pCacheBackends = g_apCacheBackends;
4936 unsigned cBackends = g_cBackends;
4937
4938 if (!pBackends)
4939 return VERR_INTERNAL_ERROR;
4940
4941 g_cBackends = 0;
4942 g_apBackends = NULL;
4943
4944#ifndef VBOX_HDD_NO_DYNAMIC_BACKENDS
4945 for (unsigned i = 0; i < cBackends; i++)
4946 if (pBackends[i]->hPlugin != NIL_RTLDRMOD)
4947 RTLdrClose(pBackends[i]->hPlugin);
4948#endif
4949
4950 /* Clear the supported cache backends. */
4951 cBackends = g_cCacheBackends;
4952 g_cCacheBackends = 0;
4953 g_apCacheBackends = NULL;
4954
4955#ifndef VBOX_HDD_NO_DYNAMIC_BACKENDS
4956 for (unsigned i = 0; i < cBackends; i++)
4957 if (pCacheBackends[i]->hPlugin != NIL_RTLDRMOD)
4958 RTLdrClose(pCacheBackends[i]->hPlugin);
4959#endif
4960
4961 if (pCacheBackends)
4962 RTMemFree(pCacheBackends);
4963 RTMemFree(pBackends);
4964 return VINF_SUCCESS;
4965}
4966
4967
4968/**
4969 * Lists all HDD backends and their capabilities in a caller-provided buffer.
4970 *
4971 * @returns VBox status code.
4972 * VERR_BUFFER_OVERFLOW if not enough space is passed.
4973 * @param cEntriesAlloc Number of list entries available.
4974 * @param pEntries Pointer to array for the entries.
4975 * @param pcEntriesUsed Number of entries returned.
4976 */
4977VBOXDDU_DECL(int) VDBackendInfo(unsigned cEntriesAlloc, PVDBACKENDINFO pEntries,
4978 unsigned *pcEntriesUsed)
4979{
4980 int rc = VINF_SUCCESS;
4981 PRTDIR pPluginDir = NULL;
4982 unsigned cEntries = 0;
4983
4984 LogFlowFunc(("cEntriesAlloc=%u pEntries=%#p pcEntriesUsed=%#p\n", cEntriesAlloc, pEntries, pcEntriesUsed));
4985 /* Check arguments. */
4986 AssertMsgReturn(cEntriesAlloc,
4987 ("cEntriesAlloc=%u\n", cEntriesAlloc),
4988 VERR_INVALID_PARAMETER);
4989 AssertMsgReturn(VALID_PTR(pEntries),
4990 ("pEntries=%#p\n", pEntries),
4991 VERR_INVALID_PARAMETER);
4992 AssertMsgReturn(VALID_PTR(pcEntriesUsed),
4993 ("pcEntriesUsed=%#p\n", pcEntriesUsed),
4994 VERR_INVALID_PARAMETER);
4995 if (!g_apBackends)
4996 VDInit();
4997
4998 if (cEntriesAlloc < g_cBackends)
4999 {
5000 *pcEntriesUsed = g_cBackends;
5001 return VERR_BUFFER_OVERFLOW;
5002 }
5003
5004 for (unsigned i = 0; i < g_cBackends; i++)
5005 {
5006 pEntries[i].pszBackend = g_apBackends[i]->pszBackendName;
5007 pEntries[i].uBackendCaps = g_apBackends[i]->uBackendCaps;
5008 pEntries[i].paFileExtensions = g_apBackends[i]->paFileExtensions;
5009 pEntries[i].paConfigInfo = g_apBackends[i]->paConfigInfo;
5010 pEntries[i].pfnComposeLocation = g_apBackends[i]->pfnComposeLocation;
5011 pEntries[i].pfnComposeName = g_apBackends[i]->pfnComposeName;
5012 }
5013
5014 LogFlowFunc(("returns %Rrc *pcEntriesUsed=%u\n", rc, cEntries));
5015 *pcEntriesUsed = g_cBackends;
5016 return rc;
5017}
5018
5019/**
5020 * Lists the capabilities of a backend identified by its name.
5021 *
5022 * @returns VBox status code.
5023 * @param pszBackend The backend name.
5024 * @param pEntries Pointer to an entry.
5025 */
5026VBOXDDU_DECL(int) VDBackendInfoOne(const char *pszBackend, PVDBACKENDINFO pEntry)
5027{
5028 LogFlowFunc(("pszBackend=%#p pEntry=%#p\n", pszBackend, pEntry));
5029 /* Check arguments. */
5030 AssertMsgReturn(VALID_PTR(pszBackend),
5031 ("pszBackend=%#p\n", pszBackend),
5032 VERR_INVALID_PARAMETER);
5033 AssertMsgReturn(VALID_PTR(pEntry),
5034 ("pEntry=%#p\n", pEntry),
5035 VERR_INVALID_PARAMETER);
5036 if (!g_apBackends)
5037 VDInit();
5038
5039 /* Go through loaded backends. */
5040 for (unsigned i = 0; i < g_cBackends; i++)
5041 {
5042 if (!RTStrICmp(pszBackend, g_apBackends[i]->pszBackendName))
5043 {
5044 pEntry->pszBackend = g_apBackends[i]->pszBackendName;
5045 pEntry->uBackendCaps = g_apBackends[i]->uBackendCaps;
5046 pEntry->paFileExtensions = g_apBackends[i]->paFileExtensions;
5047 pEntry->paConfigInfo = g_apBackends[i]->paConfigInfo;
5048 return VINF_SUCCESS;
5049 }
5050 }
5051
5052 return VERR_NOT_FOUND;
5053}
5054
5055/**
5056 * Allocates and initializes an empty HDD container.
5057 * No image files are opened.
5058 *
5059 * @returns VBox status code.
5060 * @param pVDIfsDisk Pointer to the per-disk VD interface list.
5061 * @param enmType Type of the image container.
5062 * @param ppDisk Where to store the reference to HDD container.
5063 */
5064VBOXDDU_DECL(int) VDCreate(PVDINTERFACE pVDIfsDisk, VDTYPE enmType, PVBOXHDD *ppDisk)
5065{
5066 int rc = VINF_SUCCESS;
5067 PVBOXHDD pDisk = NULL;
5068
5069 LogFlowFunc(("pVDIfsDisk=%#p\n", pVDIfsDisk));
5070 do
5071 {
5072 /* Check arguments. */
5073 AssertMsgBreakStmt(VALID_PTR(ppDisk),
5074 ("ppDisk=%#p\n", ppDisk),
5075 rc = VERR_INVALID_PARAMETER);
5076
5077 pDisk = (PVBOXHDD)RTMemAllocZ(sizeof(VBOXHDD));
5078 if (pDisk)
5079 {
5080 pDisk->u32Signature = VBOXHDDDISK_SIGNATURE;
5081 pDisk->enmType = enmType;
5082 pDisk->cImages = 0;
5083 pDisk->pBase = NULL;
5084 pDisk->pLast = NULL;
5085 pDisk->cbSize = 0;
5086 pDisk->PCHSGeometry.cCylinders = 0;
5087 pDisk->PCHSGeometry.cHeads = 0;
5088 pDisk->PCHSGeometry.cSectors = 0;
5089 pDisk->LCHSGeometry.cCylinders = 0;
5090 pDisk->LCHSGeometry.cHeads = 0;
5091 pDisk->LCHSGeometry.cSectors = 0;
5092 pDisk->pVDIfsDisk = pVDIfsDisk;
5093 pDisk->pInterfaceError = NULL;
5094 pDisk->pInterfaceThreadSync = NULL;
5095 pDisk->fLocked = false;
5096 pDisk->pIoCtxLockOwner = NULL;
5097 pDisk->pIoCtxHead = NULL;
5098 RTListInit(&pDisk->ListWriteLocked);
5099
5100 /* Create the I/O ctx cache */
5101 rc = RTMemCacheCreate(&pDisk->hMemCacheIoCtx, sizeof(VDIOCTX), 0, UINT32_MAX,
5102 NULL, NULL, NULL, 0);
5103 if (RT_FAILURE(rc))
5104 {
5105 RTMemFree(pDisk);
5106 break;
5107 }
5108
5109 /* Create the I/O task cache */
5110 rc = RTMemCacheCreate(&pDisk->hMemCacheIoTask, sizeof(VDIOTASK), 0, UINT32_MAX,
5111 NULL, NULL, NULL, 0);
5112 if (RT_FAILURE(rc))
5113 {
5114 RTMemCacheDestroy(pDisk->hMemCacheIoCtx);
5115 RTMemFree(pDisk);
5116 break;
5117 }
5118
5119 /* Create critical section. */
5120 rc = RTCritSectInit(&pDisk->CritSect);
5121 if (RT_FAILURE(rc))
5122 {
5123 RTMemCacheDestroy(pDisk->hMemCacheIoCtx);
5124 RTMemCacheDestroy(pDisk->hMemCacheIoTask);
5125 RTMemFree(pDisk);
5126 break;
5127 }
5128
5129 pDisk->pInterfaceError = VDIfErrorGet(pVDIfsDisk);
5130 pDisk->pInterfaceThreadSync = VDIfThreadSyncGet(pVDIfsDisk);
5131
5132 *ppDisk = pDisk;
5133 }
5134 else
5135 {
5136 rc = VERR_NO_MEMORY;
5137 break;
5138 }
5139 } while (0);
5140
5141 LogFlowFunc(("returns %Rrc (pDisk=%#p)\n", rc, pDisk));
5142 return rc;
5143}
5144
5145/**
5146 * Destroys HDD container.
5147 * If container has opened image files they will be closed.
5148 *
5149 * @returns VBox status code.
5150 * @param pDisk Pointer to HDD container.
5151 */
5152VBOXDDU_DECL(int) VDDestroy(PVBOXHDD pDisk)
5153{
5154 int rc = VINF_SUCCESS;
5155 LogFlowFunc(("pDisk=%#p\n", pDisk));
5156 do
5157 {
5158 /* sanity check */
5159 AssertPtrBreak(pDisk);
5160 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
5161 rc = VDCloseAll(pDisk);
5162 RTCritSectDelete(&pDisk->CritSect);
5163 RTMemCacheDestroy(pDisk->hMemCacheIoCtx);
5164 RTMemCacheDestroy(pDisk->hMemCacheIoTask);
5165 RTMemFree(pDisk);
5166 } while (0);
5167 LogFlowFunc(("returns %Rrc\n", rc));
5168 return rc;
5169}
5170
5171/**
5172 * Try to get the backend name which can use this image.
5173 *
5174 * @returns VBox status code.
5175 * VINF_SUCCESS if a plugin was found.
5176 * ppszFormat contains the string which can be used as backend name.
5177 * VERR_NOT_SUPPORTED if no backend was found.
5178 * @param pVDIfsDisk Pointer to the per-disk VD interface list.
5179 * @param pVDIfsImage Pointer to the per-image VD interface list.
5180 * @param pszFilename Name of the image file for which the backend is queried.
5181 * @param ppszFormat Receives pointer of the UTF-8 string which contains the format name.
5182 * The returned pointer must be freed using RTStrFree().
5183 */
5184VBOXDDU_DECL(int) VDGetFormat(PVDINTERFACE pVDIfsDisk, PVDINTERFACE pVDIfsImage,
5185 const char *pszFilename, char **ppszFormat, VDTYPE *penmType)
5186{
5187 int rc = VERR_NOT_SUPPORTED;
5188 VDINTERFACEIOINT VDIfIoInt;
5189 VDINTERFACEIO VDIfIoFallback;
5190 PVDINTERFACEIO pInterfaceIo;
5191
5192 LogFlowFunc(("pszFilename=\"%s\"\n", pszFilename));
5193 /* Check arguments. */
5194 AssertMsgReturn(VALID_PTR(pszFilename) && *pszFilename,
5195 ("pszFilename=%#p \"%s\"\n", pszFilename, pszFilename),
5196 VERR_INVALID_PARAMETER);
5197 AssertMsgReturn(VALID_PTR(ppszFormat),
5198 ("ppszFormat=%#p\n", ppszFormat),
5199 VERR_INVALID_PARAMETER);
5200 AssertMsgReturn(VALID_PTR(penmType),
5201 ("penmType=%#p\n", penmType),
5202 VERR_INVALID_PARAMETER);
5203
5204 if (!g_apBackends)
5205 VDInit();
5206
5207 pInterfaceIo = VDIfIoGet(pVDIfsImage);
5208 if (!pInterfaceIo)
5209 {
5210 /*
5211 * Caller doesn't provide an I/O interface, create our own using the
5212 * native file API.
5213 */
5214 vdIfIoFallbackCallbacksSetup(&VDIfIoFallback);
5215 pInterfaceIo = &VDIfIoFallback;
5216 }
5217
5218 /* Set up the internal I/O interface. */
5219 AssertReturn(!VDIfIoIntGet(pVDIfsImage), VERR_INVALID_PARAMETER);
5220 VDIfIoInt.pfnOpen = vdIOIntOpenLimited;
5221 VDIfIoInt.pfnClose = vdIOIntCloseLimited;
5222 VDIfIoInt.pfnDelete = vdIOIntDeleteLimited;
5223 VDIfIoInt.pfnMove = vdIOIntMoveLimited;
5224 VDIfIoInt.pfnGetFreeSpace = vdIOIntGetFreeSpaceLimited;
5225 VDIfIoInt.pfnGetModificationTime = vdIOIntGetModificationTimeLimited;
5226 VDIfIoInt.pfnGetSize = vdIOIntGetSizeLimited;
5227 VDIfIoInt.pfnSetSize = vdIOIntSetSizeLimited;
5228 VDIfIoInt.pfnReadSync = vdIOIntReadSyncLimited;
5229 VDIfIoInt.pfnWriteSync = vdIOIntWriteSyncLimited;
5230 VDIfIoInt.pfnFlushSync = vdIOIntFlushSyncLimited;
5231 VDIfIoInt.pfnReadUserAsync = NULL;
5232 VDIfIoInt.pfnWriteUserAsync = NULL;
5233 VDIfIoInt.pfnReadMetaAsync = NULL;
5234 VDIfIoInt.pfnWriteMetaAsync = NULL;
5235 VDIfIoInt.pfnFlushAsync = NULL;
5236 rc = VDInterfaceAdd(&VDIfIoInt.Core, "VD_IOINT", VDINTERFACETYPE_IOINT,
5237 pInterfaceIo, sizeof(VDINTERFACEIOINT), &pVDIfsImage);
5238 AssertRC(rc);
5239
5240 /* Find the backend supporting this file format. */
5241 for (unsigned i = 0; i < g_cBackends; i++)
5242 {
5243 if (g_apBackends[i]->pfnCheckIfValid)
5244 {
5245 rc = g_apBackends[i]->pfnCheckIfValid(pszFilename, pVDIfsDisk,
5246 pVDIfsImage, penmType);
5247 if ( RT_SUCCESS(rc)
5248 /* The correct backend has been found, but there is a small
5249 * incompatibility so that the file cannot be used. Stop here
5250 * and signal success - the actual open will of course fail,
5251 * but that will create a really sensible error message. */
5252 || ( rc != VERR_VD_GEN_INVALID_HEADER
5253 && rc != VERR_VD_VDI_INVALID_HEADER
5254 && rc != VERR_VD_VMDK_INVALID_HEADER
5255 && rc != VERR_VD_ISCSI_INVALID_HEADER
5256 && rc != VERR_VD_VHD_INVALID_HEADER
5257 && rc != VERR_VD_RAW_INVALID_HEADER
5258 && rc != VERR_VD_PARALLELS_INVALID_HEADER
5259 && rc != VERR_VD_DMG_INVALID_HEADER))
5260 {
5261 /* Copy the name into the new string. */
5262 char *pszFormat = RTStrDup(g_apBackends[i]->pszBackendName);
5263 if (!pszFormat)
5264 {
5265 rc = VERR_NO_MEMORY;
5266 break;
5267 }
5268 *ppszFormat = pszFormat;
5269 /* Do not consider the typical file access errors as success,
5270 * which allows the caller to deal with such issues. */
5271 if ( rc != VERR_ACCESS_DENIED
5272 && rc != VERR_PATH_NOT_FOUND
5273 && rc != VERR_FILE_NOT_FOUND)
5274 rc = VINF_SUCCESS;
5275 break;
5276 }
5277 rc = VERR_NOT_SUPPORTED;
5278 }
5279 }
5280
5281 /* Try the cache backends. */
5282 if (rc == VERR_NOT_SUPPORTED)
5283 {
5284 for (unsigned i = 0; i < g_cCacheBackends; i++)
5285 {
5286 if (g_apCacheBackends[i]->pfnProbe)
5287 {
5288 rc = g_apCacheBackends[i]->pfnProbe(pszFilename, pVDIfsDisk,
5289 pVDIfsImage);
5290 if ( RT_SUCCESS(rc)
5291 || (rc != VERR_VD_GEN_INVALID_HEADER))
5292 {
5293 /* Copy the name into the new string. */
5294 char *pszFormat = RTStrDup(g_apBackends[i]->pszBackendName);
5295 if (!pszFormat)
5296 {
5297 rc = VERR_NO_MEMORY;
5298 break;
5299 }
5300 *ppszFormat = pszFormat;
5301 rc = VINF_SUCCESS;
5302 break;
5303 }
5304 rc = VERR_NOT_SUPPORTED;
5305 }
5306 }
5307 }
5308
5309 LogFlowFunc(("returns %Rrc *ppszFormat=\"%s\"\n", rc, *ppszFormat));
5310 return rc;
5311}
5312
5313/**
5314 * Opens an image file.
5315 *
5316 * The first opened image file in HDD container must have a base image type,
5317 * others (next opened images) must be a differencing or undo images.
5318 * Linkage is checked for differencing image to be in consistence with the previously opened image.
5319 * When another differencing image is opened and the last image was opened in read/write access
5320 * mode, then the last image is reopened in read-only with deny write sharing mode. This allows
5321 * other processes to use images in read-only mode too.
5322 *
5323 * Note that the image is opened in read-only mode if a read/write open is not possible.
5324 * Use VDIsReadOnly to check open mode.
5325 *
5326 * @returns VBox status code.
5327 * @param pDisk Pointer to HDD container.
5328 * @param pszBackend Name of the image file backend to use.
5329 * @param pszFilename Name of the image file to open.
5330 * @param uOpenFlags Image file open mode, see VD_OPEN_FLAGS_* constants.
5331 * @param pVDIfsImage Pointer to the per-image VD interface list.
5332 */
5333VBOXDDU_DECL(int) VDOpen(PVBOXHDD pDisk, const char *pszBackend,
5334 const char *pszFilename, unsigned uOpenFlags,
5335 PVDINTERFACE pVDIfsImage)
5336{
5337 int rc = VINF_SUCCESS;
5338 int rc2;
5339 bool fLockWrite = false;
5340 PVDIMAGE pImage = NULL;
5341
5342 LogFlowFunc(("pDisk=%#p pszBackend=\"%s\" pszFilename=\"%s\" uOpenFlags=%#x, pVDIfsImage=%#p\n",
5343 pDisk, pszBackend, pszFilename, uOpenFlags, pVDIfsImage));
5344
5345 do
5346 {
5347 /* sanity check */
5348 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
5349 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
5350
5351 /* Check arguments. */
5352 AssertMsgBreakStmt(VALID_PTR(pszBackend) && *pszBackend,
5353 ("pszBackend=%#p \"%s\"\n", pszBackend, pszBackend),
5354 rc = VERR_INVALID_PARAMETER);
5355 AssertMsgBreakStmt(VALID_PTR(pszFilename) && *pszFilename,
5356 ("pszFilename=%#p \"%s\"\n", pszFilename, pszFilename),
5357 rc = VERR_INVALID_PARAMETER);
5358 AssertMsgBreakStmt((uOpenFlags & ~VD_OPEN_FLAGS_MASK) == 0,
5359 ("uOpenFlags=%#x\n", uOpenFlags),
5360 rc = VERR_INVALID_PARAMETER);
5361
5362 /*
5363 * Destroy the current discard state first which might still have pending blocks
5364 * for the currently opened image which will be switched to readonly mode.
5365 */
5366 /* Lock disk for writing, as we modify pDisk information below. */
5367 rc2 = vdThreadStartWrite(pDisk);
5368 AssertRC(rc2);
5369 fLockWrite = true;
5370 rc = vdDiscardStateDestroy(pDisk);
5371 if (RT_FAILURE(rc))
5372 break;
5373 rc2 = vdThreadFinishWrite(pDisk);
5374 AssertRC(rc2);
5375 fLockWrite = false;
5376
5377 /* Set up image descriptor. */
5378 pImage = (PVDIMAGE)RTMemAllocZ(sizeof(VDIMAGE));
5379 if (!pImage)
5380 {
5381 rc = VERR_NO_MEMORY;
5382 break;
5383 }
5384 pImage->pszFilename = RTStrDup(pszFilename);
5385 if (!pImage->pszFilename)
5386 {
5387 rc = VERR_NO_MEMORY;
5388 break;
5389 }
5390
5391 pImage->VDIo.pDisk = pDisk;
5392 pImage->pVDIfsImage = pVDIfsImage;
5393
5394 rc = vdFindBackend(pszBackend, &pImage->Backend);
5395 if (RT_FAILURE(rc))
5396 break;
5397 if (!pImage->Backend)
5398 {
5399 rc = vdError(pDisk, VERR_INVALID_PARAMETER, RT_SRC_POS,
5400 N_("VD: unknown backend name '%s'"), pszBackend);
5401 break;
5402 }
5403
5404 /*
5405 * Fail if the backend can't do async I/O but the
5406 * flag is set.
5407 */
5408 if ( !(pImage->Backend->uBackendCaps & VD_CAP_ASYNC)
5409 && (uOpenFlags & VD_OPEN_FLAGS_ASYNC_IO))
5410 {
5411 rc = vdError(pDisk, VERR_NOT_SUPPORTED, RT_SRC_POS,
5412 N_("VD: Backend '%s' does not support async I/O"), pszBackend);
5413 break;
5414 }
5415
5416 /*
5417 * Fail if the backend doesn't support the discard operation but the
5418 * flag is set.
5419 */
5420 if ( !(pImage->Backend->uBackendCaps & VD_CAP_DISCARD)
5421 && (uOpenFlags & VD_OPEN_FLAGS_DISCARD))
5422 {
5423 rc = vdError(pDisk, VERR_VD_DISCARD_NOT_SUPPORTED, RT_SRC_POS,
5424 N_("VD: Backend '%s' does not support discard"), pszBackend);
5425 break;
5426 }
5427
5428 /* Set up the I/O interface. */
5429 pImage->VDIo.pInterfaceIo = VDIfIoGet(pVDIfsImage);
5430 if (!pImage->VDIo.pInterfaceIo)
5431 {
5432 vdIfIoFallbackCallbacksSetup(&pImage->VDIo.VDIfIo);
5433 rc = VDInterfaceAdd(&pImage->VDIo.VDIfIo.Core, "VD_IO", VDINTERFACETYPE_IO,
5434 pDisk, sizeof(VDINTERFACEIO), &pVDIfsImage);
5435 pImage->VDIo.pInterfaceIo = &pImage->VDIo.VDIfIo;
5436 }
5437
5438 /* Set up the internal I/O interface. */
5439 AssertBreakStmt(!VDIfIoIntGet(pVDIfsImage), rc = VERR_INVALID_PARAMETER);
5440 vdIfIoIntCallbacksSetup(&pImage->VDIo.VDIfIoInt);
5441 rc = VDInterfaceAdd(&pImage->VDIo.VDIfIoInt.Core, "VD_IOINT", VDINTERFACETYPE_IOINT,
5442 &pImage->VDIo, sizeof(VDINTERFACEIOINT), &pImage->pVDIfsImage);
5443 AssertRC(rc);
5444
5445 pImage->uOpenFlags = uOpenFlags & (VD_OPEN_FLAGS_HONOR_SAME | VD_OPEN_FLAGS_DISCARD | VD_OPEN_FLAGS_IGNORE_FLUSH | VD_OPEN_FLAGS_INFORM_ABOUT_ZERO_BLOCKS);
5446 pImage->VDIo.fIgnoreFlush = (uOpenFlags & VD_OPEN_FLAGS_IGNORE_FLUSH) != 0;
5447 rc = pImage->Backend->pfnOpen(pImage->pszFilename,
5448 uOpenFlags & ~(VD_OPEN_FLAGS_HONOR_SAME | VD_OPEN_FLAGS_IGNORE_FLUSH | VD_OPEN_FLAGS_INFORM_ABOUT_ZERO_BLOCKS),
5449 pDisk->pVDIfsDisk,
5450 pImage->pVDIfsImage,
5451 pDisk->enmType,
5452 &pImage->pBackendData);
5453 /*
5454 * If the image is corrupted and there is a repair method try to repair it
5455 * first if it was openend in read-write mode and open again afterwards.
5456 */
5457 if ( RT_UNLIKELY(rc == VERR_VD_IMAGE_CORRUPTED)
5458 && pImage->Backend->pfnRepair)
5459 {
5460 rc = pImage->Backend->pfnRepair(pszFilename, pDisk->pVDIfsDisk, pImage->pVDIfsImage, 0 /* fFlags */);
5461 if (RT_SUCCESS(rc))
5462 rc = pImage->Backend->pfnOpen(pImage->pszFilename,
5463 uOpenFlags & ~(VD_OPEN_FLAGS_HONOR_SAME | VD_OPEN_FLAGS_IGNORE_FLUSH | VD_OPEN_FLAGS_INFORM_ABOUT_ZERO_BLOCKS),
5464 pDisk->pVDIfsDisk,
5465 pImage->pVDIfsImage,
5466 pDisk->enmType,
5467 &pImage->pBackendData);
5468 else
5469 {
5470 rc = vdError(pDisk, rc, RT_SRC_POS,
5471 N_("VD: error %Rrc repairing corrupted image file '%s'"), rc, pszFilename);
5472 break;
5473 }
5474 }
5475 else if (RT_UNLIKELY(rc == VERR_VD_IMAGE_CORRUPTED))
5476 {
5477 rc = vdError(pDisk, rc, RT_SRC_POS,
5478 N_("VD: Image file '%s' is corrupted and can't be opened"), pszFilename);
5479 break;
5480 }
5481
5482 /* If the open in read-write mode failed, retry in read-only mode. */
5483 if (RT_FAILURE(rc))
5484 {
5485 if (!(uOpenFlags & VD_OPEN_FLAGS_READONLY)
5486 && ( rc == VERR_ACCESS_DENIED
5487 || rc == VERR_PERMISSION_DENIED
5488 || rc == VERR_WRITE_PROTECT
5489 || rc == VERR_SHARING_VIOLATION
5490 || rc == VERR_FILE_LOCK_FAILED))
5491 rc = pImage->Backend->pfnOpen(pImage->pszFilename,
5492 (uOpenFlags & ~(VD_OPEN_FLAGS_HONOR_SAME | VD_OPEN_FLAGS_INFORM_ABOUT_ZERO_BLOCKS))
5493 | VD_OPEN_FLAGS_READONLY,
5494 pDisk->pVDIfsDisk,
5495 pImage->pVDIfsImage,
5496 pDisk->enmType,
5497 &pImage->pBackendData);
5498 if (RT_FAILURE(rc))
5499 {
5500 rc = vdError(pDisk, rc, RT_SRC_POS,
5501 N_("VD: error %Rrc opening image file '%s'"), rc, pszFilename);
5502 break;
5503 }
5504 }
5505
5506 /* Lock disk for writing, as we modify pDisk information below. */
5507 rc2 = vdThreadStartWrite(pDisk);
5508 AssertRC(rc2);
5509 fLockWrite = true;
5510
5511 pImage->VDIo.pBackendData = pImage->pBackendData;
5512
5513 /* Check image type. As the image itself has only partial knowledge
5514 * whether it's a base image or not, this info is derived here. The
5515 * base image can be fixed or normal, all others must be normal or
5516 * diff images. Some image formats don't distinguish between normal
5517 * and diff images, so this must be corrected here. */
5518 unsigned uImageFlags;
5519 uImageFlags = pImage->Backend->pfnGetImageFlags(pImage->pBackendData);
5520 if (RT_FAILURE(rc))
5521 uImageFlags = VD_IMAGE_FLAGS_NONE;
5522 if ( RT_SUCCESS(rc)
5523 && !(uOpenFlags & VD_OPEN_FLAGS_INFO))
5524 {
5525 if ( pDisk->cImages == 0
5526 && (uImageFlags & VD_IMAGE_FLAGS_DIFF))
5527 {
5528 rc = VERR_VD_INVALID_TYPE;
5529 break;
5530 }
5531 else if (pDisk->cImages != 0)
5532 {
5533 if (uImageFlags & VD_IMAGE_FLAGS_FIXED)
5534 {
5535 rc = VERR_VD_INVALID_TYPE;
5536 break;
5537 }
5538 else
5539 uImageFlags |= VD_IMAGE_FLAGS_DIFF;
5540 }
5541 }
5542
5543 /* Ensure we always get correct diff information, even if the backend
5544 * doesn't actually have a stored flag for this. It must not return
5545 * bogus information for the parent UUID if it is not a diff image. */
5546 RTUUID parentUuid;
5547 RTUuidClear(&parentUuid);
5548 rc2 = pImage->Backend->pfnGetParentUuid(pImage->pBackendData, &parentUuid);
5549 if (RT_SUCCESS(rc2) && !RTUuidIsNull(&parentUuid))
5550 uImageFlags |= VD_IMAGE_FLAGS_DIFF;
5551
5552 pImage->uImageFlags = uImageFlags;
5553
5554 /* Force sane optimization settings. It's not worth avoiding writes
5555 * to fixed size images. The overhead would have almost no payback. */
5556 if (uImageFlags & VD_IMAGE_FLAGS_FIXED)
5557 pImage->uOpenFlags |= VD_OPEN_FLAGS_HONOR_SAME;
5558
5559 /** @todo optionally check UUIDs */
5560
5561 /* Cache disk information. */
5562 pDisk->cbSize = pImage->Backend->pfnGetSize(pImage->pBackendData);
5563
5564 /* Cache PCHS geometry. */
5565 rc2 = pImage->Backend->pfnGetPCHSGeometry(pImage->pBackendData,
5566 &pDisk->PCHSGeometry);
5567 if (RT_FAILURE(rc2))
5568 {
5569 pDisk->PCHSGeometry.cCylinders = 0;
5570 pDisk->PCHSGeometry.cHeads = 0;
5571 pDisk->PCHSGeometry.cSectors = 0;
5572 }
5573 else
5574 {
5575 /* Make sure the PCHS geometry is properly clipped. */
5576 pDisk->PCHSGeometry.cCylinders = RT_MIN(pDisk->PCHSGeometry.cCylinders, 16383);
5577 pDisk->PCHSGeometry.cHeads = RT_MIN(pDisk->PCHSGeometry.cHeads, 16);
5578 pDisk->PCHSGeometry.cSectors = RT_MIN(pDisk->PCHSGeometry.cSectors, 63);
5579 }
5580
5581 /* Cache LCHS geometry. */
5582 rc2 = pImage->Backend->pfnGetLCHSGeometry(pImage->pBackendData,
5583 &pDisk->LCHSGeometry);
5584 if (RT_FAILURE(rc2))
5585 {
5586 pDisk->LCHSGeometry.cCylinders = 0;
5587 pDisk->LCHSGeometry.cHeads = 0;
5588 pDisk->LCHSGeometry.cSectors = 0;
5589 }
5590 else
5591 {
5592 /* Make sure the LCHS geometry is properly clipped. */
5593 pDisk->LCHSGeometry.cHeads = RT_MIN(pDisk->LCHSGeometry.cHeads, 255);
5594 pDisk->LCHSGeometry.cSectors = RT_MIN(pDisk->LCHSGeometry.cSectors, 63);
5595 }
5596
5597 if (pDisk->cImages != 0)
5598 {
5599 /* Switch previous image to read-only mode. */
5600 unsigned uOpenFlagsPrevImg;
5601 uOpenFlagsPrevImg = pDisk->pLast->Backend->pfnGetOpenFlags(pDisk->pLast->pBackendData);
5602 if (!(uOpenFlagsPrevImg & VD_OPEN_FLAGS_READONLY))
5603 {
5604 uOpenFlagsPrevImg |= VD_OPEN_FLAGS_READONLY;
5605 rc = pDisk->pLast->Backend->pfnSetOpenFlags(pDisk->pLast->pBackendData, uOpenFlagsPrevImg);
5606 }
5607 }
5608
5609 if (RT_SUCCESS(rc))
5610 {
5611 /* Image successfully opened, make it the last image. */
5612 vdAddImageToList(pDisk, pImage);
5613 if (!(uOpenFlags & VD_OPEN_FLAGS_READONLY))
5614 pDisk->uModified = VD_IMAGE_MODIFIED_FIRST;
5615 }
5616 else
5617 {
5618 /* Error detected, but image opened. Close image. */
5619 rc2 = pImage->Backend->pfnClose(pImage->pBackendData, false);
5620 AssertRC(rc2);
5621 pImage->pBackendData = NULL;
5622 }
5623 } while (0);
5624
5625 if (RT_UNLIKELY(fLockWrite))
5626 {
5627 rc2 = vdThreadFinishWrite(pDisk);
5628 AssertRC(rc2);
5629 }
5630
5631 if (RT_FAILURE(rc))
5632 {
5633 if (pImage)
5634 {
5635 if (pImage->pszFilename)
5636 RTStrFree(pImage->pszFilename);
5637 RTMemFree(pImage);
5638 }
5639 }
5640
5641 LogFlowFunc(("returns %Rrc\n", rc));
5642 return rc;
5643}
5644
5645/**
5646 * Opens a cache image.
5647 *
5648 * @return VBox status code.
5649 * @param pDisk Pointer to the HDD container which should use the cache image.
5650 * @param pszBackend Name of the cache file backend to use (case insensitive).
5651 * @param pszFilename Name of the cache image to open.
5652 * @param uOpenFlags Image file open mode, see VD_OPEN_FLAGS_* constants.
5653 * @param pVDIfsCache Pointer to the per-cache VD interface list.
5654 */
5655VBOXDDU_DECL(int) VDCacheOpen(PVBOXHDD pDisk, const char *pszBackend,
5656 const char *pszFilename, unsigned uOpenFlags,
5657 PVDINTERFACE pVDIfsCache)
5658{
5659 int rc = VINF_SUCCESS;
5660 int rc2;
5661 bool fLockWrite = false;
5662 PVDCACHE pCache = NULL;
5663
5664 LogFlowFunc(("pDisk=%#p pszBackend=\"%s\" pszFilename=\"%s\" uOpenFlags=%#x, pVDIfsCache=%#p\n",
5665 pDisk, pszBackend, pszFilename, uOpenFlags, pVDIfsCache));
5666
5667 do
5668 {
5669 /* sanity check */
5670 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
5671 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
5672
5673 /* Check arguments. */
5674 AssertMsgBreakStmt(VALID_PTR(pszBackend) && *pszBackend,
5675 ("pszBackend=%#p \"%s\"\n", pszBackend, pszBackend),
5676 rc = VERR_INVALID_PARAMETER);
5677 AssertMsgBreakStmt(VALID_PTR(pszFilename) && *pszFilename,
5678 ("pszFilename=%#p \"%s\"\n", pszFilename, pszFilename),
5679 rc = VERR_INVALID_PARAMETER);
5680 AssertMsgBreakStmt((uOpenFlags & ~VD_OPEN_FLAGS_MASK) == 0,
5681 ("uOpenFlags=%#x\n", uOpenFlags),
5682 rc = VERR_INVALID_PARAMETER);
5683
5684 /* Set up image descriptor. */
5685 pCache = (PVDCACHE)RTMemAllocZ(sizeof(VDCACHE));
5686 if (!pCache)
5687 {
5688 rc = VERR_NO_MEMORY;
5689 break;
5690 }
5691 pCache->pszFilename = RTStrDup(pszFilename);
5692 if (!pCache->pszFilename)
5693 {
5694 rc = VERR_NO_MEMORY;
5695 break;
5696 }
5697
5698 pCache->VDIo.pDisk = pDisk;
5699 pCache->pVDIfsCache = pVDIfsCache;
5700
5701 rc = vdFindCacheBackend(pszBackend, &pCache->Backend);
5702 if (RT_FAILURE(rc))
5703 break;
5704 if (!pCache->Backend)
5705 {
5706 rc = vdError(pDisk, VERR_INVALID_PARAMETER, RT_SRC_POS,
5707 N_("VD: unknown backend name '%s'"), pszBackend);
5708 break;
5709 }
5710
5711 /* Set up the I/O interface. */
5712 pCache->VDIo.pInterfaceIo = VDIfIoGet(pVDIfsCache);
5713 if (!pCache->VDIo.pInterfaceIo)
5714 {
5715 vdIfIoFallbackCallbacksSetup(&pCache->VDIo.VDIfIo);
5716 rc = VDInterfaceAdd(&pCache->VDIo.VDIfIo.Core, "VD_IO", VDINTERFACETYPE_IO,
5717 pDisk, sizeof(VDINTERFACEIO), &pVDIfsCache);
5718 pCache->VDIo.pInterfaceIo = &pCache->VDIo.VDIfIo;
5719 }
5720
5721 /* Set up the internal I/O interface. */
5722 AssertBreakStmt(!VDIfIoIntGet(pVDIfsCache), rc = VERR_INVALID_PARAMETER);
5723 vdIfIoIntCallbacksSetup(&pCache->VDIo.VDIfIoInt);
5724 rc = VDInterfaceAdd(&pCache->VDIo.VDIfIoInt.Core, "VD_IOINT", VDINTERFACETYPE_IOINT,
5725 &pCache->VDIo, sizeof(VDINTERFACEIOINT), &pCache->pVDIfsCache);
5726 AssertRC(rc);
5727
5728 pCache->uOpenFlags = uOpenFlags & VD_OPEN_FLAGS_HONOR_SAME;
5729 rc = pCache->Backend->pfnOpen(pCache->pszFilename,
5730 uOpenFlags & ~VD_OPEN_FLAGS_HONOR_SAME,
5731 pDisk->pVDIfsDisk,
5732 pCache->pVDIfsCache,
5733 &pCache->pBackendData);
5734 /* If the open in read-write mode failed, retry in read-only mode. */
5735 if (RT_FAILURE(rc))
5736 {
5737 if (!(uOpenFlags & VD_OPEN_FLAGS_READONLY)
5738 && ( rc == VERR_ACCESS_DENIED
5739 || rc == VERR_PERMISSION_DENIED
5740 || rc == VERR_WRITE_PROTECT
5741 || rc == VERR_SHARING_VIOLATION
5742 || rc == VERR_FILE_LOCK_FAILED))
5743 rc = pCache->Backend->pfnOpen(pCache->pszFilename,
5744 (uOpenFlags & ~VD_OPEN_FLAGS_HONOR_SAME)
5745 | VD_OPEN_FLAGS_READONLY,
5746 pDisk->pVDIfsDisk,
5747 pCache->pVDIfsCache,
5748 &pCache->pBackendData);
5749 if (RT_FAILURE(rc))
5750 {
5751 rc = vdError(pDisk, rc, RT_SRC_POS,
5752 N_("VD: error %Rrc opening image file '%s'"), rc, pszFilename);
5753 break;
5754 }
5755 }
5756
5757 /* Lock disk for writing, as we modify pDisk information below. */
5758 rc2 = vdThreadStartWrite(pDisk);
5759 AssertRC(rc2);
5760 fLockWrite = true;
5761
5762 /*
5763 * Check that the modification UUID of the cache and last image
5764 * match. If not the image was modified in-between without the cache.
5765 * The cache might contain stale data.
5766 */
5767 RTUUID UuidImage, UuidCache;
5768
5769 rc = pCache->Backend->pfnGetModificationUuid(pCache->pBackendData,
5770 &UuidCache);
5771 if (RT_SUCCESS(rc))
5772 {
5773 rc = pDisk->pLast->Backend->pfnGetModificationUuid(pDisk->pLast->pBackendData,
5774 &UuidImage);
5775 if (RT_SUCCESS(rc))
5776 {
5777 if (RTUuidCompare(&UuidImage, &UuidCache))
5778 rc = VERR_VD_CACHE_NOT_UP_TO_DATE;
5779 }
5780 }
5781
5782 /*
5783 * We assume that the user knows what he is doing if one of the images
5784 * doesn't support the modification uuid.
5785 */
5786 if (rc == VERR_NOT_SUPPORTED)
5787 rc = VINF_SUCCESS;
5788
5789 if (RT_SUCCESS(rc))
5790 {
5791 /* Cache successfully opened, make it the current one. */
5792 if (!pDisk->pCache)
5793 pDisk->pCache = pCache;
5794 else
5795 rc = VERR_VD_CACHE_ALREADY_EXISTS;
5796 }
5797
5798 if (RT_FAILURE(rc))
5799 {
5800 /* Error detected, but image opened. Close image. */
5801 rc2 = pCache->Backend->pfnClose(pCache->pBackendData, false);
5802 AssertRC(rc2);
5803 pCache->pBackendData = NULL;
5804 }
5805 } while (0);
5806
5807 if (RT_UNLIKELY(fLockWrite))
5808 {
5809 rc2 = vdThreadFinishWrite(pDisk);
5810 AssertRC(rc2);
5811 }
5812
5813 if (RT_FAILURE(rc))
5814 {
5815 if (pCache)
5816 {
5817 if (pCache->pszFilename)
5818 RTStrFree(pCache->pszFilename);
5819 RTMemFree(pCache);
5820 }
5821 }
5822
5823 LogFlowFunc(("returns %Rrc\n", rc));
5824 return rc;
5825}
5826
5827/**
5828 * Creates and opens a new base image file.
5829 *
5830 * @returns VBox status code.
5831 * @param pDisk Pointer to HDD container.
5832 * @param pszBackend Name of the image file backend to use.
5833 * @param pszFilename Name of the image file to create.
5834 * @param cbSize Image size in bytes.
5835 * @param uImageFlags Flags specifying special image features.
5836 * @param pszComment Pointer to image comment. NULL is ok.
5837 * @param pPCHSGeometry Pointer to physical disk geometry <= (16383,16,63). Not NULL.
5838 * @param pLCHSGeometry Pointer to logical disk geometry <= (x,255,63). Not NULL.
5839 * @param pUuid New UUID of the image. If NULL, a new UUID is created.
5840 * @param uOpenFlags Image file open mode, see VD_OPEN_FLAGS_* constants.
5841 * @param pVDIfsImage Pointer to the per-image VD interface list.
5842 * @param pVDIfsOperation Pointer to the per-operation VD interface list.
5843 */
5844VBOXDDU_DECL(int) VDCreateBase(PVBOXHDD pDisk, const char *pszBackend,
5845 const char *pszFilename, uint64_t cbSize,
5846 unsigned uImageFlags, const char *pszComment,
5847 PCVDGEOMETRY pPCHSGeometry,
5848 PCVDGEOMETRY pLCHSGeometry,
5849 PCRTUUID pUuid, unsigned uOpenFlags,
5850 PVDINTERFACE pVDIfsImage,
5851 PVDINTERFACE pVDIfsOperation)
5852{
5853 int rc = VINF_SUCCESS;
5854 int rc2;
5855 bool fLockWrite = false, fLockRead = false;
5856 PVDIMAGE pImage = NULL;
5857 RTUUID uuid;
5858
5859 LogFlowFunc(("pDisk=%#p pszBackend=\"%s\" pszFilename=\"%s\" cbSize=%llu uImageFlags=%#x pszComment=\"%s\" PCHS=%u/%u/%u LCHS=%u/%u/%u Uuid=%RTuuid uOpenFlags=%#x pVDIfsImage=%#p pVDIfsOperation=%#p\n",
5860 pDisk, pszBackend, pszFilename, cbSize, uImageFlags, pszComment,
5861 pPCHSGeometry->cCylinders, pPCHSGeometry->cHeads,
5862 pPCHSGeometry->cSectors, pLCHSGeometry->cCylinders,
5863 pLCHSGeometry->cHeads, pLCHSGeometry->cSectors, pUuid,
5864 uOpenFlags, pVDIfsImage, pVDIfsOperation));
5865
5866 PVDINTERFACEPROGRESS pIfProgress = VDIfProgressGet(pVDIfsOperation);
5867
5868 do
5869 {
5870 /* sanity check */
5871 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
5872 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
5873
5874 /* Check arguments. */
5875 AssertMsgBreakStmt(VALID_PTR(pszBackend) && *pszBackend,
5876 ("pszBackend=%#p \"%s\"\n", pszBackend, pszBackend),
5877 rc = VERR_INVALID_PARAMETER);
5878 AssertMsgBreakStmt(VALID_PTR(pszFilename) && *pszFilename,
5879 ("pszFilename=%#p \"%s\"\n", pszFilename, pszFilename),
5880 rc = VERR_INVALID_PARAMETER);
5881 AssertMsgBreakStmt(cbSize,
5882 ("cbSize=%llu\n", cbSize),
5883 rc = VERR_INVALID_PARAMETER);
5884 AssertMsgBreakStmt( ((uImageFlags & ~VD_IMAGE_FLAGS_MASK) == 0)
5885 || ((uImageFlags & (VD_IMAGE_FLAGS_FIXED | VD_IMAGE_FLAGS_DIFF)) != VD_IMAGE_FLAGS_FIXED),
5886 ("uImageFlags=%#x\n", uImageFlags),
5887 rc = VERR_INVALID_PARAMETER);
5888 /* The PCHS geometry fields may be 0 to leave it for later. */
5889 AssertMsgBreakStmt( VALID_PTR(pPCHSGeometry)
5890 && pPCHSGeometry->cHeads <= 16
5891 && pPCHSGeometry->cSectors <= 63,
5892 ("pPCHSGeometry=%#p PCHS=%u/%u/%u\n", pPCHSGeometry,
5893 pPCHSGeometry->cCylinders, pPCHSGeometry->cHeads,
5894 pPCHSGeometry->cSectors),
5895 rc = VERR_INVALID_PARAMETER);
5896 /* The LCHS geometry fields may be 0 to leave it to later autodetection. */
5897 AssertMsgBreakStmt( VALID_PTR(pLCHSGeometry)
5898 && pLCHSGeometry->cHeads <= 255
5899 && pLCHSGeometry->cSectors <= 63,
5900 ("pLCHSGeometry=%#p LCHS=%u/%u/%u\n", pLCHSGeometry,
5901 pLCHSGeometry->cCylinders, pLCHSGeometry->cHeads,
5902 pLCHSGeometry->cSectors),
5903 rc = VERR_INVALID_PARAMETER);
5904 /* The UUID may be NULL. */
5905 AssertMsgBreakStmt(pUuid == NULL || VALID_PTR(pUuid),
5906 ("pUuid=%#p UUID=%RTuuid\n", pUuid, pUuid),
5907 rc = VERR_INVALID_PARAMETER);
5908 AssertMsgBreakStmt((uOpenFlags & ~VD_OPEN_FLAGS_MASK) == 0,
5909 ("uOpenFlags=%#x\n", uOpenFlags),
5910 rc = VERR_INVALID_PARAMETER);
5911
5912 /* Check state. Needs a temporary read lock. Holding the write lock
5913 * all the time would be blocking other activities for too long. */
5914 rc2 = vdThreadStartRead(pDisk);
5915 AssertRC(rc2);
5916 fLockRead = true;
5917 AssertMsgBreakStmt(pDisk->cImages == 0,
5918 ("Create base image cannot be done with other images open\n"),
5919 rc = VERR_VD_INVALID_STATE);
5920 rc2 = vdThreadFinishRead(pDisk);
5921 AssertRC(rc2);
5922 fLockRead = false;
5923
5924 /* Set up image descriptor. */
5925 pImage = (PVDIMAGE)RTMemAllocZ(sizeof(VDIMAGE));
5926 if (!pImage)
5927 {
5928 rc = VERR_NO_MEMORY;
5929 break;
5930 }
5931 pImage->pszFilename = RTStrDup(pszFilename);
5932 if (!pImage->pszFilename)
5933 {
5934 rc = VERR_NO_MEMORY;
5935 break;
5936 }
5937 pImage->VDIo.pDisk = pDisk;
5938 pImage->pVDIfsImage = pVDIfsImage;
5939
5940 /* Set up the I/O interface. */
5941 pImage->VDIo.pInterfaceIo = VDIfIoGet(pVDIfsImage);
5942 if (!pImage->VDIo.pInterfaceIo)
5943 {
5944 vdIfIoFallbackCallbacksSetup(&pImage->VDIo.VDIfIo);
5945 rc = VDInterfaceAdd(&pImage->VDIo.VDIfIo.Core, "VD_IO", VDINTERFACETYPE_IO,
5946 pDisk, sizeof(VDINTERFACEIO), &pVDIfsImage);
5947 pImage->VDIo.pInterfaceIo = &pImage->VDIo.VDIfIo;
5948 }
5949
5950 /* Set up the internal I/O interface. */
5951 AssertBreakStmt(!VDIfIoIntGet(pVDIfsImage), rc = VERR_INVALID_PARAMETER);
5952 vdIfIoIntCallbacksSetup(&pImage->VDIo.VDIfIoInt);
5953 rc = VDInterfaceAdd(&pImage->VDIo.VDIfIoInt.Core, "VD_IOINT", VDINTERFACETYPE_IOINT,
5954 &pImage->VDIo, sizeof(VDINTERFACEIOINT), &pImage->pVDIfsImage);
5955 AssertRC(rc);
5956
5957 rc = vdFindBackend(pszBackend, &pImage->Backend);
5958 if (RT_FAILURE(rc))
5959 break;
5960 if (!pImage->Backend)
5961 {
5962 rc = vdError(pDisk, VERR_INVALID_PARAMETER, RT_SRC_POS,
5963 N_("VD: unknown backend name '%s'"), pszBackend);
5964 break;
5965 }
5966 if (!(pImage->Backend->uBackendCaps & ( VD_CAP_CREATE_FIXED
5967 | VD_CAP_CREATE_DYNAMIC)))
5968 {
5969 rc = vdError(pDisk, VERR_INVALID_PARAMETER, RT_SRC_POS,
5970 N_("VD: backend '%s' cannot create base images"), pszBackend);
5971 break;
5972 }
5973
5974 /* Create UUID if the caller didn't specify one. */
5975 if (!pUuid)
5976 {
5977 rc = RTUuidCreate(&uuid);
5978 if (RT_FAILURE(rc))
5979 {
5980 rc = vdError(pDisk, rc, RT_SRC_POS,
5981 N_("VD: cannot generate UUID for image '%s'"),
5982 pszFilename);
5983 break;
5984 }
5985 pUuid = &uuid;
5986 }
5987
5988 pImage->uOpenFlags = uOpenFlags & VD_OPEN_FLAGS_HONOR_SAME;
5989 uImageFlags &= ~VD_IMAGE_FLAGS_DIFF;
5990 pImage->VDIo.fIgnoreFlush = (uOpenFlags & VD_OPEN_FLAGS_IGNORE_FLUSH) != 0;
5991 rc = pImage->Backend->pfnCreate(pImage->pszFilename, cbSize,
5992 uImageFlags, pszComment, pPCHSGeometry,
5993 pLCHSGeometry, pUuid,
5994 uOpenFlags & ~VD_OPEN_FLAGS_HONOR_SAME,
5995 0, 99,
5996 pDisk->pVDIfsDisk,
5997 pImage->pVDIfsImage,
5998 pVDIfsOperation,
5999 &pImage->pBackendData);
6000
6001 if (RT_SUCCESS(rc))
6002 {
6003 pImage->VDIo.pBackendData = pImage->pBackendData;
6004 pImage->uImageFlags = uImageFlags;
6005
6006 /* Force sane optimization settings. It's not worth avoiding writes
6007 * to fixed size images. The overhead would have almost no payback. */
6008 if (uImageFlags & VD_IMAGE_FLAGS_FIXED)
6009 pImage->uOpenFlags |= VD_OPEN_FLAGS_HONOR_SAME;
6010
6011 /* Lock disk for writing, as we modify pDisk information below. */
6012 rc2 = vdThreadStartWrite(pDisk);
6013 AssertRC(rc2);
6014 fLockWrite = true;
6015
6016 /** @todo optionally check UUIDs */
6017
6018 /* Re-check state, as the lock wasn't held and another image
6019 * creation call could have been done by another thread. */
6020 AssertMsgStmt(pDisk->cImages == 0,
6021 ("Create base image cannot be done with other images open\n"),
6022 rc = VERR_VD_INVALID_STATE);
6023 }
6024
6025 if (RT_SUCCESS(rc))
6026 {
6027 /* Cache disk information. */
6028 pDisk->cbSize = pImage->Backend->pfnGetSize(pImage->pBackendData);
6029
6030 /* Cache PCHS geometry. */
6031 rc2 = pImage->Backend->pfnGetPCHSGeometry(pImage->pBackendData,
6032 &pDisk->PCHSGeometry);
6033 if (RT_FAILURE(rc2))
6034 {
6035 pDisk->PCHSGeometry.cCylinders = 0;
6036 pDisk->PCHSGeometry.cHeads = 0;
6037 pDisk->PCHSGeometry.cSectors = 0;
6038 }
6039 else
6040 {
6041 /* Make sure the CHS geometry is properly clipped. */
6042 pDisk->PCHSGeometry.cCylinders = RT_MIN(pDisk->PCHSGeometry.cCylinders, 16383);
6043 pDisk->PCHSGeometry.cHeads = RT_MIN(pDisk->PCHSGeometry.cHeads, 16);
6044 pDisk->PCHSGeometry.cSectors = RT_MIN(pDisk->PCHSGeometry.cSectors, 63);
6045 }
6046
6047 /* Cache LCHS geometry. */
6048 rc2 = pImage->Backend->pfnGetLCHSGeometry(pImage->pBackendData,
6049 &pDisk->LCHSGeometry);
6050 if (RT_FAILURE(rc2))
6051 {
6052 pDisk->LCHSGeometry.cCylinders = 0;
6053 pDisk->LCHSGeometry.cHeads = 0;
6054 pDisk->LCHSGeometry.cSectors = 0;
6055 }
6056 else
6057 {
6058 /* Make sure the CHS geometry is properly clipped. */
6059 pDisk->LCHSGeometry.cHeads = RT_MIN(pDisk->LCHSGeometry.cHeads, 255);
6060 pDisk->LCHSGeometry.cSectors = RT_MIN(pDisk->LCHSGeometry.cSectors, 63);
6061 }
6062
6063 /* Image successfully opened, make it the last image. */
6064 vdAddImageToList(pDisk, pImage);
6065 if (!(uOpenFlags & VD_OPEN_FLAGS_READONLY))
6066 pDisk->uModified = VD_IMAGE_MODIFIED_FIRST;
6067 }
6068 else
6069 {
6070 /* Error detected, image may or may not be opened. Close and delete
6071 * image if it was opened. */
6072 if (pImage->pBackendData)
6073 {
6074 rc2 = pImage->Backend->pfnClose(pImage->pBackendData, true);
6075 AssertRC(rc2);
6076 pImage->pBackendData = NULL;
6077 }
6078 }
6079 } while (0);
6080
6081 if (RT_UNLIKELY(fLockWrite))
6082 {
6083 rc2 = vdThreadFinishWrite(pDisk);
6084 AssertRC(rc2);
6085 }
6086 else if (RT_UNLIKELY(fLockRead))
6087 {
6088 rc2 = vdThreadFinishRead(pDisk);
6089 AssertRC(rc2);
6090 }
6091
6092 if (RT_FAILURE(rc))
6093 {
6094 if (pImage)
6095 {
6096 if (pImage->pszFilename)
6097 RTStrFree(pImage->pszFilename);
6098 RTMemFree(pImage);
6099 }
6100 }
6101
6102 if (RT_SUCCESS(rc) && pIfProgress && pIfProgress->pfnProgress)
6103 pIfProgress->pfnProgress(pIfProgress->Core.pvUser, 100);
6104
6105 LogFlowFunc(("returns %Rrc\n", rc));
6106 return rc;
6107}
6108
6109/**
6110 * Creates and opens a new differencing image file in HDD container.
6111 * See comments for VDOpen function about differencing images.
6112 *
6113 * @returns VBox status code.
6114 * @param pDisk Pointer to HDD container.
6115 * @param pszBackend Name of the image file backend to use.
6116 * @param pszFilename Name of the differencing image file to create.
6117 * @param uImageFlags Flags specifying special image features.
6118 * @param pszComment Pointer to image comment. NULL is ok.
6119 * @param pUuid New UUID of the image. If NULL, a new UUID is created.
6120 * @param pParentUuid New parent UUID of the image. If NULL, the UUID is queried automatically.
6121 * @param uOpenFlags Image file open mode, see VD_OPEN_FLAGS_* constants.
6122 * @param pVDIfsImage Pointer to the per-image VD interface list.
6123 * @param pVDIfsOperation Pointer to the per-operation VD interface list.
6124 */
6125VBOXDDU_DECL(int) VDCreateDiff(PVBOXHDD pDisk, const char *pszBackend,
6126 const char *pszFilename, unsigned uImageFlags,
6127 const char *pszComment, PCRTUUID pUuid,
6128 PCRTUUID pParentUuid, unsigned uOpenFlags,
6129 PVDINTERFACE pVDIfsImage,
6130 PVDINTERFACE pVDIfsOperation)
6131{
6132 int rc = VINF_SUCCESS;
6133 int rc2;
6134 bool fLockWrite = false, fLockRead = false;
6135 PVDIMAGE pImage = NULL;
6136 RTUUID uuid;
6137
6138 LogFlowFunc(("pDisk=%#p pszBackend=\"%s\" pszFilename=\"%s\" uImageFlags=%#x pszComment=\"%s\" Uuid=%RTuuid uOpenFlags=%#x pVDIfsImage=%#p pVDIfsOperation=%#p\n",
6139 pDisk, pszBackend, pszFilename, uImageFlags, pszComment, pUuid, uOpenFlags, pVDIfsImage, pVDIfsOperation));
6140
6141 PVDINTERFACEPROGRESS pIfProgress = VDIfProgressGet(pVDIfsOperation);
6142
6143 do
6144 {
6145 /* sanity check */
6146 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
6147 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
6148
6149 /* Check arguments. */
6150 AssertMsgBreakStmt(VALID_PTR(pszBackend) && *pszBackend,
6151 ("pszBackend=%#p \"%s\"\n", pszBackend, pszBackend),
6152 rc = VERR_INVALID_PARAMETER);
6153 AssertMsgBreakStmt(VALID_PTR(pszFilename) && *pszFilename,
6154 ("pszFilename=%#p \"%s\"\n", pszFilename, pszFilename),
6155 rc = VERR_INVALID_PARAMETER);
6156 AssertMsgBreakStmt((uImageFlags & ~VD_IMAGE_FLAGS_MASK) == 0,
6157 ("uImageFlags=%#x\n", uImageFlags),
6158 rc = VERR_INVALID_PARAMETER);
6159 /* The UUID may be NULL. */
6160 AssertMsgBreakStmt(pUuid == NULL || VALID_PTR(pUuid),
6161 ("pUuid=%#p UUID=%RTuuid\n", pUuid, pUuid),
6162 rc = VERR_INVALID_PARAMETER);
6163 /* The parent UUID may be NULL. */
6164 AssertMsgBreakStmt(pParentUuid == NULL || VALID_PTR(pParentUuid),
6165 ("pParentUuid=%#p ParentUUID=%RTuuid\n", pParentUuid, pParentUuid),
6166 rc = VERR_INVALID_PARAMETER);
6167 AssertMsgBreakStmt((uOpenFlags & ~VD_OPEN_FLAGS_MASK) == 0,
6168 ("uOpenFlags=%#x\n", uOpenFlags),
6169 rc = VERR_INVALID_PARAMETER);
6170
6171 /* Check state. Needs a temporary read lock. Holding the write lock
6172 * all the time would be blocking other activities for too long. */
6173 rc2 = vdThreadStartRead(pDisk);
6174 AssertRC(rc2);
6175 fLockRead = true;
6176 AssertMsgBreakStmt(pDisk->cImages != 0,
6177 ("Create diff image cannot be done without other images open\n"),
6178 rc = VERR_VD_INVALID_STATE);
6179 rc2 = vdThreadFinishRead(pDisk);
6180 AssertRC(rc2);
6181 fLockRead = false;
6182
6183 /*
6184 * Destroy the current discard state first which might still have pending blocks
6185 * for the currently opened image which will be switched to readonly mode.
6186 */
6187 /* Lock disk for writing, as we modify pDisk information below. */
6188 rc2 = vdThreadStartWrite(pDisk);
6189 AssertRC(rc2);
6190 fLockWrite = true;
6191 rc = vdDiscardStateDestroy(pDisk);
6192 if (RT_FAILURE(rc))
6193 break;
6194 rc2 = vdThreadFinishWrite(pDisk);
6195 AssertRC(rc2);
6196 fLockWrite = false;
6197
6198 /* Set up image descriptor. */
6199 pImage = (PVDIMAGE)RTMemAllocZ(sizeof(VDIMAGE));
6200 if (!pImage)
6201 {
6202 rc = VERR_NO_MEMORY;
6203 break;
6204 }
6205 pImage->pszFilename = RTStrDup(pszFilename);
6206 if (!pImage->pszFilename)
6207 {
6208 rc = VERR_NO_MEMORY;
6209 break;
6210 }
6211
6212 rc = vdFindBackend(pszBackend, &pImage->Backend);
6213 if (RT_FAILURE(rc))
6214 break;
6215 if (!pImage->Backend)
6216 {
6217 rc = vdError(pDisk, VERR_INVALID_PARAMETER, RT_SRC_POS,
6218 N_("VD: unknown backend name '%s'"), pszBackend);
6219 break;
6220 }
6221 if ( !(pImage->Backend->uBackendCaps & VD_CAP_DIFF)
6222 || !(pImage->Backend->uBackendCaps & ( VD_CAP_CREATE_FIXED
6223 | VD_CAP_CREATE_DYNAMIC)))
6224 {
6225 rc = vdError(pDisk, VERR_INVALID_PARAMETER, RT_SRC_POS,
6226 N_("VD: backend '%s' cannot create diff images"), pszBackend);
6227 break;
6228 }
6229
6230 pImage->VDIo.pDisk = pDisk;
6231 pImage->pVDIfsImage = pVDIfsImage;
6232
6233 /* Set up the I/O interface. */
6234 pImage->VDIo.pInterfaceIo = VDIfIoGet(pVDIfsImage);
6235 if (!pImage->VDIo.pInterfaceIo)
6236 {
6237 vdIfIoFallbackCallbacksSetup(&pImage->VDIo.VDIfIo);
6238 rc = VDInterfaceAdd(&pImage->VDIo.VDIfIo.Core, "VD_IO", VDINTERFACETYPE_IO,
6239 pDisk, sizeof(VDINTERFACEIO), &pVDIfsImage);
6240 pImage->VDIo.pInterfaceIo = &pImage->VDIo.VDIfIo;
6241 }
6242
6243 /* Set up the internal I/O interface. */
6244 AssertBreakStmt(!VDIfIoIntGet(pVDIfsImage), rc = VERR_INVALID_PARAMETER);
6245 vdIfIoIntCallbacksSetup(&pImage->VDIo.VDIfIoInt);
6246 rc = VDInterfaceAdd(&pImage->VDIo.VDIfIoInt.Core, "VD_IOINT", VDINTERFACETYPE_IOINT,
6247 &pImage->VDIo, sizeof(VDINTERFACEIOINT), &pImage->pVDIfsImage);
6248 AssertRC(rc);
6249
6250 /* Create UUID if the caller didn't specify one. */
6251 if (!pUuid)
6252 {
6253 rc = RTUuidCreate(&uuid);
6254 if (RT_FAILURE(rc))
6255 {
6256 rc = vdError(pDisk, rc, RT_SRC_POS,
6257 N_("VD: cannot generate UUID for image '%s'"),
6258 pszFilename);
6259 break;
6260 }
6261 pUuid = &uuid;
6262 }
6263
6264 pImage->uOpenFlags = uOpenFlags & VD_OPEN_FLAGS_HONOR_SAME;
6265 pImage->VDIo.fIgnoreFlush = (uOpenFlags & VD_OPEN_FLAGS_IGNORE_FLUSH) != 0;
6266 uImageFlags |= VD_IMAGE_FLAGS_DIFF;
6267 rc = pImage->Backend->pfnCreate(pImage->pszFilename, pDisk->cbSize,
6268 uImageFlags | VD_IMAGE_FLAGS_DIFF,
6269 pszComment, &pDisk->PCHSGeometry,
6270 &pDisk->LCHSGeometry, pUuid,
6271 uOpenFlags & ~VD_OPEN_FLAGS_HONOR_SAME,
6272 0, 99,
6273 pDisk->pVDIfsDisk,
6274 pImage->pVDIfsImage,
6275 pVDIfsOperation,
6276 &pImage->pBackendData);
6277
6278 if (RT_SUCCESS(rc))
6279 {
6280 pImage->VDIo.pBackendData = pImage->pBackendData;
6281 pImage->uImageFlags = uImageFlags;
6282
6283 /* Lock disk for writing, as we modify pDisk information below. */
6284 rc2 = vdThreadStartWrite(pDisk);
6285 AssertRC(rc2);
6286 fLockWrite = true;
6287
6288 /* Switch previous image to read-only mode. */
6289 unsigned uOpenFlagsPrevImg;
6290 uOpenFlagsPrevImg = pDisk->pLast->Backend->pfnGetOpenFlags(pDisk->pLast->pBackendData);
6291 if (!(uOpenFlagsPrevImg & VD_OPEN_FLAGS_READONLY))
6292 {
6293 uOpenFlagsPrevImg |= VD_OPEN_FLAGS_READONLY;
6294 rc = pDisk->pLast->Backend->pfnSetOpenFlags(pDisk->pLast->pBackendData, uOpenFlagsPrevImg);
6295 }
6296
6297 /** @todo optionally check UUIDs */
6298
6299 /* Re-check state, as the lock wasn't held and another image
6300 * creation call could have been done by another thread. */
6301 AssertMsgStmt(pDisk->cImages != 0,
6302 ("Create diff image cannot be done without other images open\n"),
6303 rc = VERR_VD_INVALID_STATE);
6304 }
6305
6306 if (RT_SUCCESS(rc))
6307 {
6308 RTUUID Uuid;
6309 RTTIMESPEC ts;
6310
6311 if (pParentUuid && !RTUuidIsNull(pParentUuid))
6312 {
6313 Uuid = *pParentUuid;
6314 pImage->Backend->pfnSetParentUuid(pImage->pBackendData, &Uuid);
6315 }
6316 else
6317 {
6318 rc2 = pDisk->pLast->Backend->pfnGetUuid(pDisk->pLast->pBackendData,
6319 &Uuid);
6320 if (RT_SUCCESS(rc2))
6321 pImage->Backend->pfnSetParentUuid(pImage->pBackendData, &Uuid);
6322 }
6323 rc2 = pDisk->pLast->Backend->pfnGetModificationUuid(pDisk->pLast->pBackendData,
6324 &Uuid);
6325 if (RT_SUCCESS(rc2))
6326 pImage->Backend->pfnSetParentModificationUuid(pImage->pBackendData,
6327 &Uuid);
6328 if (pDisk->pLast->Backend->pfnGetTimeStamp)
6329 rc2 = pDisk->pLast->Backend->pfnGetTimeStamp(pDisk->pLast->pBackendData,
6330 &ts);
6331 else
6332 rc2 = VERR_NOT_IMPLEMENTED;
6333 if (RT_SUCCESS(rc2) && pImage->Backend->pfnSetParentTimeStamp)
6334 pImage->Backend->pfnSetParentTimeStamp(pImage->pBackendData, &ts);
6335
6336 if (pImage->Backend->pfnSetParentFilename)
6337 rc2 = pImage->Backend->pfnSetParentFilename(pImage->pBackendData, pDisk->pLast->pszFilename);
6338 }
6339
6340 if (RT_SUCCESS(rc))
6341 {
6342 /* Image successfully opened, make it the last image. */
6343 vdAddImageToList(pDisk, pImage);
6344 if (!(uOpenFlags & VD_OPEN_FLAGS_READONLY))
6345 pDisk->uModified = VD_IMAGE_MODIFIED_FIRST;
6346 }
6347 else
6348 {
6349 /* Error detected, but image opened. Close and delete image. */
6350 rc2 = pImage->Backend->pfnClose(pImage->pBackendData, true);
6351 AssertRC(rc2);
6352 pImage->pBackendData = NULL;
6353 }
6354 } while (0);
6355
6356 if (RT_UNLIKELY(fLockWrite))
6357 {
6358 rc2 = vdThreadFinishWrite(pDisk);
6359 AssertRC(rc2);
6360 }
6361 else if (RT_UNLIKELY(fLockRead))
6362 {
6363 rc2 = vdThreadFinishRead(pDisk);
6364 AssertRC(rc2);
6365 }
6366
6367 if (RT_FAILURE(rc))
6368 {
6369 if (pImage)
6370 {
6371 if (pImage->pszFilename)
6372 RTStrFree(pImage->pszFilename);
6373 RTMemFree(pImage);
6374 }
6375 }
6376
6377 if (RT_SUCCESS(rc) && pIfProgress && pIfProgress->pfnProgress)
6378 pIfProgress->pfnProgress(pIfProgress->Core.pvUser, 100);
6379
6380 LogFlowFunc(("returns %Rrc\n", rc));
6381 return rc;
6382}
6383
6384
6385/**
6386 * Creates and opens new cache image file in HDD container.
6387 *
6388 * @return VBox status code.
6389 * @param pDisk Name of the cache file backend to use (case insensitive).
6390 * @param pszFilename Name of the differencing cache file to create.
6391 * @param cbSize Maximum size of the cache.
6392 * @param uImageFlags Flags specifying special cache features.
6393 * @param pszComment Pointer to image comment. NULL is ok.
6394 * @param pUuid New UUID of the image. If NULL, a new UUID is created.
6395 * @param uOpenFlags Image file open mode, see VD_OPEN_FLAGS_* constants.
6396 * @param pVDIfsCache Pointer to the per-cache VD interface list.
6397 * @param pVDIfsOperation Pointer to the per-operation VD interface list.
6398 */
6399VBOXDDU_DECL(int) VDCreateCache(PVBOXHDD pDisk, const char *pszBackend,
6400 const char *pszFilename, uint64_t cbSize,
6401 unsigned uImageFlags, const char *pszComment,
6402 PCRTUUID pUuid, unsigned uOpenFlags,
6403 PVDINTERFACE pVDIfsCache, PVDINTERFACE pVDIfsOperation)
6404{
6405 int rc = VINF_SUCCESS;
6406 int rc2;
6407 bool fLockWrite = false, fLockRead = false;
6408 PVDCACHE pCache = NULL;
6409 RTUUID uuid;
6410
6411 LogFlowFunc(("pDisk=%#p pszBackend=\"%s\" pszFilename=\"%s\" cbSize=%llu uImageFlags=%#x pszComment=\"%s\" Uuid=%RTuuid uOpenFlags=%#x pVDIfsImage=%#p pVDIfsOperation=%#p\n",
6412 pDisk, pszBackend, pszFilename, cbSize, uImageFlags, pszComment, pUuid, uOpenFlags, pVDIfsCache, pVDIfsOperation));
6413
6414 PVDINTERFACEPROGRESS pIfProgress = VDIfProgressGet(pVDIfsOperation);
6415
6416 do
6417 {
6418 /* sanity check */
6419 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
6420 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
6421
6422 /* Check arguments. */
6423 AssertMsgBreakStmt(VALID_PTR(pszBackend) && *pszBackend,
6424 ("pszBackend=%#p \"%s\"\n", pszBackend, pszBackend),
6425 rc = VERR_INVALID_PARAMETER);
6426 AssertMsgBreakStmt(VALID_PTR(pszFilename) && *pszFilename,
6427 ("pszFilename=%#p \"%s\"\n", pszFilename, pszFilename),
6428 rc = VERR_INVALID_PARAMETER);
6429 AssertMsgBreakStmt(cbSize,
6430 ("cbSize=%llu\n", cbSize),
6431 rc = VERR_INVALID_PARAMETER);
6432 AssertMsgBreakStmt((uImageFlags & ~VD_IMAGE_FLAGS_MASK) == 0,
6433 ("uImageFlags=%#x\n", uImageFlags),
6434 rc = VERR_INVALID_PARAMETER);
6435 /* The UUID may be NULL. */
6436 AssertMsgBreakStmt(pUuid == NULL || VALID_PTR(pUuid),
6437 ("pUuid=%#p UUID=%RTuuid\n", pUuid, pUuid),
6438 rc = VERR_INVALID_PARAMETER);
6439 AssertMsgBreakStmt((uOpenFlags & ~VD_OPEN_FLAGS_MASK) == 0,
6440 ("uOpenFlags=%#x\n", uOpenFlags),
6441 rc = VERR_INVALID_PARAMETER);
6442
6443 /* Check state. Needs a temporary read lock. Holding the write lock
6444 * all the time would be blocking other activities for too long. */
6445 rc2 = vdThreadStartRead(pDisk);
6446 AssertRC(rc2);
6447 fLockRead = true;
6448 AssertMsgBreakStmt(!pDisk->pCache,
6449 ("Create cache image cannot be done with a cache already attached\n"),
6450 rc = VERR_VD_CACHE_ALREADY_EXISTS);
6451 rc2 = vdThreadFinishRead(pDisk);
6452 AssertRC(rc2);
6453 fLockRead = false;
6454
6455 /* Set up image descriptor. */
6456 pCache = (PVDCACHE)RTMemAllocZ(sizeof(VDCACHE));
6457 if (!pCache)
6458 {
6459 rc = VERR_NO_MEMORY;
6460 break;
6461 }
6462 pCache->pszFilename = RTStrDup(pszFilename);
6463 if (!pCache->pszFilename)
6464 {
6465 rc = VERR_NO_MEMORY;
6466 break;
6467 }
6468
6469 rc = vdFindCacheBackend(pszBackend, &pCache->Backend);
6470 if (RT_FAILURE(rc))
6471 break;
6472 if (!pCache->Backend)
6473 {
6474 rc = vdError(pDisk, VERR_INVALID_PARAMETER, RT_SRC_POS,
6475 N_("VD: unknown backend name '%s'"), pszBackend);
6476 break;
6477 }
6478
6479 pCache->VDIo.pDisk = pDisk;
6480 pCache->pVDIfsCache = pVDIfsCache;
6481
6482 /* Set up the I/O interface. */
6483 pCache->VDIo.pInterfaceIo = VDIfIoGet(pVDIfsCache);
6484 if (!pCache->VDIo.pInterfaceIo)
6485 {
6486 vdIfIoFallbackCallbacksSetup(&pCache->VDIo.VDIfIo);
6487 rc = VDInterfaceAdd(&pCache->VDIo.VDIfIo.Core, "VD_IO", VDINTERFACETYPE_IO,
6488 pDisk, sizeof(VDINTERFACEIO), &pVDIfsCache);
6489 pCache->VDIo.pInterfaceIo = &pCache->VDIo.VDIfIo;
6490 }
6491
6492 /* Set up the internal I/O interface. */
6493 AssertBreakStmt(!VDIfIoIntGet(pVDIfsCache), rc = VERR_INVALID_PARAMETER);
6494 vdIfIoIntCallbacksSetup(&pCache->VDIo.VDIfIoInt);
6495 rc = VDInterfaceAdd(&pCache->VDIo.VDIfIoInt.Core, "VD_IOINT", VDINTERFACETYPE_IOINT,
6496 &pCache->VDIo, sizeof(VDINTERFACEIOINT), &pCache->pVDIfsCache);
6497 AssertRC(rc);
6498
6499 /* Create UUID if the caller didn't specify one. */
6500 if (!pUuid)
6501 {
6502 rc = RTUuidCreate(&uuid);
6503 if (RT_FAILURE(rc))
6504 {
6505 rc = vdError(pDisk, rc, RT_SRC_POS,
6506 N_("VD: cannot generate UUID for image '%s'"),
6507 pszFilename);
6508 break;
6509 }
6510 pUuid = &uuid;
6511 }
6512
6513 pCache->uOpenFlags = uOpenFlags & VD_OPEN_FLAGS_HONOR_SAME;
6514 pCache->VDIo.fIgnoreFlush = (uOpenFlags & VD_OPEN_FLAGS_IGNORE_FLUSH) != 0;
6515 rc = pCache->Backend->pfnCreate(pCache->pszFilename, cbSize,
6516 uImageFlags,
6517 pszComment, pUuid,
6518 uOpenFlags & ~VD_OPEN_FLAGS_HONOR_SAME,
6519 0, 99,
6520 pDisk->pVDIfsDisk,
6521 pCache->pVDIfsCache,
6522 pVDIfsOperation,
6523 &pCache->pBackendData);
6524
6525 if (RT_SUCCESS(rc))
6526 {
6527 /* Lock disk for writing, as we modify pDisk information below. */
6528 rc2 = vdThreadStartWrite(pDisk);
6529 AssertRC(rc2);
6530 fLockWrite = true;
6531
6532 pCache->VDIo.pBackendData = pCache->pBackendData;
6533
6534 /* Re-check state, as the lock wasn't held and another image
6535 * creation call could have been done by another thread. */
6536 AssertMsgStmt(!pDisk->pCache,
6537 ("Create cache image cannot be done with another cache open\n"),
6538 rc = VERR_VD_CACHE_ALREADY_EXISTS);
6539 }
6540
6541 if ( RT_SUCCESS(rc)
6542 && pDisk->pLast)
6543 {
6544 RTUUID UuidModification;
6545
6546 /* Set same modification Uuid as the last image. */
6547 rc = pDisk->pLast->Backend->pfnGetModificationUuid(pDisk->pLast->pBackendData,
6548 &UuidModification);
6549 if (RT_SUCCESS(rc))
6550 {
6551 rc = pCache->Backend->pfnSetModificationUuid(pCache->pBackendData,
6552 &UuidModification);
6553 }
6554
6555 if (rc == VERR_NOT_SUPPORTED)
6556 rc = VINF_SUCCESS;
6557 }
6558
6559 if (RT_SUCCESS(rc))
6560 {
6561 /* Cache successfully created. */
6562 pDisk->pCache = pCache;
6563 }
6564 else
6565 {
6566 /* Error detected, but image opened. Close and delete image. */
6567 rc2 = pCache->Backend->pfnClose(pCache->pBackendData, true);
6568 AssertRC(rc2);
6569 pCache->pBackendData = NULL;
6570 }
6571 } while (0);
6572
6573 if (RT_UNLIKELY(fLockWrite))
6574 {
6575 rc2 = vdThreadFinishWrite(pDisk);
6576 AssertRC(rc2);
6577 }
6578 else if (RT_UNLIKELY(fLockRead))
6579 {
6580 rc2 = vdThreadFinishRead(pDisk);
6581 AssertRC(rc2);
6582 }
6583
6584 if (RT_FAILURE(rc))
6585 {
6586 if (pCache)
6587 {
6588 if (pCache->pszFilename)
6589 RTStrFree(pCache->pszFilename);
6590 RTMemFree(pCache);
6591 }
6592 }
6593
6594 if (RT_SUCCESS(rc) && pIfProgress && pIfProgress->pfnProgress)
6595 pIfProgress->pfnProgress(pIfProgress->Core.pvUser, 100);
6596
6597 LogFlowFunc(("returns %Rrc\n", rc));
6598 return rc;
6599}
6600
6601/**
6602 * Merges two images (not necessarily with direct parent/child relationship).
6603 * As a side effect the source image and potentially the other images which
6604 * are also merged to the destination are deleted from both the disk and the
6605 * images in the HDD container.
6606 *
6607 * @returns VBox status code.
6608 * @returns VERR_VD_IMAGE_NOT_FOUND if image with specified number was not opened.
6609 * @param pDisk Pointer to HDD container.
6610 * @param nImageFrom Name of the image file to merge from.
6611 * @param nImageTo Name of the image file to merge to.
6612 * @param pVDIfsOperation Pointer to the per-operation VD interface list.
6613 */
6614VBOXDDU_DECL(int) VDMerge(PVBOXHDD pDisk, unsigned nImageFrom,
6615 unsigned nImageTo, PVDINTERFACE pVDIfsOperation)
6616{
6617 int rc = VINF_SUCCESS;
6618 int rc2;
6619 bool fLockWrite = false, fLockRead = false;
6620 void *pvBuf = NULL;
6621
6622 LogFlowFunc(("pDisk=%#p nImageFrom=%u nImageTo=%u pVDIfsOperation=%#p\n",
6623 pDisk, nImageFrom, nImageTo, pVDIfsOperation));
6624
6625 PVDINTERFACEPROGRESS pIfProgress = VDIfProgressGet(pVDIfsOperation);
6626
6627 do
6628 {
6629 /* sanity check */
6630 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
6631 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
6632
6633 /* For simplicity reasons lock for writing as the image reopen below
6634 * might need it. After all the reopen is usually needed. */
6635 rc2 = vdThreadStartWrite(pDisk);
6636 AssertRC(rc2);
6637 fLockWrite = true;
6638 PVDIMAGE pImageFrom = vdGetImageByNumber(pDisk, nImageFrom);
6639 PVDIMAGE pImageTo = vdGetImageByNumber(pDisk, nImageTo);
6640 if (!pImageFrom || !pImageTo)
6641 {
6642 rc = VERR_VD_IMAGE_NOT_FOUND;
6643 break;
6644 }
6645 AssertBreakStmt(pImageFrom != pImageTo, rc = VERR_INVALID_PARAMETER);
6646
6647 /* Make sure destination image is writable. */
6648 unsigned uOpenFlags = pImageTo->Backend->pfnGetOpenFlags(pImageTo->pBackendData);
6649 if (uOpenFlags & VD_OPEN_FLAGS_READONLY)
6650 {
6651 uOpenFlags &= ~VD_OPEN_FLAGS_READONLY;
6652 rc = pImageTo->Backend->pfnSetOpenFlags(pImageTo->pBackendData,
6653 uOpenFlags);
6654 if (RT_FAILURE(rc))
6655 break;
6656 }
6657
6658 /* Get size of destination image. */
6659 uint64_t cbSize = pImageTo->Backend->pfnGetSize(pImageTo->pBackendData);
6660 rc2 = vdThreadFinishWrite(pDisk);
6661 AssertRC(rc2);
6662 fLockWrite = false;
6663
6664 /* Allocate tmp buffer. */
6665 pvBuf = RTMemTmpAlloc(VD_MERGE_BUFFER_SIZE);
6666 if (!pvBuf)
6667 {
6668 rc = VERR_NO_MEMORY;
6669 break;
6670 }
6671
6672 /* Merging is done directly on the images itself. This potentially
6673 * causes trouble if the disk is full in the middle of operation. */
6674 if (nImageFrom < nImageTo)
6675 {
6676 /* Merge parent state into child. This means writing all not
6677 * allocated blocks in the destination image which are allocated in
6678 * the images to be merged. */
6679 uint64_t uOffset = 0;
6680 uint64_t cbRemaining = cbSize;
6681 do
6682 {
6683 size_t cbThisRead = RT_MIN(VD_MERGE_BUFFER_SIZE, cbRemaining);
6684
6685 /* Need to hold the write lock during a read-write operation. */
6686 rc2 = vdThreadStartWrite(pDisk);
6687 AssertRC(rc2);
6688 fLockWrite = true;
6689
6690 rc = pImageTo->Backend->pfnRead(pImageTo->pBackendData,
6691 uOffset, pvBuf, cbThisRead,
6692 &cbThisRead);
6693 if (rc == VERR_VD_BLOCK_FREE)
6694 {
6695 /* Search for image with allocated block. Do not attempt to
6696 * read more than the previous reads marked as valid.
6697 * Otherwise this would return stale data when different
6698 * block sizes are used for the images. */
6699 for (PVDIMAGE pCurrImage = pImageTo->pPrev;
6700 pCurrImage != NULL && pCurrImage != pImageFrom->pPrev && rc == VERR_VD_BLOCK_FREE;
6701 pCurrImage = pCurrImage->pPrev)
6702 {
6703 rc = pCurrImage->Backend->pfnRead(pCurrImage->pBackendData,
6704 uOffset, pvBuf,
6705 cbThisRead,
6706 &cbThisRead);
6707 }
6708
6709 if (rc != VERR_VD_BLOCK_FREE)
6710 {
6711 if (RT_FAILURE(rc))
6712 break;
6713 /* Updating the cache is required because this might be a live merge. */
6714 rc = vdWriteHelperEx(pDisk, pImageTo, pImageFrom->pPrev,
6715 uOffset, pvBuf, cbThisRead,
6716 true /* fUpdateCache */, 0);
6717 if (RT_FAILURE(rc))
6718 break;
6719 }
6720 else
6721 rc = VINF_SUCCESS;
6722 }
6723 else if (RT_FAILURE(rc))
6724 break;
6725
6726 rc2 = vdThreadFinishWrite(pDisk);
6727 AssertRC(rc2);
6728 fLockWrite = false;
6729
6730 uOffset += cbThisRead;
6731 cbRemaining -= cbThisRead;
6732
6733 if (pIfProgress && pIfProgress->pfnProgress)
6734 {
6735 /** @todo r=klaus: this can update the progress to the same
6736 * percentage over and over again if the image format makes
6737 * relatively small increments. */
6738 rc = pIfProgress->pfnProgress(pIfProgress->Core.pvUser,
6739 uOffset * 99 / cbSize);
6740 if (RT_FAILURE(rc))
6741 break;
6742 }
6743 } while (uOffset < cbSize);
6744 }
6745 else
6746 {
6747 /*
6748 * We may need to update the parent uuid of the child coming after
6749 * the last image to be merged. We have to reopen it read/write.
6750 *
6751 * This is done before we do the actual merge to prevent an
6752 * inconsistent chain if the mode change fails for some reason.
6753 */
6754 if (pImageFrom->pNext)
6755 {
6756 PVDIMAGE pImageChild = pImageFrom->pNext;
6757
6758 /* Take the write lock. */
6759 rc2 = vdThreadStartWrite(pDisk);
6760 AssertRC(rc2);
6761 fLockWrite = true;
6762
6763 /* We need to open the image in read/write mode. */
6764 uOpenFlags = pImageChild->Backend->pfnGetOpenFlags(pImageChild->pBackendData);
6765
6766 if (uOpenFlags & VD_OPEN_FLAGS_READONLY)
6767 {
6768 uOpenFlags &= ~VD_OPEN_FLAGS_READONLY;
6769 rc = pImageChild->Backend->pfnSetOpenFlags(pImageChild->pBackendData,
6770 uOpenFlags);
6771 if (RT_FAILURE(rc))
6772 break;
6773 }
6774
6775 rc2 = vdThreadFinishWrite(pDisk);
6776 AssertRC(rc2);
6777 fLockWrite = false;
6778 }
6779
6780 /* If the merge is from the last image we have to relay all writes
6781 * to the merge destination as well, so that concurrent writes
6782 * (in case of a live merge) are handled correctly. */
6783 if (!pImageFrom->pNext)
6784 {
6785 /* Take the write lock. */
6786 rc2 = vdThreadStartWrite(pDisk);
6787 AssertRC(rc2);
6788 fLockWrite = true;
6789
6790 pDisk->pImageRelay = pImageTo;
6791
6792 rc2 = vdThreadFinishWrite(pDisk);
6793 AssertRC(rc2);
6794 fLockWrite = false;
6795 }
6796
6797 /* Merge child state into parent. This means writing all blocks
6798 * which are allocated in the image up to the source image to the
6799 * destination image. */
6800 uint64_t uOffset = 0;
6801 uint64_t cbRemaining = cbSize;
6802 do
6803 {
6804 size_t cbThisRead = RT_MIN(VD_MERGE_BUFFER_SIZE, cbRemaining);
6805 rc = VERR_VD_BLOCK_FREE;
6806
6807 /* Need to hold the write lock during a read-write operation. */
6808 rc2 = vdThreadStartWrite(pDisk);
6809 AssertRC(rc2);
6810 fLockWrite = true;
6811
6812 /* Search for image with allocated block. Do not attempt to
6813 * read more than the previous reads marked as valid. Otherwise
6814 * this would return stale data when different block sizes are
6815 * used for the images. */
6816 for (PVDIMAGE pCurrImage = pImageFrom;
6817 pCurrImage != NULL && pCurrImage != pImageTo && rc == VERR_VD_BLOCK_FREE;
6818 pCurrImage = pCurrImage->pPrev)
6819 {
6820 rc = pCurrImage->Backend->pfnRead(pCurrImage->pBackendData,
6821 uOffset, pvBuf,
6822 cbThisRead, &cbThisRead);
6823 }
6824
6825 if (rc != VERR_VD_BLOCK_FREE)
6826 {
6827 if (RT_FAILURE(rc))
6828 break;
6829 rc = vdWriteHelper(pDisk, pImageTo, uOffset, pvBuf,
6830 cbThisRead, true /* fUpdateCache */);
6831 if (RT_FAILURE(rc))
6832 break;
6833 }
6834 else
6835 rc = VINF_SUCCESS;
6836
6837 rc2 = vdThreadFinishWrite(pDisk);
6838 AssertRC(rc2);
6839 fLockWrite = false;
6840
6841 uOffset += cbThisRead;
6842 cbRemaining -= cbThisRead;
6843
6844 if (pIfProgress && pIfProgress->pfnProgress)
6845 {
6846 /** @todo r=klaus: this can update the progress to the same
6847 * percentage over and over again if the image format makes
6848 * relatively small increments. */
6849 rc = pIfProgress->pfnProgress(pIfProgress->Core.pvUser,
6850 uOffset * 99 / cbSize);
6851 if (RT_FAILURE(rc))
6852 break;
6853 }
6854 } while (uOffset < cbSize);
6855
6856 /* In case we set up a "write proxy" image above we must clear
6857 * this again now to prevent stray writes. Failure or not. */
6858 if (!pImageFrom->pNext)
6859 {
6860 /* Take the write lock. */
6861 rc2 = vdThreadStartWrite(pDisk);
6862 AssertRC(rc2);
6863 fLockWrite = true;
6864
6865 pDisk->pImageRelay = NULL;
6866
6867 rc2 = vdThreadFinishWrite(pDisk);
6868 AssertRC(rc2);
6869 fLockWrite = false;
6870 }
6871 }
6872
6873 /*
6874 * Leave in case of an error to avoid corrupted data in the image chain
6875 * (includes cancelling the operation by the user).
6876 */
6877 if (RT_FAILURE(rc))
6878 break;
6879
6880 /* Need to hold the write lock while finishing the merge. */
6881 rc2 = vdThreadStartWrite(pDisk);
6882 AssertRC(rc2);
6883 fLockWrite = true;
6884
6885 /* Update parent UUID so that image chain is consistent.
6886 * The two attempts work around the problem that some backends
6887 * (e.g. iSCSI) do not support UUIDs, so we exploit the fact that
6888 * so far there can only be one such image in the chain. */
6889 /** @todo needs a better long-term solution, passing the UUID
6890 * knowledge from the caller or some such */
6891 RTUUID Uuid;
6892 PVDIMAGE pImageChild = NULL;
6893 if (nImageFrom < nImageTo)
6894 {
6895 if (pImageFrom->pPrev)
6896 {
6897 /* plan A: ask the parent itself for its UUID */
6898 rc = pImageFrom->pPrev->Backend->pfnGetUuid(pImageFrom->pPrev->pBackendData,
6899 &Uuid);
6900 if (RT_FAILURE(rc))
6901 {
6902 /* plan B: ask the child of the parent for parent UUID */
6903 rc = pImageFrom->Backend->pfnGetParentUuid(pImageFrom->pBackendData,
6904 &Uuid);
6905 }
6906 AssertRC(rc);
6907 }
6908 else
6909 RTUuidClear(&Uuid);
6910 rc = pImageTo->Backend->pfnSetParentUuid(pImageTo->pBackendData,
6911 &Uuid);
6912 AssertRC(rc);
6913 }
6914 else
6915 {
6916 /* Update the parent uuid of the child of the last merged image. */
6917 if (pImageFrom->pNext)
6918 {
6919 /* plan A: ask the parent itself for its UUID */
6920 rc = pImageTo->Backend->pfnGetUuid(pImageTo->pBackendData,
6921 &Uuid);
6922 if (RT_FAILURE(rc))
6923 {
6924 /* plan B: ask the child of the parent for parent UUID */
6925 rc = pImageTo->pNext->Backend->pfnGetParentUuid(pImageTo->pNext->pBackendData,
6926 &Uuid);
6927 }
6928 AssertRC(rc);
6929
6930 rc = pImageFrom->Backend->pfnSetParentUuid(pImageFrom->pNext->pBackendData,
6931 &Uuid);
6932 AssertRC(rc);
6933
6934 pImageChild = pImageFrom->pNext;
6935 }
6936 }
6937
6938 /* Delete the no longer needed images. */
6939 PVDIMAGE pImg = pImageFrom, pTmp;
6940 while (pImg != pImageTo)
6941 {
6942 if (nImageFrom < nImageTo)
6943 pTmp = pImg->pNext;
6944 else
6945 pTmp = pImg->pPrev;
6946 vdRemoveImageFromList(pDisk, pImg);
6947 pImg->Backend->pfnClose(pImg->pBackendData, true);
6948 RTMemFree(pImg->pszFilename);
6949 RTMemFree(pImg);
6950 pImg = pTmp;
6951 }
6952
6953 /* Make sure destination image is back to read only if necessary. */
6954 if (pImageTo != pDisk->pLast)
6955 {
6956 uOpenFlags = pImageTo->Backend->pfnGetOpenFlags(pImageTo->pBackendData);
6957 uOpenFlags |= VD_OPEN_FLAGS_READONLY;
6958 rc = pImageTo->Backend->pfnSetOpenFlags(pImageTo->pBackendData,
6959 uOpenFlags);
6960 if (RT_FAILURE(rc))
6961 break;
6962 }
6963
6964 /*
6965 * Make sure the child is readonly
6966 * for the child -> parent merge direction
6967 * if necessary.
6968 */
6969 if ( nImageFrom > nImageTo
6970 && pImageChild
6971 && pImageChild != pDisk->pLast)
6972 {
6973 uOpenFlags = pImageChild->Backend->pfnGetOpenFlags(pImageChild->pBackendData);
6974 uOpenFlags |= VD_OPEN_FLAGS_READONLY;
6975 rc = pImageChild->Backend->pfnSetOpenFlags(pImageChild->pBackendData,
6976 uOpenFlags);
6977 if (RT_FAILURE(rc))
6978 break;
6979 }
6980 } while (0);
6981
6982 if (RT_UNLIKELY(fLockWrite))
6983 {
6984 rc2 = vdThreadFinishWrite(pDisk);
6985 AssertRC(rc2);
6986 }
6987 else if (RT_UNLIKELY(fLockRead))
6988 {
6989 rc2 = vdThreadFinishRead(pDisk);
6990 AssertRC(rc2);
6991 }
6992
6993 if (pvBuf)
6994 RTMemTmpFree(pvBuf);
6995
6996 if (RT_SUCCESS(rc) && pIfProgress && pIfProgress->pfnProgress)
6997 pIfProgress->pfnProgress(pIfProgress->Core.pvUser, 100);
6998
6999 LogFlowFunc(("returns %Rrc\n", rc));
7000 return rc;
7001}
7002
7003/**
7004 * Copies an image from one HDD container to another - extended version.
7005 * The copy is opened in the target HDD container.
7006 * It is possible to convert between different image formats, because the
7007 * backend for the destination may be different from the source.
7008 * If both the source and destination reference the same HDD container,
7009 * then the image is moved (by copying/deleting or renaming) to the new location.
7010 * The source container is unchanged if the move operation fails, otherwise
7011 * the image at the new location is opened in the same way as the old one was.
7012 *
7013 * @note The read/write accesses across disks are not synchronized, just the
7014 * accesses to each disk. Once there is a use case which requires a defined
7015 * read/write behavior in this situation this needs to be extended.
7016 *
7017 * @return VBox status code.
7018 * @return VERR_VD_IMAGE_NOT_FOUND if image with specified number was not opened.
7019 * @param pDiskFrom Pointer to source HDD container.
7020 * @param nImage Image number, counts from 0. 0 is always base image of container.
7021 * @param pDiskTo Pointer to destination HDD container.
7022 * @param pszBackend Name of the image file backend to use (may be NULL to use the same as the source, case insensitive).
7023 * @param pszFilename New name of the image (may be NULL to specify that the
7024 * copy destination is the destination container, or
7025 * if pDiskFrom == pDiskTo, i.e. when moving).
7026 * @param fMoveByRename If true, attempt to perform a move by renaming (if successful the new size is ignored).
7027 * @param cbSize New image size (0 means leave unchanged).
7028 * @param nImageSameFrom todo
7029 * @param nImageSameTo todo
7030 * @param uImageFlags Flags specifying special destination image features.
7031 * @param pDstUuid New UUID of the destination image. If NULL, a new UUID is created.
7032 * This parameter is used if and only if a true copy is created.
7033 * In all rename/move cases or copy to existing image cases the modification UUIDs are copied over.
7034 * @param uOpenFlags Image file open mode, see VD_OPEN_FLAGS_* constants.
7035 * Only used if the destination image is created.
7036 * @param pVDIfsOperation Pointer to the per-operation VD interface list.
7037 * @param pDstVDIfsImage Pointer to the per-image VD interface list, for the
7038 * destination image.
7039 * @param pDstVDIfsOperation Pointer to the per-operation VD interface list,
7040 * for the destination operation.
7041 */
7042VBOXDDU_DECL(int) VDCopyEx(PVBOXHDD pDiskFrom, unsigned nImage, PVBOXHDD pDiskTo,
7043 const char *pszBackend, const char *pszFilename,
7044 bool fMoveByRename, uint64_t cbSize,
7045 unsigned nImageFromSame, unsigned nImageToSame,
7046 unsigned uImageFlags, PCRTUUID pDstUuid,
7047 unsigned uOpenFlags, PVDINTERFACE pVDIfsOperation,
7048 PVDINTERFACE pDstVDIfsImage,
7049 PVDINTERFACE pDstVDIfsOperation)
7050{
7051 int rc = VINF_SUCCESS;
7052 int rc2;
7053 bool fLockReadFrom = false, fLockWriteFrom = false, fLockWriteTo = false;
7054 PVDIMAGE pImageTo = NULL;
7055
7056 LogFlowFunc(("pDiskFrom=%#p nImage=%u pDiskTo=%#p pszBackend=\"%s\" pszFilename=\"%s\" fMoveByRename=%d cbSize=%llu nImageFromSame=%u nImageToSame=%u uImageFlags=%#x pDstUuid=%#p uOpenFlags=%#x pVDIfsOperation=%#p pDstVDIfsImage=%#p pDstVDIfsOperation=%#p\n",
7057 pDiskFrom, nImage, pDiskTo, pszBackend, pszFilename, fMoveByRename, cbSize, nImageFromSame, nImageToSame, uImageFlags, pDstUuid, uOpenFlags, pVDIfsOperation, pDstVDIfsImage, pDstVDIfsOperation));
7058
7059 PVDINTERFACEPROGRESS pIfProgress = VDIfProgressGet(pVDIfsOperation);
7060 PVDINTERFACEPROGRESS pDstIfProgress = VDIfProgressGet(pDstVDIfsOperation);
7061
7062 do {
7063 /* Check arguments. */
7064 AssertMsgBreakStmt(VALID_PTR(pDiskFrom), ("pDiskFrom=%#p\n", pDiskFrom),
7065 rc = VERR_INVALID_PARAMETER);
7066 AssertMsg(pDiskFrom->u32Signature == VBOXHDDDISK_SIGNATURE,
7067 ("u32Signature=%08x\n", pDiskFrom->u32Signature));
7068
7069 rc2 = vdThreadStartRead(pDiskFrom);
7070 AssertRC(rc2);
7071 fLockReadFrom = true;
7072 PVDIMAGE pImageFrom = vdGetImageByNumber(pDiskFrom, nImage);
7073 AssertPtrBreakStmt(pImageFrom, rc = VERR_VD_IMAGE_NOT_FOUND);
7074 AssertMsgBreakStmt(VALID_PTR(pDiskTo), ("pDiskTo=%#p\n", pDiskTo),
7075 rc = VERR_INVALID_PARAMETER);
7076 AssertMsg(pDiskTo->u32Signature == VBOXHDDDISK_SIGNATURE,
7077 ("u32Signature=%08x\n", pDiskTo->u32Signature));
7078 AssertMsgBreakStmt( (nImageFromSame < nImage || nImageFromSame == VD_IMAGE_CONTENT_UNKNOWN)
7079 && (nImageToSame < pDiskTo->cImages || nImageToSame == VD_IMAGE_CONTENT_UNKNOWN)
7080 && ( (nImageFromSame == VD_IMAGE_CONTENT_UNKNOWN && nImageToSame == VD_IMAGE_CONTENT_UNKNOWN)
7081 || (nImageFromSame != VD_IMAGE_CONTENT_UNKNOWN && nImageToSame != VD_IMAGE_CONTENT_UNKNOWN)),
7082 ("nImageFromSame=%u nImageToSame=%u\n", nImageFromSame, nImageToSame),
7083 rc = VERR_INVALID_PARAMETER);
7084
7085 /* Move the image. */
7086 if (pDiskFrom == pDiskTo)
7087 {
7088 /* Rename only works when backends are the same, are file based
7089 * and the rename method is implemented. */
7090 if ( fMoveByRename
7091 && !RTStrICmp(pszBackend, pImageFrom->Backend->pszBackendName)
7092 && pImageFrom->Backend->uBackendCaps & VD_CAP_FILE
7093 && pImageFrom->Backend->pfnRename)
7094 {
7095 rc2 = vdThreadFinishRead(pDiskFrom);
7096 AssertRC(rc2);
7097 fLockReadFrom = false;
7098
7099 rc2 = vdThreadStartWrite(pDiskFrom);
7100 AssertRC(rc2);
7101 fLockWriteFrom = true;
7102 rc = pImageFrom->Backend->pfnRename(pImageFrom->pBackendData, pszFilename ? pszFilename : pImageFrom->pszFilename);
7103 break;
7104 }
7105
7106 /** @todo Moving (including shrinking/growing) of the image is
7107 * requested, but the rename attempt failed or it wasn't possible.
7108 * Must now copy image to temp location. */
7109 AssertReleaseMsgFailed(("VDCopy: moving by copy/delete not implemented\n"));
7110 }
7111
7112 /* pszFilename is allowed to be NULL, as this indicates copy to the existing image. */
7113 AssertMsgBreakStmt(pszFilename == NULL || (VALID_PTR(pszFilename) && *pszFilename),
7114 ("pszFilename=%#p \"%s\"\n", pszFilename, pszFilename),
7115 rc = VERR_INVALID_PARAMETER);
7116
7117 uint64_t cbSizeFrom;
7118 cbSizeFrom = pImageFrom->Backend->pfnGetSize(pImageFrom->pBackendData);
7119 if (cbSizeFrom == 0)
7120 {
7121 rc = VERR_VD_VALUE_NOT_FOUND;
7122 break;
7123 }
7124
7125 VDGEOMETRY PCHSGeometryFrom = {0, 0, 0};
7126 VDGEOMETRY LCHSGeometryFrom = {0, 0, 0};
7127 pImageFrom->Backend->pfnGetPCHSGeometry(pImageFrom->pBackendData, &PCHSGeometryFrom);
7128 pImageFrom->Backend->pfnGetLCHSGeometry(pImageFrom->pBackendData, &LCHSGeometryFrom);
7129
7130 RTUUID ImageUuid, ImageModificationUuid;
7131 if (pDiskFrom != pDiskTo)
7132 {
7133 if (pDstUuid)
7134 ImageUuid = *pDstUuid;
7135 else
7136 RTUuidCreate(&ImageUuid);
7137 }
7138 else
7139 {
7140 rc = pImageFrom->Backend->pfnGetUuid(pImageFrom->pBackendData, &ImageUuid);
7141 if (RT_FAILURE(rc))
7142 RTUuidCreate(&ImageUuid);
7143 }
7144 rc = pImageFrom->Backend->pfnGetModificationUuid(pImageFrom->pBackendData, &ImageModificationUuid);
7145 if (RT_FAILURE(rc))
7146 RTUuidClear(&ImageModificationUuid);
7147
7148 char szComment[1024];
7149 rc = pImageFrom->Backend->pfnGetComment(pImageFrom->pBackendData, szComment, sizeof(szComment));
7150 if (RT_FAILURE(rc))
7151 szComment[0] = '\0';
7152 else
7153 szComment[sizeof(szComment) - 1] = '\0';
7154
7155 rc2 = vdThreadFinishRead(pDiskFrom);
7156 AssertRC(rc2);
7157 fLockReadFrom = false;
7158
7159 rc2 = vdThreadStartRead(pDiskTo);
7160 AssertRC(rc2);
7161 unsigned cImagesTo = pDiskTo->cImages;
7162 rc2 = vdThreadFinishRead(pDiskTo);
7163 AssertRC(rc2);
7164
7165 if (pszFilename)
7166 {
7167 if (cbSize == 0)
7168 cbSize = cbSizeFrom;
7169
7170 /* Create destination image with the properties of source image. */
7171 /** @todo replace the VDCreateDiff/VDCreateBase calls by direct
7172 * calls to the backend. Unifies the code and reduces the API
7173 * dependencies. Would also make the synchronization explicit. */
7174 if (cImagesTo > 0)
7175 {
7176 rc = VDCreateDiff(pDiskTo, pszBackend, pszFilename,
7177 uImageFlags, szComment, &ImageUuid,
7178 NULL /* pParentUuid */,
7179 uOpenFlags & ~VD_OPEN_FLAGS_READONLY,
7180 pDstVDIfsImage, NULL);
7181
7182 rc2 = vdThreadStartWrite(pDiskTo);
7183 AssertRC(rc2);
7184 fLockWriteTo = true;
7185 } else {
7186 /** @todo hack to force creation of a fixed image for
7187 * the RAW backend, which can't handle anything else. */
7188 if (!RTStrICmp(pszBackend, "RAW"))
7189 uImageFlags |= VD_IMAGE_FLAGS_FIXED;
7190
7191 vdFixupPCHSGeometry(&PCHSGeometryFrom, cbSize);
7192 vdFixupLCHSGeometry(&LCHSGeometryFrom, cbSize);
7193
7194 rc = VDCreateBase(pDiskTo, pszBackend, pszFilename, cbSize,
7195 uImageFlags, szComment,
7196 &PCHSGeometryFrom, &LCHSGeometryFrom,
7197 NULL, uOpenFlags & ~VD_OPEN_FLAGS_READONLY,
7198 pDstVDIfsImage, NULL);
7199
7200 rc2 = vdThreadStartWrite(pDiskTo);
7201 AssertRC(rc2);
7202 fLockWriteTo = true;
7203
7204 if (RT_SUCCESS(rc) && !RTUuidIsNull(&ImageUuid))
7205 pDiskTo->pLast->Backend->pfnSetUuid(pDiskTo->pLast->pBackendData, &ImageUuid);
7206 }
7207 if (RT_FAILURE(rc))
7208 break;
7209
7210 pImageTo = pDiskTo->pLast;
7211 AssertPtrBreakStmt(pImageTo, rc = VERR_VD_IMAGE_NOT_FOUND);
7212
7213 cbSize = RT_MIN(cbSize, cbSizeFrom);
7214 }
7215 else
7216 {
7217 pImageTo = pDiskTo->pLast;
7218 AssertPtrBreakStmt(pImageTo, rc = VERR_VD_IMAGE_NOT_FOUND);
7219
7220 uint64_t cbSizeTo;
7221 cbSizeTo = pImageTo->Backend->pfnGetSize(pImageTo->pBackendData);
7222 if (cbSizeTo == 0)
7223 {
7224 rc = VERR_VD_VALUE_NOT_FOUND;
7225 break;
7226 }
7227
7228 if (cbSize == 0)
7229 cbSize = RT_MIN(cbSizeFrom, cbSizeTo);
7230
7231 vdFixupPCHSGeometry(&PCHSGeometryFrom, cbSize);
7232 vdFixupLCHSGeometry(&LCHSGeometryFrom, cbSize);
7233
7234 /* Update the geometry in the destination image. */
7235 pImageTo->Backend->pfnSetPCHSGeometry(pImageTo->pBackendData, &PCHSGeometryFrom);
7236 pImageTo->Backend->pfnSetLCHSGeometry(pImageTo->pBackendData, &LCHSGeometryFrom);
7237 }
7238
7239 rc2 = vdThreadFinishWrite(pDiskTo);
7240 AssertRC(rc2);
7241 fLockWriteTo = false;
7242
7243 /* Whether we can take the optimized copy path (false) or not.
7244 * Don't optimize if the image existed or if it is a child image. */
7245 bool fSuppressRedundantIo = ( !(pszFilename == NULL || cImagesTo > 0)
7246 || (nImageToSame != VD_IMAGE_CONTENT_UNKNOWN));
7247 unsigned cImagesFromReadBack, cImagesToReadBack;
7248
7249 if (nImageFromSame == VD_IMAGE_CONTENT_UNKNOWN)
7250 cImagesFromReadBack = 0;
7251 else
7252 {
7253 if (nImage == VD_LAST_IMAGE)
7254 cImagesFromReadBack = pDiskFrom->cImages - nImageFromSame - 1;
7255 else
7256 cImagesFromReadBack = nImage - nImageFromSame;
7257 }
7258
7259 if (nImageToSame == VD_IMAGE_CONTENT_UNKNOWN)
7260 cImagesToReadBack = 0;
7261 else
7262 cImagesToReadBack = pDiskTo->cImages - nImageToSame - 1;
7263
7264 /* Copy the data. */
7265 rc = vdCopyHelper(pDiskFrom, pImageFrom, pDiskTo, cbSize,
7266 cImagesFromReadBack, cImagesToReadBack,
7267 fSuppressRedundantIo, pIfProgress, pDstIfProgress);
7268
7269 if (RT_SUCCESS(rc))
7270 {
7271 rc2 = vdThreadStartWrite(pDiskTo);
7272 AssertRC(rc2);
7273 fLockWriteTo = true;
7274
7275 /* Only set modification UUID if it is non-null, since the source
7276 * backend might not provide a valid modification UUID. */
7277 if (!RTUuidIsNull(&ImageModificationUuid))
7278 pImageTo->Backend->pfnSetModificationUuid(pImageTo->pBackendData, &ImageModificationUuid);
7279
7280 /* Set the requested open flags if they differ from the value
7281 * required for creating the image and copying the contents. */
7282 if ( pImageTo && pszFilename
7283 && uOpenFlags != (uOpenFlags & ~VD_OPEN_FLAGS_READONLY))
7284 rc = pImageTo->Backend->pfnSetOpenFlags(pImageTo->pBackendData,
7285 uOpenFlags);
7286 }
7287 } while (0);
7288
7289 if (RT_FAILURE(rc) && pImageTo && pszFilename)
7290 {
7291 /* Take the write lock only if it is not taken. Not worth making the
7292 * above code even more complicated. */
7293 if (RT_UNLIKELY(!fLockWriteTo))
7294 {
7295 rc2 = vdThreadStartWrite(pDiskTo);
7296 AssertRC(rc2);
7297 fLockWriteTo = true;
7298 }
7299 /* Error detected, but new image created. Remove image from list. */
7300 vdRemoveImageFromList(pDiskTo, pImageTo);
7301
7302 /* Close and delete image. */
7303 rc2 = pImageTo->Backend->pfnClose(pImageTo->pBackendData, true);
7304 AssertRC(rc2);
7305 pImageTo->pBackendData = NULL;
7306
7307 /* Free remaining resources. */
7308 if (pImageTo->pszFilename)
7309 RTStrFree(pImageTo->pszFilename);
7310
7311 RTMemFree(pImageTo);
7312 }
7313
7314 if (RT_UNLIKELY(fLockWriteTo))
7315 {
7316 rc2 = vdThreadFinishWrite(pDiskTo);
7317 AssertRC(rc2);
7318 }
7319 if (RT_UNLIKELY(fLockWriteFrom))
7320 {
7321 rc2 = vdThreadFinishWrite(pDiskFrom);
7322 AssertRC(rc2);
7323 }
7324 else if (RT_UNLIKELY(fLockReadFrom))
7325 {
7326 rc2 = vdThreadFinishRead(pDiskFrom);
7327 AssertRC(rc2);
7328 }
7329
7330 if (RT_SUCCESS(rc))
7331 {
7332 if (pIfProgress && pIfProgress->pfnProgress)
7333 pIfProgress->pfnProgress(pIfProgress->Core.pvUser, 100);
7334 if (pDstIfProgress && pDstIfProgress->pfnProgress)
7335 pDstIfProgress->pfnProgress(pDstIfProgress->Core.pvUser, 100);
7336 }
7337
7338 LogFlowFunc(("returns %Rrc\n", rc));
7339 return rc;
7340}
7341
7342/**
7343 * Copies an image from one HDD container to another.
7344 * The copy is opened in the target HDD container.
7345 * It is possible to convert between different image formats, because the
7346 * backend for the destination may be different from the source.
7347 * If both the source and destination reference the same HDD container,
7348 * then the image is moved (by copying/deleting or renaming) to the new location.
7349 * The source container is unchanged if the move operation fails, otherwise
7350 * the image at the new location is opened in the same way as the old one was.
7351 *
7352 * @returns VBox status code.
7353 * @returns VERR_VD_IMAGE_NOT_FOUND if image with specified number was not opened.
7354 * @param pDiskFrom Pointer to source HDD container.
7355 * @param nImage Image number, counts from 0. 0 is always base image of container.
7356 * @param pDiskTo Pointer to destination HDD container.
7357 * @param pszBackend Name of the image file backend to use.
7358 * @param pszFilename New name of the image (may be NULL if pDiskFrom == pDiskTo).
7359 * @param fMoveByRename If true, attempt to perform a move by renaming (if successful the new size is ignored).
7360 * @param cbSize New image size (0 means leave unchanged).
7361 * @param uImageFlags Flags specifying special destination image features.
7362 * @param pDstUuid New UUID of the destination image. If NULL, a new UUID is created.
7363 * This parameter is used if and only if a true copy is created.
7364 * In all rename/move cases the UUIDs are copied over.
7365 * @param uOpenFlags Image file open mode, see VD_OPEN_FLAGS_* constants.
7366 * Only used if the destination image is created.
7367 * @param pVDIfsOperation Pointer to the per-operation VD interface list.
7368 * @param pDstVDIfsImage Pointer to the per-image VD interface list, for the
7369 * destination image.
7370 * @param pDstVDIfsOperation Pointer to the per-image VD interface list,
7371 * for the destination image.
7372 */
7373VBOXDDU_DECL(int) VDCopy(PVBOXHDD pDiskFrom, unsigned nImage, PVBOXHDD pDiskTo,
7374 const char *pszBackend, const char *pszFilename,
7375 bool fMoveByRename, uint64_t cbSize,
7376 unsigned uImageFlags, PCRTUUID pDstUuid,
7377 unsigned uOpenFlags, PVDINTERFACE pVDIfsOperation,
7378 PVDINTERFACE pDstVDIfsImage,
7379 PVDINTERFACE pDstVDIfsOperation)
7380{
7381 return VDCopyEx(pDiskFrom, nImage, pDiskTo, pszBackend, pszFilename, fMoveByRename,
7382 cbSize, VD_IMAGE_CONTENT_UNKNOWN, VD_IMAGE_CONTENT_UNKNOWN,
7383 uImageFlags, pDstUuid, uOpenFlags, pVDIfsOperation,
7384 pDstVDIfsImage, pDstVDIfsOperation);
7385}
7386
7387/**
7388 * Optimizes the storage consumption of an image. Typically the unused blocks
7389 * have to be wiped with zeroes to achieve a substantial reduced storage use.
7390 * Another optimization done is reordering the image blocks, which can provide
7391 * a significant performance boost, as reads and writes tend to use less random
7392 * file offsets.
7393 *
7394 * @return VBox status code.
7395 * @return VERR_VD_IMAGE_NOT_FOUND if image with specified number was not opened.
7396 * @return VERR_VD_IMAGE_READ_ONLY if image is not writable.
7397 * @return VERR_NOT_SUPPORTED if this kind of image can be compacted, but
7398 * the code for this isn't implemented yet.
7399 * @param pDisk Pointer to HDD container.
7400 * @param nImage Image number, counts from 0. 0 is always base image of container.
7401 * @param pVDIfsOperation Pointer to the per-operation VD interface list.
7402 */
7403VBOXDDU_DECL(int) VDCompact(PVBOXHDD pDisk, unsigned nImage,
7404 PVDINTERFACE pVDIfsOperation)
7405{
7406 int rc = VINF_SUCCESS;
7407 int rc2;
7408 bool fLockRead = false, fLockWrite = false;
7409 void *pvBuf = NULL;
7410 void *pvTmp = NULL;
7411
7412 LogFlowFunc(("pDisk=%#p nImage=%u pVDIfsOperation=%#p\n",
7413 pDisk, nImage, pVDIfsOperation));
7414
7415 PVDINTERFACEPROGRESS pIfProgress = VDIfProgressGet(pVDIfsOperation);
7416
7417 do {
7418 /* Check arguments. */
7419 AssertMsgBreakStmt(VALID_PTR(pDisk), ("pDisk=%#p\n", pDisk),
7420 rc = VERR_INVALID_PARAMETER);
7421 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE,
7422 ("u32Signature=%08x\n", pDisk->u32Signature));
7423
7424 rc2 = vdThreadStartRead(pDisk);
7425 AssertRC(rc2);
7426 fLockRead = true;
7427
7428 PVDIMAGE pImage = vdGetImageByNumber(pDisk, nImage);
7429 AssertPtrBreakStmt(pImage, rc = VERR_VD_IMAGE_NOT_FOUND);
7430
7431 /* If there is no compact callback for not file based backends then
7432 * the backend doesn't need compaction. No need to make much fuss about
7433 * this. For file based ones signal this as not yet supported. */
7434 if (!pImage->Backend->pfnCompact)
7435 {
7436 if (pImage->Backend->uBackendCaps & VD_CAP_FILE)
7437 rc = VERR_NOT_SUPPORTED;
7438 else
7439 rc = VINF_SUCCESS;
7440 break;
7441 }
7442
7443 /* Insert interface for reading parent state into per-operation list,
7444 * if there is a parent image. */
7445 VDINTERFACEPARENTSTATE VDIfParent;
7446 VDPARENTSTATEDESC ParentUser;
7447 if (pImage->pPrev)
7448 {
7449 VDIfParent.pfnParentRead = vdParentRead;
7450 ParentUser.pDisk = pDisk;
7451 ParentUser.pImage = pImage->pPrev;
7452 rc = VDInterfaceAdd(&VDIfParent.Core, "VDCompact_ParentState", VDINTERFACETYPE_PARENTSTATE,
7453 &ParentUser, sizeof(VDINTERFACEPARENTSTATE), &pVDIfsOperation);
7454 AssertRC(rc);
7455 }
7456
7457 rc2 = vdThreadFinishRead(pDisk);
7458 AssertRC(rc2);
7459 fLockRead = false;
7460
7461 rc2 = vdThreadStartWrite(pDisk);
7462 AssertRC(rc2);
7463 fLockWrite = true;
7464
7465 rc = pImage->Backend->pfnCompact(pImage->pBackendData,
7466 0, 99,
7467 pDisk->pVDIfsDisk,
7468 pImage->pVDIfsImage,
7469 pVDIfsOperation);
7470 } while (0);
7471
7472 if (RT_UNLIKELY(fLockWrite))
7473 {
7474 rc2 = vdThreadFinishWrite(pDisk);
7475 AssertRC(rc2);
7476 }
7477 else if (RT_UNLIKELY(fLockRead))
7478 {
7479 rc2 = vdThreadFinishRead(pDisk);
7480 AssertRC(rc2);
7481 }
7482
7483 if (pvBuf)
7484 RTMemTmpFree(pvBuf);
7485 if (pvTmp)
7486 RTMemTmpFree(pvTmp);
7487
7488 if (RT_SUCCESS(rc))
7489 {
7490 if (pIfProgress && pIfProgress->pfnProgress)
7491 pIfProgress->pfnProgress(pIfProgress->Core.pvUser, 100);
7492 }
7493
7494 LogFlowFunc(("returns %Rrc\n", rc));
7495 return rc;
7496}
7497
7498/**
7499 * Resizes the given disk image to the given size.
7500 *
7501 * @return VBox status
7502 * @return VERR_VD_IMAGE_READ_ONLY if image is not writable.
7503 * @return VERR_NOT_SUPPORTED if this kind of image can be compacted, but
7504 *
7505 * @param pDisk Pointer to the HDD container.
7506 * @param cbSize New size of the image.
7507 * @param pPCHSGeometry Pointer to the new physical disk geometry <= (16383,16,63). Not NULL.
7508 * @param pLCHSGeometry Pointer to the new logical disk geometry <= (x,255,63). Not NULL.
7509 * @param pVDIfsOperation Pointer to the per-operation VD interface list.
7510 */
7511VBOXDDU_DECL(int) VDResize(PVBOXHDD pDisk, uint64_t cbSize,
7512 PCVDGEOMETRY pPCHSGeometry,
7513 PCVDGEOMETRY pLCHSGeometry,
7514 PVDINTERFACE pVDIfsOperation)
7515{
7516 /** @todo r=klaus resizing was designed to be part of VDCopy, so having a separate function is not desirable. */
7517 int rc = VINF_SUCCESS;
7518 int rc2;
7519 bool fLockRead = false, fLockWrite = false;
7520
7521 LogFlowFunc(("pDisk=%#p cbSize=%llu pVDIfsOperation=%#p\n",
7522 pDisk, cbSize, pVDIfsOperation));
7523
7524 PVDINTERFACEPROGRESS pIfProgress = VDIfProgressGet(pVDIfsOperation);
7525
7526 do {
7527 /* Check arguments. */
7528 AssertMsgBreakStmt(VALID_PTR(pDisk), ("pDisk=%#p\n", pDisk),
7529 rc = VERR_INVALID_PARAMETER);
7530 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE,
7531 ("u32Signature=%08x\n", pDisk->u32Signature));
7532
7533 rc2 = vdThreadStartRead(pDisk);
7534 AssertRC(rc2);
7535 fLockRead = true;
7536
7537 /* Not supported if the disk has child images attached. */
7538 AssertMsgBreakStmt(pDisk->cImages == 1, ("cImages=%u\n", pDisk->cImages),
7539 rc = VERR_NOT_SUPPORTED);
7540
7541 PVDIMAGE pImage = pDisk->pBase;
7542
7543 /* If there is no compact callback for not file based backends then
7544 * the backend doesn't need compaction. No need to make much fuss about
7545 * this. For file based ones signal this as not yet supported. */
7546 if (!pImage->Backend->pfnResize)
7547 {
7548 if (pImage->Backend->uBackendCaps & VD_CAP_FILE)
7549 rc = VERR_NOT_SUPPORTED;
7550 else
7551 rc = VINF_SUCCESS;
7552 break;
7553 }
7554
7555 rc2 = vdThreadFinishRead(pDisk);
7556 AssertRC(rc2);
7557 fLockRead = false;
7558
7559 rc2 = vdThreadStartWrite(pDisk);
7560 AssertRC(rc2);
7561 fLockWrite = true;
7562
7563 VDGEOMETRY PCHSGeometryOld;
7564 VDGEOMETRY LCHSGeometryOld;
7565 PCVDGEOMETRY pPCHSGeometryNew;
7566 PCVDGEOMETRY pLCHSGeometryNew;
7567
7568 if (pPCHSGeometry->cCylinders == 0)
7569 {
7570 /* Auto-detect marker, calculate new value ourself. */
7571 rc = pImage->Backend->pfnGetPCHSGeometry(pImage->pBackendData, &PCHSGeometryOld);
7572 if (RT_SUCCESS(rc) && (PCHSGeometryOld.cCylinders != 0))
7573 PCHSGeometryOld.cCylinders = RT_MIN(cbSize / 512 / PCHSGeometryOld.cHeads / PCHSGeometryOld.cSectors, 16383);
7574 else if (rc == VERR_VD_GEOMETRY_NOT_SET)
7575 rc = VINF_SUCCESS;
7576
7577 pPCHSGeometryNew = &PCHSGeometryOld;
7578 }
7579 else
7580 pPCHSGeometryNew = pPCHSGeometry;
7581
7582 if (pLCHSGeometry->cCylinders == 0)
7583 {
7584 /* Auto-detect marker, calculate new value ourself. */
7585 rc = pImage->Backend->pfnGetLCHSGeometry(pImage->pBackendData, &LCHSGeometryOld);
7586 if (RT_SUCCESS(rc) && (LCHSGeometryOld.cCylinders != 0))
7587 LCHSGeometryOld.cCylinders = cbSize / 512 / LCHSGeometryOld.cHeads / LCHSGeometryOld.cSectors;
7588 else if (rc == VERR_VD_GEOMETRY_NOT_SET)
7589 rc = VINF_SUCCESS;
7590
7591 pLCHSGeometryNew = &LCHSGeometryOld;
7592 }
7593 else
7594 pLCHSGeometryNew = pLCHSGeometry;
7595
7596 if (RT_SUCCESS(rc))
7597 rc = pImage->Backend->pfnResize(pImage->pBackendData,
7598 cbSize,
7599 pPCHSGeometryNew,
7600 pLCHSGeometryNew,
7601 0, 99,
7602 pDisk->pVDIfsDisk,
7603 pImage->pVDIfsImage,
7604 pVDIfsOperation);
7605 } while (0);
7606
7607 if (RT_UNLIKELY(fLockWrite))
7608 {
7609 rc2 = vdThreadFinishWrite(pDisk);
7610 AssertRC(rc2);
7611 }
7612 else if (RT_UNLIKELY(fLockRead))
7613 {
7614 rc2 = vdThreadFinishRead(pDisk);
7615 AssertRC(rc2);
7616 }
7617
7618 if (RT_SUCCESS(rc))
7619 {
7620 if (pIfProgress && pIfProgress->pfnProgress)
7621 pIfProgress->pfnProgress(pIfProgress->Core.pvUser, 100);
7622 }
7623
7624 LogFlowFunc(("returns %Rrc\n", rc));
7625 return rc;
7626}
7627
7628/**
7629 * Closes the last opened image file in HDD container.
7630 * If previous image file was opened in read-only mode (the normal case) and
7631 * the last opened image is in read-write mode then the previous image will be
7632 * reopened in read/write mode.
7633 *
7634 * @returns VBox status code.
7635 * @returns VERR_VD_NOT_OPENED if no image is opened in HDD container.
7636 * @param pDisk Pointer to HDD container.
7637 * @param fDelete If true, delete the image from the host disk.
7638 */
7639VBOXDDU_DECL(int) VDClose(PVBOXHDD pDisk, bool fDelete)
7640{
7641 int rc = VINF_SUCCESS;
7642 int rc2;
7643 bool fLockWrite = false;
7644
7645 LogFlowFunc(("pDisk=%#p fDelete=%d\n", pDisk, fDelete));
7646 do
7647 {
7648 /* sanity check */
7649 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
7650 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
7651
7652 /* Not worth splitting this up into a read lock phase and write
7653 * lock phase, as closing an image is a relatively fast operation
7654 * dominated by the part which needs the write lock. */
7655 rc2 = vdThreadStartWrite(pDisk);
7656 AssertRC(rc2);
7657 fLockWrite = true;
7658
7659 PVDIMAGE pImage = pDisk->pLast;
7660 if (!pImage)
7661 {
7662 rc = VERR_VD_NOT_OPENED;
7663 break;
7664 }
7665
7666 /* Destroy the current discard state first which might still have pending blocks. */
7667 rc = vdDiscardStateDestroy(pDisk);
7668 if (RT_FAILURE(rc))
7669 break;
7670
7671 unsigned uOpenFlags = pImage->Backend->pfnGetOpenFlags(pImage->pBackendData);
7672 /* Remove image from list of opened images. */
7673 vdRemoveImageFromList(pDisk, pImage);
7674 /* Close (and optionally delete) image. */
7675 rc = pImage->Backend->pfnClose(pImage->pBackendData, fDelete);
7676 /* Free remaining resources related to the image. */
7677 RTStrFree(pImage->pszFilename);
7678 RTMemFree(pImage);
7679
7680 pImage = pDisk->pLast;
7681 if (!pImage)
7682 break;
7683
7684 /* If disk was previously in read/write mode, make sure it will stay
7685 * like this (if possible) after closing this image. Set the open flags
7686 * accordingly. */
7687 if (!(uOpenFlags & VD_OPEN_FLAGS_READONLY))
7688 {
7689 uOpenFlags = pImage->Backend->pfnGetOpenFlags(pImage->pBackendData);
7690 uOpenFlags &= ~ VD_OPEN_FLAGS_READONLY;
7691 rc = pImage->Backend->pfnSetOpenFlags(pImage->pBackendData, uOpenFlags);
7692 }
7693
7694 /* Cache disk information. */
7695 pDisk->cbSize = pImage->Backend->pfnGetSize(pImage->pBackendData);
7696
7697 /* Cache PCHS geometry. */
7698 rc2 = pImage->Backend->pfnGetPCHSGeometry(pImage->pBackendData,
7699 &pDisk->PCHSGeometry);
7700 if (RT_FAILURE(rc2))
7701 {
7702 pDisk->PCHSGeometry.cCylinders = 0;
7703 pDisk->PCHSGeometry.cHeads = 0;
7704 pDisk->PCHSGeometry.cSectors = 0;
7705 }
7706 else
7707 {
7708 /* Make sure the PCHS geometry is properly clipped. */
7709 pDisk->PCHSGeometry.cCylinders = RT_MIN(pDisk->PCHSGeometry.cCylinders, 16383);
7710 pDisk->PCHSGeometry.cHeads = RT_MIN(pDisk->PCHSGeometry.cHeads, 16);
7711 pDisk->PCHSGeometry.cSectors = RT_MIN(pDisk->PCHSGeometry.cSectors, 63);
7712 }
7713
7714 /* Cache LCHS geometry. */
7715 rc2 = pImage->Backend->pfnGetLCHSGeometry(pImage->pBackendData,
7716 &pDisk->LCHSGeometry);
7717 if (RT_FAILURE(rc2))
7718 {
7719 pDisk->LCHSGeometry.cCylinders = 0;
7720 pDisk->LCHSGeometry.cHeads = 0;
7721 pDisk->LCHSGeometry.cSectors = 0;
7722 }
7723 else
7724 {
7725 /* Make sure the LCHS geometry is properly clipped. */
7726 pDisk->LCHSGeometry.cHeads = RT_MIN(pDisk->LCHSGeometry.cHeads, 255);
7727 pDisk->LCHSGeometry.cSectors = RT_MIN(pDisk->LCHSGeometry.cSectors, 63);
7728 }
7729 } while (0);
7730
7731 if (RT_UNLIKELY(fLockWrite))
7732 {
7733 rc2 = vdThreadFinishWrite(pDisk);
7734 AssertRC(rc2);
7735 }
7736
7737 LogFlowFunc(("returns %Rrc\n", rc));
7738 return rc;
7739}
7740
7741/**
7742 * Closes the currently opened cache image file in HDD container.
7743 *
7744 * @return VBox status code.
7745 * @return VERR_VD_NOT_OPENED if no cache is opened in HDD container.
7746 * @param pDisk Pointer to HDD container.
7747 * @param fDelete If true, delete the image from the host disk.
7748 */
7749VBOXDDU_DECL(int) VDCacheClose(PVBOXHDD pDisk, bool fDelete)
7750{
7751 int rc = VINF_SUCCESS;
7752 int rc2;
7753 bool fLockWrite = false;
7754 PVDCACHE pCache = NULL;
7755
7756 LogFlowFunc(("pDisk=%#p fDelete=%d\n", pDisk, fDelete));
7757
7758 do
7759 {
7760 /* sanity check */
7761 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
7762 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
7763
7764 rc2 = vdThreadStartWrite(pDisk);
7765 AssertRC(rc2);
7766 fLockWrite = true;
7767
7768 AssertPtrBreakStmt(pDisk->pCache, rc = VERR_VD_CACHE_NOT_FOUND);
7769
7770 pCache = pDisk->pCache;
7771 pDisk->pCache = NULL;
7772
7773 pCache->Backend->pfnClose(pCache->pBackendData, fDelete);
7774 if (pCache->pszFilename)
7775 RTStrFree(pCache->pszFilename);
7776 RTMemFree(pCache);
7777 } while (0);
7778
7779 if (RT_LIKELY(fLockWrite))
7780 {
7781 rc2 = vdThreadFinishWrite(pDisk);
7782 AssertRC(rc2);
7783 }
7784
7785 LogFlowFunc(("returns %Rrc\n", rc));
7786 return rc;
7787}
7788
7789/**
7790 * Closes all opened image files in HDD container.
7791 *
7792 * @returns VBox status code.
7793 * @param pDisk Pointer to HDD container.
7794 */
7795VBOXDDU_DECL(int) VDCloseAll(PVBOXHDD pDisk)
7796{
7797 int rc = VINF_SUCCESS;
7798 int rc2;
7799 bool fLockWrite = false;
7800
7801 LogFlowFunc(("pDisk=%#p\n", pDisk));
7802 do
7803 {
7804 /* sanity check */
7805 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
7806 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
7807
7808 /* Lock the entire operation. */
7809 rc2 = vdThreadStartWrite(pDisk);
7810 AssertRC(rc2);
7811 fLockWrite = true;
7812
7813 PVDCACHE pCache = pDisk->pCache;
7814 if (pCache)
7815 {
7816 rc2 = pCache->Backend->pfnClose(pCache->pBackendData, false);
7817 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
7818 rc = rc2;
7819
7820 if (pCache->pszFilename)
7821 RTStrFree(pCache->pszFilename);
7822 RTMemFree(pCache);
7823 }
7824
7825 PVDIMAGE pImage = pDisk->pLast;
7826 while (VALID_PTR(pImage))
7827 {
7828 PVDIMAGE pPrev = pImage->pPrev;
7829 /* Remove image from list of opened images. */
7830 vdRemoveImageFromList(pDisk, pImage);
7831 /* Close image. */
7832 rc2 = pImage->Backend->pfnClose(pImage->pBackendData, false);
7833 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
7834 rc = rc2;
7835 /* Free remaining resources related to the image. */
7836 RTStrFree(pImage->pszFilename);
7837 RTMemFree(pImage);
7838 pImage = pPrev;
7839 }
7840 Assert(!VALID_PTR(pDisk->pLast));
7841 } while (0);
7842
7843 if (RT_UNLIKELY(fLockWrite))
7844 {
7845 rc2 = vdThreadFinishWrite(pDisk);
7846 AssertRC(rc2);
7847 }
7848
7849 LogFlowFunc(("returns %Rrc\n", rc));
7850 return rc;
7851}
7852
7853/**
7854 * Read data from virtual HDD.
7855 *
7856 * @returns VBox status code.
7857 * @returns VERR_VD_NOT_OPENED if no image is opened in HDD container.
7858 * @param pDisk Pointer to HDD container.
7859 * @param uOffset Offset of first reading byte from start of disk.
7860 * @param pvBuf Pointer to buffer for reading data.
7861 * @param cbRead Number of bytes to read.
7862 */
7863VBOXDDU_DECL(int) VDRead(PVBOXHDD pDisk, uint64_t uOffset, void *pvBuf,
7864 size_t cbRead)
7865{
7866 int rc = VINF_SUCCESS;
7867 int rc2;
7868 bool fLockRead = false;
7869
7870 LogFlowFunc(("pDisk=%#p uOffset=%llu pvBuf=%p cbRead=%zu\n",
7871 pDisk, uOffset, pvBuf, cbRead));
7872 do
7873 {
7874 /* sanity check */
7875 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
7876 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
7877
7878 /* Check arguments. */
7879 AssertMsgBreakStmt(VALID_PTR(pvBuf),
7880 ("pvBuf=%#p\n", pvBuf),
7881 rc = VERR_INVALID_PARAMETER);
7882 AssertMsgBreakStmt(cbRead,
7883 ("cbRead=%zu\n", cbRead),
7884 rc = VERR_INVALID_PARAMETER);
7885
7886 rc2 = vdThreadStartRead(pDisk);
7887 AssertRC(rc2);
7888 fLockRead = true;
7889
7890 AssertMsgBreakStmt(uOffset + cbRead <= pDisk->cbSize,
7891 ("uOffset=%llu cbRead=%zu pDisk->cbSize=%llu\n",
7892 uOffset, cbRead, pDisk->cbSize),
7893 rc = VERR_INVALID_PARAMETER);
7894
7895 PVDIMAGE pImage = pDisk->pLast;
7896 AssertPtrBreakStmt(pImage, rc = VERR_VD_NOT_OPENED);
7897
7898 rc = vdReadHelper(pDisk, pImage, uOffset, pvBuf, cbRead,
7899 true /* fUpdateCache */);
7900 } while (0);
7901
7902 if (RT_UNLIKELY(fLockRead))
7903 {
7904 rc2 = vdThreadFinishRead(pDisk);
7905 AssertRC(rc2);
7906 }
7907
7908 LogFlowFunc(("returns %Rrc\n", rc));
7909 return rc;
7910}
7911
7912/**
7913 * Write data to virtual HDD.
7914 *
7915 * @returns VBox status code.
7916 * @returns VERR_VD_NOT_OPENED if no image is opened in HDD container.
7917 * @param pDisk Pointer to HDD container.
7918 * @param uOffset Offset of the first byte being
7919 * written from start of disk.
7920 * @param pvBuf Pointer to buffer for writing data.
7921 * @param cbWrite Number of bytes to write.
7922 */
7923VBOXDDU_DECL(int) VDWrite(PVBOXHDD pDisk, uint64_t uOffset, const void *pvBuf,
7924 size_t cbWrite)
7925{
7926 int rc = VINF_SUCCESS;
7927 int rc2;
7928 bool fLockWrite = false;
7929
7930 LogFlowFunc(("pDisk=%#p uOffset=%llu pvBuf=%p cbWrite=%zu\n",
7931 pDisk, uOffset, pvBuf, cbWrite));
7932 do
7933 {
7934 /* sanity check */
7935 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
7936 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
7937
7938 /* Check arguments. */
7939 AssertMsgBreakStmt(VALID_PTR(pvBuf),
7940 ("pvBuf=%#p\n", pvBuf),
7941 rc = VERR_INVALID_PARAMETER);
7942 AssertMsgBreakStmt(cbWrite,
7943 ("cbWrite=%zu\n", cbWrite),
7944 rc = VERR_INVALID_PARAMETER);
7945
7946 rc2 = vdThreadStartWrite(pDisk);
7947 AssertRC(rc2);
7948 fLockWrite = true;
7949
7950 AssertMsgBreakStmt(uOffset + cbWrite <= pDisk->cbSize,
7951 ("uOffset=%llu cbWrite=%zu pDisk->cbSize=%llu\n",
7952 uOffset, cbWrite, pDisk->cbSize),
7953 rc = VERR_INVALID_PARAMETER);
7954
7955 PVDIMAGE pImage = pDisk->pLast;
7956 AssertPtrBreakStmt(pImage, rc = VERR_VD_NOT_OPENED);
7957
7958 vdSetModifiedFlag(pDisk);
7959 rc = vdWriteHelper(pDisk, pImage, uOffset, pvBuf, cbWrite,
7960 true /* fUpdateCache */);
7961 if (RT_FAILURE(rc))
7962 break;
7963
7964 /* If there is a merge (in the direction towards a parent) running
7965 * concurrently then we have to also "relay" the write to this parent,
7966 * as the merge position might be already past the position where
7967 * this write is going. The "context" of the write can come from the
7968 * natural chain, since merging either already did or will take care
7969 * of the "other" content which is might be needed to fill the block
7970 * to a full allocation size. The cache doesn't need to be touched
7971 * as this write is covered by the previous one. */
7972 if (RT_UNLIKELY(pDisk->pImageRelay))
7973 rc = vdWriteHelper(pDisk, pDisk->pImageRelay, uOffset,
7974 pvBuf, cbWrite, false /* fUpdateCache */);
7975 } while (0);
7976
7977 if (RT_UNLIKELY(fLockWrite))
7978 {
7979 rc2 = vdThreadFinishWrite(pDisk);
7980 AssertRC(rc2);
7981 }
7982
7983 LogFlowFunc(("returns %Rrc\n", rc));
7984 return rc;
7985}
7986
7987/**
7988 * Make sure the on disk representation of a virtual HDD is up to date.
7989 *
7990 * @returns VBox status code.
7991 * @returns VERR_VD_NOT_OPENED if no image is opened in HDD container.
7992 * @param pDisk Pointer to HDD container.
7993 */
7994VBOXDDU_DECL(int) VDFlush(PVBOXHDD pDisk)
7995{
7996 int rc = VINF_SUCCESS;
7997 int rc2;
7998 bool fLockWrite = false;
7999
8000 LogFlowFunc(("pDisk=%#p\n", pDisk));
8001 do
8002 {
8003 /* sanity check */
8004 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
8005 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
8006
8007 rc2 = vdThreadStartWrite(pDisk);
8008 AssertRC(rc2);
8009 fLockWrite = true;
8010
8011 PVDIMAGE pImage = pDisk->pLast;
8012 AssertPtrBreakStmt(pImage, rc = VERR_VD_NOT_OPENED);
8013
8014 vdResetModifiedFlag(pDisk);
8015 rc = pImage->Backend->pfnFlush(pImage->pBackendData);
8016
8017 if ( RT_SUCCESS(rc)
8018 && pDisk->pCache)
8019 rc = pDisk->pCache->Backend->pfnFlush(pDisk->pCache->pBackendData);
8020 } while (0);
8021
8022 if (RT_UNLIKELY(fLockWrite))
8023 {
8024 rc2 = vdThreadFinishWrite(pDisk);
8025 AssertRC(rc2);
8026 }
8027
8028 LogFlowFunc(("returns %Rrc\n", rc));
8029 return rc;
8030}
8031
8032/**
8033 * Get number of opened images in HDD container.
8034 *
8035 * @returns Number of opened images for HDD container. 0 if no images have been opened.
8036 * @param pDisk Pointer to HDD container.
8037 */
8038VBOXDDU_DECL(unsigned) VDGetCount(PVBOXHDD pDisk)
8039{
8040 unsigned cImages;
8041 int rc2;
8042 bool fLockRead = false;
8043
8044 LogFlowFunc(("pDisk=%#p\n", pDisk));
8045 do
8046 {
8047 /* sanity check */
8048 AssertPtrBreakStmt(pDisk, cImages = 0);
8049 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
8050
8051 rc2 = vdThreadStartRead(pDisk);
8052 AssertRC(rc2);
8053 fLockRead = true;
8054
8055 cImages = pDisk->cImages;
8056 } while (0);
8057
8058 if (RT_UNLIKELY(fLockRead))
8059 {
8060 rc2 = vdThreadFinishRead(pDisk);
8061 AssertRC(rc2);
8062 }
8063
8064 LogFlowFunc(("returns %u\n", cImages));
8065 return cImages;
8066}
8067
8068/**
8069 * Get read/write mode of HDD container.
8070 *
8071 * @returns Virtual disk ReadOnly status.
8072 * @returns true if no image is opened in HDD container.
8073 * @param pDisk Pointer to HDD container.
8074 */
8075VBOXDDU_DECL(bool) VDIsReadOnly(PVBOXHDD pDisk)
8076{
8077 bool fReadOnly;
8078 int rc2;
8079 bool fLockRead = false;
8080
8081 LogFlowFunc(("pDisk=%#p\n", pDisk));
8082 do
8083 {
8084 /* sanity check */
8085 AssertPtrBreakStmt(pDisk, fReadOnly = false);
8086 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
8087
8088 rc2 = vdThreadStartRead(pDisk);
8089 AssertRC(rc2);
8090 fLockRead = true;
8091
8092 PVDIMAGE pImage = pDisk->pLast;
8093 AssertPtrBreakStmt(pImage, fReadOnly = true);
8094
8095 unsigned uOpenFlags;
8096 uOpenFlags = pDisk->pLast->Backend->pfnGetOpenFlags(pDisk->pLast->pBackendData);
8097 fReadOnly = !!(uOpenFlags & VD_OPEN_FLAGS_READONLY);
8098 } while (0);
8099
8100 if (RT_UNLIKELY(fLockRead))
8101 {
8102 rc2 = vdThreadFinishRead(pDisk);
8103 AssertRC(rc2);
8104 }
8105
8106 LogFlowFunc(("returns %d\n", fReadOnly));
8107 return fReadOnly;
8108}
8109
8110/**
8111 * Get total capacity of an image in HDD container.
8112 *
8113 * @returns Virtual disk size in bytes.
8114 * @returns 0 if no image with specified number was not opened.
8115 * @param pDisk Pointer to HDD container.
8116 * @param nImage Image number, counts from 0. 0 is always base image of container.
8117 */
8118VBOXDDU_DECL(uint64_t) VDGetSize(PVBOXHDD pDisk, unsigned nImage)
8119{
8120 uint64_t cbSize;
8121 int rc2;
8122 bool fLockRead = false;
8123
8124 LogFlowFunc(("pDisk=%#p nImage=%u\n", pDisk, nImage));
8125 do
8126 {
8127 /* sanity check */
8128 AssertPtrBreakStmt(pDisk, cbSize = 0);
8129 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
8130
8131 rc2 = vdThreadStartRead(pDisk);
8132 AssertRC(rc2);
8133 fLockRead = true;
8134
8135 PVDIMAGE pImage = vdGetImageByNumber(pDisk, nImage);
8136 AssertPtrBreakStmt(pImage, cbSize = 0);
8137 cbSize = pImage->Backend->pfnGetSize(pImage->pBackendData);
8138 } while (0);
8139
8140 if (RT_UNLIKELY(fLockRead))
8141 {
8142 rc2 = vdThreadFinishRead(pDisk);
8143 AssertRC(rc2);
8144 }
8145
8146 LogFlowFunc(("returns %llu\n", cbSize));
8147 return cbSize;
8148}
8149
8150/**
8151 * Get total file size of an image in HDD container.
8152 *
8153 * @returns Virtual disk size in bytes.
8154 * @returns 0 if no image is opened in HDD container.
8155 * @param pDisk Pointer to HDD container.
8156 * @param nImage Image number, counts from 0. 0 is always base image of container.
8157 */
8158VBOXDDU_DECL(uint64_t) VDGetFileSize(PVBOXHDD pDisk, unsigned nImage)
8159{
8160 uint64_t cbSize;
8161 int rc2;
8162 bool fLockRead = false;
8163
8164 LogFlowFunc(("pDisk=%#p nImage=%u\n", pDisk, nImage));
8165 do
8166 {
8167 /* sanity check */
8168 AssertPtrBreakStmt(pDisk, cbSize = 0);
8169 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
8170
8171 rc2 = vdThreadStartRead(pDisk);
8172 AssertRC(rc2);
8173 fLockRead = true;
8174
8175 PVDIMAGE pImage = vdGetImageByNumber(pDisk, nImage);
8176 AssertPtrBreakStmt(pImage, cbSize = 0);
8177 cbSize = pImage->Backend->pfnGetFileSize(pImage->pBackendData);
8178 } while (0);
8179
8180 if (RT_UNLIKELY(fLockRead))
8181 {
8182 rc2 = vdThreadFinishRead(pDisk);
8183 AssertRC(rc2);
8184 }
8185
8186 LogFlowFunc(("returns %llu\n", cbSize));
8187 return cbSize;
8188}
8189
8190/**
8191 * Get virtual disk PCHS geometry stored in HDD container.
8192 *
8193 * @returns VBox status code.
8194 * @returns VERR_VD_IMAGE_NOT_FOUND if image with specified number was not opened.
8195 * @returns VERR_VD_GEOMETRY_NOT_SET if no geometry present in the HDD container.
8196 * @param pDisk Pointer to HDD container.
8197 * @param nImage Image number, counts from 0. 0 is always base image of container.
8198 * @param pPCHSGeometry Where to store PCHS geometry. Not NULL.
8199 */
8200VBOXDDU_DECL(int) VDGetPCHSGeometry(PVBOXHDD pDisk, unsigned nImage,
8201 PVDGEOMETRY pPCHSGeometry)
8202{
8203 int rc = VINF_SUCCESS;
8204 int rc2;
8205 bool fLockRead = false;
8206
8207 LogFlowFunc(("pDisk=%#p nImage=%u pPCHSGeometry=%#p\n",
8208 pDisk, nImage, pPCHSGeometry));
8209 do
8210 {
8211 /* sanity check */
8212 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
8213 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
8214
8215 /* Check arguments. */
8216 AssertMsgBreakStmt(VALID_PTR(pPCHSGeometry),
8217 ("pPCHSGeometry=%#p\n", pPCHSGeometry),
8218 rc = VERR_INVALID_PARAMETER);
8219
8220 rc2 = vdThreadStartRead(pDisk);
8221 AssertRC(rc2);
8222 fLockRead = true;
8223
8224 PVDIMAGE pImage = vdGetImageByNumber(pDisk, nImage);
8225 AssertPtrBreakStmt(pImage, rc = VERR_VD_IMAGE_NOT_FOUND);
8226
8227 if (pImage == pDisk->pLast)
8228 {
8229 /* Use cached information if possible. */
8230 if (pDisk->PCHSGeometry.cCylinders != 0)
8231 *pPCHSGeometry = pDisk->PCHSGeometry;
8232 else
8233 rc = VERR_VD_GEOMETRY_NOT_SET;
8234 }
8235 else
8236 rc = pImage->Backend->pfnGetPCHSGeometry(pImage->pBackendData,
8237 pPCHSGeometry);
8238 } while (0);
8239
8240 if (RT_UNLIKELY(fLockRead))
8241 {
8242 rc2 = vdThreadFinishRead(pDisk);
8243 AssertRC(rc2);
8244 }
8245
8246 LogFlowFunc(("%Rrc (PCHS=%u/%u/%u)\n", rc,
8247 pDisk->PCHSGeometry.cCylinders, pDisk->PCHSGeometry.cHeads,
8248 pDisk->PCHSGeometry.cSectors));
8249 return rc;
8250}
8251
8252/**
8253 * Store virtual disk PCHS geometry in HDD container.
8254 *
8255 * Note that in case of unrecoverable error all images in HDD container will be closed.
8256 *
8257 * @returns VBox status code.
8258 * @returns VERR_VD_IMAGE_NOT_FOUND if image with specified number was not opened.
8259 * @returns VERR_VD_GEOMETRY_NOT_SET if no geometry present in the HDD container.
8260 * @param pDisk Pointer to HDD container.
8261 * @param nImage Image number, counts from 0. 0 is always base image of container.
8262 * @param pPCHSGeometry Where to load PCHS geometry from. Not NULL.
8263 */
8264VBOXDDU_DECL(int) VDSetPCHSGeometry(PVBOXHDD pDisk, unsigned nImage,
8265 PCVDGEOMETRY pPCHSGeometry)
8266{
8267 int rc = VINF_SUCCESS;
8268 int rc2;
8269 bool fLockWrite = false;
8270
8271 LogFlowFunc(("pDisk=%#p nImage=%u pPCHSGeometry=%#p PCHS=%u/%u/%u\n",
8272 pDisk, nImage, pPCHSGeometry, pPCHSGeometry->cCylinders,
8273 pPCHSGeometry->cHeads, pPCHSGeometry->cSectors));
8274 do
8275 {
8276 /* sanity check */
8277 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
8278 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
8279
8280 /* Check arguments. */
8281 AssertMsgBreakStmt( VALID_PTR(pPCHSGeometry)
8282 && pPCHSGeometry->cHeads <= 16
8283 && pPCHSGeometry->cSectors <= 63,
8284 ("pPCHSGeometry=%#p PCHS=%u/%u/%u\n", pPCHSGeometry,
8285 pPCHSGeometry->cCylinders, pPCHSGeometry->cHeads,
8286 pPCHSGeometry->cSectors),
8287 rc = VERR_INVALID_PARAMETER);
8288
8289 rc2 = vdThreadStartWrite(pDisk);
8290 AssertRC(rc2);
8291 fLockWrite = true;
8292
8293 PVDIMAGE pImage = vdGetImageByNumber(pDisk, nImage);
8294 AssertPtrBreakStmt(pImage, rc = VERR_VD_IMAGE_NOT_FOUND);
8295
8296 if (pImage == pDisk->pLast)
8297 {
8298 if ( pPCHSGeometry->cCylinders != pDisk->PCHSGeometry.cCylinders
8299 || pPCHSGeometry->cHeads != pDisk->PCHSGeometry.cHeads
8300 || pPCHSGeometry->cSectors != pDisk->PCHSGeometry.cSectors)
8301 {
8302 /* Only update geometry if it is changed. Avoids similar checks
8303 * in every backend. Most of the time the new geometry is set
8304 * to the previous values, so no need to go through the hassle
8305 * of updating an image which could be opened in read-only mode
8306 * right now. */
8307 rc = pImage->Backend->pfnSetPCHSGeometry(pImage->pBackendData,
8308 pPCHSGeometry);
8309
8310 /* Cache new geometry values in any case. */
8311 rc2 = pImage->Backend->pfnGetPCHSGeometry(pImage->pBackendData,
8312 &pDisk->PCHSGeometry);
8313 if (RT_FAILURE(rc2))
8314 {
8315 pDisk->PCHSGeometry.cCylinders = 0;
8316 pDisk->PCHSGeometry.cHeads = 0;
8317 pDisk->PCHSGeometry.cSectors = 0;
8318 }
8319 else
8320 {
8321 /* Make sure the CHS geometry is properly clipped. */
8322 pDisk->PCHSGeometry.cHeads = RT_MIN(pDisk->PCHSGeometry.cHeads, 255);
8323 pDisk->PCHSGeometry.cSectors = RT_MIN(pDisk->PCHSGeometry.cSectors, 63);
8324 }
8325 }
8326 }
8327 else
8328 {
8329 VDGEOMETRY PCHS;
8330 rc = pImage->Backend->pfnGetPCHSGeometry(pImage->pBackendData,
8331 &PCHS);
8332 if ( RT_FAILURE(rc)
8333 || pPCHSGeometry->cCylinders != PCHS.cCylinders
8334 || pPCHSGeometry->cHeads != PCHS.cHeads
8335 || pPCHSGeometry->cSectors != PCHS.cSectors)
8336 {
8337 /* Only update geometry if it is changed. Avoids similar checks
8338 * in every backend. Most of the time the new geometry is set
8339 * to the previous values, so no need to go through the hassle
8340 * of updating an image which could be opened in read-only mode
8341 * right now. */
8342 rc = pImage->Backend->pfnSetPCHSGeometry(pImage->pBackendData,
8343 pPCHSGeometry);
8344 }
8345 }
8346 } while (0);
8347
8348 if (RT_UNLIKELY(fLockWrite))
8349 {
8350 rc2 = vdThreadFinishWrite(pDisk);
8351 AssertRC(rc2);
8352 }
8353
8354 LogFlowFunc(("returns %Rrc\n", rc));
8355 return rc;
8356}
8357
8358/**
8359 * Get virtual disk LCHS geometry stored in HDD container.
8360 *
8361 * @returns VBox status code.
8362 * @returns VERR_VD_IMAGE_NOT_FOUND if image with specified number was not opened.
8363 * @returns VERR_VD_GEOMETRY_NOT_SET if no geometry present in the HDD container.
8364 * @param pDisk Pointer to HDD container.
8365 * @param nImage Image number, counts from 0. 0 is always base image of container.
8366 * @param pLCHSGeometry Where to store LCHS geometry. Not NULL.
8367 */
8368VBOXDDU_DECL(int) VDGetLCHSGeometry(PVBOXHDD pDisk, unsigned nImage,
8369 PVDGEOMETRY pLCHSGeometry)
8370{
8371 int rc = VINF_SUCCESS;
8372 int rc2;
8373 bool fLockRead = false;
8374
8375 LogFlowFunc(("pDisk=%#p nImage=%u pLCHSGeometry=%#p\n",
8376 pDisk, nImage, pLCHSGeometry));
8377 do
8378 {
8379 /* sanity check */
8380 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
8381 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
8382
8383 /* Check arguments. */
8384 AssertMsgBreakStmt(VALID_PTR(pLCHSGeometry),
8385 ("pLCHSGeometry=%#p\n", pLCHSGeometry),
8386 rc = VERR_INVALID_PARAMETER);
8387
8388 rc2 = vdThreadStartRead(pDisk);
8389 AssertRC(rc2);
8390 fLockRead = true;
8391
8392 PVDIMAGE pImage = vdGetImageByNumber(pDisk, nImage);
8393 AssertPtrBreakStmt(pImage, rc = VERR_VD_IMAGE_NOT_FOUND);
8394
8395 if (pImage == pDisk->pLast)
8396 {
8397 /* Use cached information if possible. */
8398 if (pDisk->LCHSGeometry.cCylinders != 0)
8399 *pLCHSGeometry = pDisk->LCHSGeometry;
8400 else
8401 rc = VERR_VD_GEOMETRY_NOT_SET;
8402 }
8403 else
8404 rc = pImage->Backend->pfnGetLCHSGeometry(pImage->pBackendData,
8405 pLCHSGeometry);
8406 } while (0);
8407
8408 if (RT_UNLIKELY(fLockRead))
8409 {
8410 rc2 = vdThreadFinishRead(pDisk);
8411 AssertRC(rc2);
8412 }
8413
8414 LogFlowFunc((": %Rrc (LCHS=%u/%u/%u)\n", rc,
8415 pDisk->LCHSGeometry.cCylinders, pDisk->LCHSGeometry.cHeads,
8416 pDisk->LCHSGeometry.cSectors));
8417 return rc;
8418}
8419
8420/**
8421 * Store virtual disk LCHS geometry in HDD container.
8422 *
8423 * Note that in case of unrecoverable error all images in HDD container will be closed.
8424 *
8425 * @returns VBox status code.
8426 * @returns VERR_VD_IMAGE_NOT_FOUND if image with specified number was not opened.
8427 * @returns VERR_VD_GEOMETRY_NOT_SET if no geometry present in the HDD container.
8428 * @param pDisk Pointer to HDD container.
8429 * @param nImage Image number, counts from 0. 0 is always base image of container.
8430 * @param pLCHSGeometry Where to load LCHS geometry from. Not NULL.
8431 */
8432VBOXDDU_DECL(int) VDSetLCHSGeometry(PVBOXHDD pDisk, unsigned nImage,
8433 PCVDGEOMETRY pLCHSGeometry)
8434{
8435 int rc = VINF_SUCCESS;
8436 int rc2;
8437 bool fLockWrite = false;
8438
8439 LogFlowFunc(("pDisk=%#p nImage=%u pLCHSGeometry=%#p LCHS=%u/%u/%u\n",
8440 pDisk, nImage, pLCHSGeometry, pLCHSGeometry->cCylinders,
8441 pLCHSGeometry->cHeads, pLCHSGeometry->cSectors));
8442 do
8443 {
8444 /* sanity check */
8445 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
8446 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
8447
8448 /* Check arguments. */
8449 AssertMsgBreakStmt( VALID_PTR(pLCHSGeometry)
8450 && pLCHSGeometry->cHeads <= 255
8451 && pLCHSGeometry->cSectors <= 63,
8452 ("pLCHSGeometry=%#p LCHS=%u/%u/%u\n", pLCHSGeometry,
8453 pLCHSGeometry->cCylinders, pLCHSGeometry->cHeads,
8454 pLCHSGeometry->cSectors),
8455 rc = VERR_INVALID_PARAMETER);
8456
8457 rc2 = vdThreadStartWrite(pDisk);
8458 AssertRC(rc2);
8459 fLockWrite = true;
8460
8461 PVDIMAGE pImage = vdGetImageByNumber(pDisk, nImage);
8462 AssertPtrBreakStmt(pImage, rc = VERR_VD_IMAGE_NOT_FOUND);
8463
8464 if (pImage == pDisk->pLast)
8465 {
8466 if ( pLCHSGeometry->cCylinders != pDisk->LCHSGeometry.cCylinders
8467 || pLCHSGeometry->cHeads != pDisk->LCHSGeometry.cHeads
8468 || pLCHSGeometry->cSectors != pDisk->LCHSGeometry.cSectors)
8469 {
8470 /* Only update geometry if it is changed. Avoids similar checks
8471 * in every backend. Most of the time the new geometry is set
8472 * to the previous values, so no need to go through the hassle
8473 * of updating an image which could be opened in read-only mode
8474 * right now. */
8475 rc = pImage->Backend->pfnSetLCHSGeometry(pImage->pBackendData,
8476 pLCHSGeometry);
8477
8478 /* Cache new geometry values in any case. */
8479 rc2 = pImage->Backend->pfnGetLCHSGeometry(pImage->pBackendData,
8480 &pDisk->LCHSGeometry);
8481 if (RT_FAILURE(rc2))
8482 {
8483 pDisk->LCHSGeometry.cCylinders = 0;
8484 pDisk->LCHSGeometry.cHeads = 0;
8485 pDisk->LCHSGeometry.cSectors = 0;
8486 }
8487 else
8488 {
8489 /* Make sure the CHS geometry is properly clipped. */
8490 pDisk->LCHSGeometry.cHeads = RT_MIN(pDisk->LCHSGeometry.cHeads, 255);
8491 pDisk->LCHSGeometry.cSectors = RT_MIN(pDisk->LCHSGeometry.cSectors, 63);
8492 }
8493 }
8494 }
8495 else
8496 {
8497 VDGEOMETRY LCHS;
8498 rc = pImage->Backend->pfnGetLCHSGeometry(pImage->pBackendData,
8499 &LCHS);
8500 if ( RT_FAILURE(rc)
8501 || pLCHSGeometry->cCylinders != LCHS.cCylinders
8502 || pLCHSGeometry->cHeads != LCHS.cHeads
8503 || pLCHSGeometry->cSectors != LCHS.cSectors)
8504 {
8505 /* Only update geometry if it is changed. Avoids similar checks
8506 * in every backend. Most of the time the new geometry is set
8507 * to the previous values, so no need to go through the hassle
8508 * of updating an image which could be opened in read-only mode
8509 * right now. */
8510 rc = pImage->Backend->pfnSetLCHSGeometry(pImage->pBackendData,
8511 pLCHSGeometry);
8512 }
8513 }
8514 } while (0);
8515
8516 if (RT_UNLIKELY(fLockWrite))
8517 {
8518 rc2 = vdThreadFinishWrite(pDisk);
8519 AssertRC(rc2);
8520 }
8521
8522 LogFlowFunc(("returns %Rrc\n", rc));
8523 return rc;
8524}
8525
8526/**
8527 * Get version of image in HDD container.
8528 *
8529 * @returns VBox status code.
8530 * @returns VERR_VD_IMAGE_NOT_FOUND if image with specified number was not opened.
8531 * @param pDisk Pointer to HDD container.
8532 * @param nImage Image number, counts from 0. 0 is always base image of container.
8533 * @param puVersion Where to store the image version.
8534 */
8535VBOXDDU_DECL(int) VDGetVersion(PVBOXHDD pDisk, unsigned nImage,
8536 unsigned *puVersion)
8537{
8538 int rc = VINF_SUCCESS;
8539 int rc2;
8540 bool fLockRead = false;
8541
8542 LogFlowFunc(("pDisk=%#p nImage=%u puVersion=%#p\n",
8543 pDisk, nImage, puVersion));
8544 do
8545 {
8546 /* sanity check */
8547 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
8548 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
8549
8550 /* Check arguments. */
8551 AssertMsgBreakStmt(VALID_PTR(puVersion),
8552 ("puVersion=%#p\n", puVersion),
8553 rc = VERR_INVALID_PARAMETER);
8554
8555 rc2 = vdThreadStartRead(pDisk);
8556 AssertRC(rc2);
8557 fLockRead = true;
8558
8559 PVDIMAGE pImage = vdGetImageByNumber(pDisk, nImage);
8560 AssertPtrBreakStmt(pImage, rc = VERR_VD_IMAGE_NOT_FOUND);
8561
8562 *puVersion = pImage->Backend->pfnGetVersion(pImage->pBackendData);
8563 } while (0);
8564
8565 if (RT_UNLIKELY(fLockRead))
8566 {
8567 rc2 = vdThreadFinishRead(pDisk);
8568 AssertRC(rc2);
8569 }
8570
8571 LogFlowFunc(("returns %Rrc uVersion=%#x\n", rc, *puVersion));
8572 return rc;
8573}
8574
8575/**
8576 * List the capabilities of image backend in HDD container.
8577 *
8578 * @returns VBox status code.
8579 * @returns VERR_VD_IMAGE_NOT_FOUND if image with specified number was not opened.
8580 * @param pDisk Pointer to the HDD container.
8581 * @param nImage Image number, counts from 0. 0 is always base image of container.
8582 * @param pbackendInfo Where to store the backend information.
8583 */
8584VBOXDDU_DECL(int) VDBackendInfoSingle(PVBOXHDD pDisk, unsigned nImage,
8585 PVDBACKENDINFO pBackendInfo)
8586{
8587 int rc = VINF_SUCCESS;
8588 int rc2;
8589 bool fLockRead = false;
8590
8591 LogFlowFunc(("pDisk=%#p nImage=%u pBackendInfo=%#p\n",
8592 pDisk, nImage, pBackendInfo));
8593 do
8594 {
8595 /* sanity check */
8596 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
8597 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
8598
8599 /* Check arguments. */
8600 AssertMsgBreakStmt(VALID_PTR(pBackendInfo),
8601 ("pBackendInfo=%#p\n", pBackendInfo),
8602 rc = VERR_INVALID_PARAMETER);
8603
8604 rc2 = vdThreadStartRead(pDisk);
8605 AssertRC(rc2);
8606 fLockRead = true;
8607
8608 PVDIMAGE pImage = vdGetImageByNumber(pDisk, nImage);
8609 AssertPtrBreakStmt(pImage, rc = VERR_VD_IMAGE_NOT_FOUND);
8610
8611 pBackendInfo->pszBackend = pImage->Backend->pszBackendName;
8612 pBackendInfo->uBackendCaps = pImage->Backend->uBackendCaps;
8613 pBackendInfo->paFileExtensions = pImage->Backend->paFileExtensions;
8614 pBackendInfo->paConfigInfo = pImage->Backend->paConfigInfo;
8615 } while (0);
8616
8617 if (RT_UNLIKELY(fLockRead))
8618 {
8619 rc2 = vdThreadFinishRead(pDisk);
8620 AssertRC(rc2);
8621 }
8622
8623 LogFlowFunc(("returns %Rrc\n", rc));
8624 return rc;
8625}
8626
8627/**
8628 * Get flags of image in HDD container.
8629 *
8630 * @returns VBox status code.
8631 * @returns VERR_VD_IMAGE_NOT_FOUND if image with specified number was not opened.
8632 * @param pDisk Pointer to HDD container.
8633 * @param nImage Image number, counts from 0. 0 is always base image of container.
8634 * @param puImageFlags Where to store the image flags.
8635 */
8636VBOXDDU_DECL(int) VDGetImageFlags(PVBOXHDD pDisk, unsigned nImage,
8637 unsigned *puImageFlags)
8638{
8639 int rc = VINF_SUCCESS;
8640 int rc2;
8641 bool fLockRead = false;
8642
8643 LogFlowFunc(("pDisk=%#p nImage=%u puImageFlags=%#p\n",
8644 pDisk, nImage, puImageFlags));
8645 do
8646 {
8647 /* sanity check */
8648 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
8649 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
8650
8651 /* Check arguments. */
8652 AssertMsgBreakStmt(VALID_PTR(puImageFlags),
8653 ("puImageFlags=%#p\n", puImageFlags),
8654 rc = VERR_INVALID_PARAMETER);
8655
8656 rc2 = vdThreadStartRead(pDisk);
8657 AssertRC(rc2);
8658 fLockRead = true;
8659
8660 PVDIMAGE pImage = vdGetImageByNumber(pDisk, nImage);
8661 AssertPtrBreakStmt(pImage, rc = VERR_VD_IMAGE_NOT_FOUND);
8662
8663 *puImageFlags = pImage->uImageFlags;
8664 } while (0);
8665
8666 if (RT_UNLIKELY(fLockRead))
8667 {
8668 rc2 = vdThreadFinishRead(pDisk);
8669 AssertRC(rc2);
8670 }
8671
8672 LogFlowFunc(("returns %Rrc uImageFlags=%#x\n", rc, *puImageFlags));
8673 return rc;
8674}
8675
8676/**
8677 * Get open flags of image in HDD container.
8678 *
8679 * @returns VBox status code.
8680 * @returns VERR_VD_IMAGE_NOT_FOUND if image with specified number was not opened.
8681 * @param pDisk Pointer to HDD container.
8682 * @param nImage Image number, counts from 0. 0 is always base image of container.
8683 * @param puOpenFlags Where to store the image open flags.
8684 */
8685VBOXDDU_DECL(int) VDGetOpenFlags(PVBOXHDD pDisk, unsigned nImage,
8686 unsigned *puOpenFlags)
8687{
8688 int rc = VINF_SUCCESS;
8689 int rc2;
8690 bool fLockRead = false;
8691
8692 LogFlowFunc(("pDisk=%#p nImage=%u puOpenFlags=%#p\n",
8693 pDisk, nImage, puOpenFlags));
8694 do
8695 {
8696 /* sanity check */
8697 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
8698 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
8699
8700 /* Check arguments. */
8701 AssertMsgBreakStmt(VALID_PTR(puOpenFlags),
8702 ("puOpenFlags=%#p\n", puOpenFlags),
8703 rc = VERR_INVALID_PARAMETER);
8704
8705 rc2 = vdThreadStartRead(pDisk);
8706 AssertRC(rc2);
8707 fLockRead = true;
8708
8709 PVDIMAGE pImage = vdGetImageByNumber(pDisk, nImage);
8710 AssertPtrBreakStmt(pImage, rc = VERR_VD_IMAGE_NOT_FOUND);
8711
8712 *puOpenFlags = pImage->Backend->pfnGetOpenFlags(pImage->pBackendData);
8713 } while (0);
8714
8715 if (RT_UNLIKELY(fLockRead))
8716 {
8717 rc2 = vdThreadFinishRead(pDisk);
8718 AssertRC(rc2);
8719 }
8720
8721 LogFlowFunc(("returns %Rrc uOpenFlags=%#x\n", rc, *puOpenFlags));
8722 return rc;
8723}
8724
8725/**
8726 * Set open flags of image in HDD container.
8727 * This operation may cause file locking changes and/or files being reopened.
8728 * Note that in case of unrecoverable error all images in HDD container will be closed.
8729 *
8730 * @returns VBox status code.
8731 * @returns VERR_VD_IMAGE_NOT_FOUND if image with specified number was not opened.
8732 * @param pDisk Pointer to HDD container.
8733 * @param nImage Image number, counts from 0. 0 is always base image of container.
8734 * @param uOpenFlags Image file open mode, see VD_OPEN_FLAGS_* constants.
8735 */
8736VBOXDDU_DECL(int) VDSetOpenFlags(PVBOXHDD pDisk, unsigned nImage,
8737 unsigned uOpenFlags)
8738{
8739 int rc;
8740 int rc2;
8741 bool fLockWrite = false;
8742
8743 LogFlowFunc(("pDisk=%#p uOpenFlags=%#u\n", pDisk, uOpenFlags));
8744 do
8745 {
8746 /* sanity check */
8747 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
8748 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
8749
8750 /* Check arguments. */
8751 AssertMsgBreakStmt((uOpenFlags & ~VD_OPEN_FLAGS_MASK) == 0,
8752 ("uOpenFlags=%#x\n", uOpenFlags),
8753 rc = VERR_INVALID_PARAMETER);
8754
8755 rc2 = vdThreadStartWrite(pDisk);
8756 AssertRC(rc2);
8757 fLockWrite = true;
8758
8759 /* Destroy any discard state because the image might be changed to readonly mode. */
8760 rc = vdDiscardStateDestroy(pDisk);
8761 if (RT_FAILURE(rc))
8762 break;
8763
8764 PVDIMAGE pImage = vdGetImageByNumber(pDisk, nImage);
8765 AssertPtrBreakStmt(pImage, rc = VERR_VD_IMAGE_NOT_FOUND);
8766
8767 rc = pImage->Backend->pfnSetOpenFlags(pImage->pBackendData,
8768 uOpenFlags & ~(VD_OPEN_FLAGS_HONOR_SAME | VD_OPEN_FLAGS_IGNORE_FLUSH | VD_OPEN_FLAGS_INFORM_ABOUT_ZERO_BLOCKS));
8769 if (RT_SUCCESS(rc))
8770 pImage->uOpenFlags = uOpenFlags & (VD_OPEN_FLAGS_HONOR_SAME | VD_OPEN_FLAGS_DISCARD | VD_OPEN_FLAGS_IGNORE_FLUSH | VD_OPEN_FLAGS_INFORM_ABOUT_ZERO_BLOCKS);
8771 } while (0);
8772
8773 if (RT_UNLIKELY(fLockWrite))
8774 {
8775 rc2 = vdThreadFinishWrite(pDisk);
8776 AssertRC(rc2);
8777 }
8778
8779 LogFlowFunc(("returns %Rrc\n", rc));
8780 return rc;
8781}
8782
8783/**
8784 * Get base filename of image in HDD container. Some image formats use
8785 * other filenames as well, so don't use this for anything but informational
8786 * purposes.
8787 *
8788 * @returns VBox status code.
8789 * @returns VERR_VD_IMAGE_NOT_FOUND if image with specified number was not opened.
8790 * @returns VERR_BUFFER_OVERFLOW if pszFilename buffer too small to hold filename.
8791 * @param pDisk Pointer to HDD container.
8792 * @param nImage Image number, counts from 0. 0 is always base image of container.
8793 * @param pszFilename Where to store the image file name.
8794 * @param cbFilename Size of buffer pszFilename points to.
8795 */
8796VBOXDDU_DECL(int) VDGetFilename(PVBOXHDD pDisk, unsigned nImage,
8797 char *pszFilename, unsigned cbFilename)
8798{
8799 int rc;
8800 int rc2;
8801 bool fLockRead = false;
8802
8803 LogFlowFunc(("pDisk=%#p nImage=%u pszFilename=%#p cbFilename=%u\n",
8804 pDisk, nImage, pszFilename, cbFilename));
8805 do
8806 {
8807 /* sanity check */
8808 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
8809 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
8810
8811 /* Check arguments. */
8812 AssertMsgBreakStmt(VALID_PTR(pszFilename) && *pszFilename,
8813 ("pszFilename=%#p \"%s\"\n", pszFilename, pszFilename),
8814 rc = VERR_INVALID_PARAMETER);
8815 AssertMsgBreakStmt(cbFilename,
8816 ("cbFilename=%u\n", cbFilename),
8817 rc = VERR_INVALID_PARAMETER);
8818
8819 rc2 = vdThreadStartRead(pDisk);
8820 AssertRC(rc2);
8821 fLockRead = true;
8822
8823 PVDIMAGE pImage = vdGetImageByNumber(pDisk, nImage);
8824 AssertPtrBreakStmt(pImage, rc = VERR_VD_IMAGE_NOT_FOUND);
8825
8826 size_t cb = strlen(pImage->pszFilename);
8827 if (cb <= cbFilename)
8828 {
8829 strcpy(pszFilename, pImage->pszFilename);
8830 rc = VINF_SUCCESS;
8831 }
8832 else
8833 {
8834 strncpy(pszFilename, pImage->pszFilename, cbFilename - 1);
8835 pszFilename[cbFilename - 1] = '\0';
8836 rc = VERR_BUFFER_OVERFLOW;
8837 }
8838 } while (0);
8839
8840 if (RT_UNLIKELY(fLockRead))
8841 {
8842 rc2 = vdThreadFinishRead(pDisk);
8843 AssertRC(rc2);
8844 }
8845
8846 LogFlowFunc(("returns %Rrc, pszFilename=\"%s\"\n", rc, pszFilename));
8847 return rc;
8848}
8849
8850/**
8851 * Get the comment line of image in HDD container.
8852 *
8853 * @returns VBox status code.
8854 * @returns VERR_VD_IMAGE_NOT_FOUND if image with specified number was not opened.
8855 * @returns VERR_BUFFER_OVERFLOW if pszComment buffer too small to hold comment text.
8856 * @param pDisk Pointer to HDD container.
8857 * @param nImage Image number, counts from 0. 0 is always base image of container.
8858 * @param pszComment Where to store the comment string of image. NULL is ok.
8859 * @param cbComment The size of pszComment buffer. 0 is ok.
8860 */
8861VBOXDDU_DECL(int) VDGetComment(PVBOXHDD pDisk, unsigned nImage,
8862 char *pszComment, unsigned cbComment)
8863{
8864 int rc;
8865 int rc2;
8866 bool fLockRead = false;
8867
8868 LogFlowFunc(("pDisk=%#p nImage=%u pszComment=%#p cbComment=%u\n",
8869 pDisk, nImage, pszComment, cbComment));
8870 do
8871 {
8872 /* sanity check */
8873 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
8874 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
8875
8876 /* Check arguments. */
8877 AssertMsgBreakStmt(VALID_PTR(pszComment),
8878 ("pszComment=%#p \"%s\"\n", pszComment, pszComment),
8879 rc = VERR_INVALID_PARAMETER);
8880 AssertMsgBreakStmt(cbComment,
8881 ("cbComment=%u\n", cbComment),
8882 rc = VERR_INVALID_PARAMETER);
8883
8884 rc2 = vdThreadStartRead(pDisk);
8885 AssertRC(rc2);
8886 fLockRead = true;
8887
8888 PVDIMAGE pImage = vdGetImageByNumber(pDisk, nImage);
8889 AssertPtrBreakStmt(pImage, rc = VERR_VD_IMAGE_NOT_FOUND);
8890
8891 rc = pImage->Backend->pfnGetComment(pImage->pBackendData, pszComment,
8892 cbComment);
8893 } while (0);
8894
8895 if (RT_UNLIKELY(fLockRead))
8896 {
8897 rc2 = vdThreadFinishRead(pDisk);
8898 AssertRC(rc2);
8899 }
8900
8901 LogFlowFunc(("returns %Rrc, pszComment=\"%s\"\n", rc, pszComment));
8902 return rc;
8903}
8904
8905/**
8906 * Changes the comment line of image in HDD container.
8907 *
8908 * @returns VBox status code.
8909 * @returns VERR_VD_IMAGE_NOT_FOUND if image with specified number was not opened.
8910 * @param pDisk Pointer to HDD container.
8911 * @param nImage Image number, counts from 0. 0 is always base image of container.
8912 * @param pszComment New comment string (UTF-8). NULL is allowed to reset the comment.
8913 */
8914VBOXDDU_DECL(int) VDSetComment(PVBOXHDD pDisk, unsigned nImage,
8915 const char *pszComment)
8916{
8917 int rc;
8918 int rc2;
8919 bool fLockWrite = false;
8920
8921 LogFlowFunc(("pDisk=%#p nImage=%u pszComment=%#p \"%s\"\n",
8922 pDisk, nImage, pszComment, pszComment));
8923 do
8924 {
8925 /* sanity check */
8926 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
8927 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
8928
8929 /* Check arguments. */
8930 AssertMsgBreakStmt(VALID_PTR(pszComment) || pszComment == NULL,
8931 ("pszComment=%#p \"%s\"\n", pszComment, pszComment),
8932 rc = VERR_INVALID_PARAMETER);
8933
8934 rc2 = vdThreadStartWrite(pDisk);
8935 AssertRC(rc2);
8936 fLockWrite = true;
8937
8938 PVDIMAGE pImage = vdGetImageByNumber(pDisk, nImage);
8939 AssertPtrBreakStmt(pImage, rc = VERR_VD_IMAGE_NOT_FOUND);
8940
8941 rc = pImage->Backend->pfnSetComment(pImage->pBackendData, pszComment);
8942 } while (0);
8943
8944 if (RT_UNLIKELY(fLockWrite))
8945 {
8946 rc2 = vdThreadFinishWrite(pDisk);
8947 AssertRC(rc2);
8948 }
8949
8950 LogFlowFunc(("returns %Rrc\n", rc));
8951 return rc;
8952}
8953
8954
8955/**
8956 * Get UUID of image in HDD container.
8957 *
8958 * @returns VBox status code.
8959 * @returns VERR_VD_IMAGE_NOT_FOUND if image with specified number was not opened.
8960 * @param pDisk Pointer to HDD container.
8961 * @param nImage Image number, counts from 0. 0 is always base image of container.
8962 * @param pUuid Where to store the image creation UUID.
8963 */
8964VBOXDDU_DECL(int) VDGetUuid(PVBOXHDD pDisk, unsigned nImage, PRTUUID pUuid)
8965{
8966 int rc;
8967 int rc2;
8968 bool fLockRead = false;
8969
8970 LogFlowFunc(("pDisk=%#p nImage=%u pUuid=%#p\n", pDisk, nImage, pUuid));
8971 do
8972 {
8973 /* sanity check */
8974 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
8975 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
8976
8977 /* Check arguments. */
8978 AssertMsgBreakStmt(VALID_PTR(pUuid),
8979 ("pUuid=%#p\n", pUuid),
8980 rc = VERR_INVALID_PARAMETER);
8981
8982 rc2 = vdThreadStartRead(pDisk);
8983 AssertRC(rc2);
8984 fLockRead = true;
8985
8986 PVDIMAGE pImage = vdGetImageByNumber(pDisk, nImage);
8987 AssertPtrBreakStmt(pImage, rc = VERR_VD_IMAGE_NOT_FOUND);
8988
8989 rc = pImage->Backend->pfnGetUuid(pImage->pBackendData, pUuid);
8990 } while (0);
8991
8992 if (RT_UNLIKELY(fLockRead))
8993 {
8994 rc2 = vdThreadFinishRead(pDisk);
8995 AssertRC(rc2);
8996 }
8997
8998 LogFlowFunc(("returns %Rrc, Uuid={%RTuuid}\n", rc, pUuid));
8999 return rc;
9000}
9001
9002/**
9003 * Set the image's UUID. Should not be used by normal applications.
9004 *
9005 * @returns VBox status code.
9006 * @returns VERR_VD_IMAGE_NOT_FOUND if image with specified number was not opened.
9007 * @param pDisk Pointer to HDD container.
9008 * @param nImage Image number, counts from 0. 0 is always base image of container.
9009 * @param pUuid New UUID of the image. If NULL, a new UUID is created.
9010 */
9011VBOXDDU_DECL(int) VDSetUuid(PVBOXHDD pDisk, unsigned nImage, PCRTUUID pUuid)
9012{
9013 int rc;
9014 int rc2;
9015 bool fLockWrite = false;
9016
9017 LogFlowFunc(("pDisk=%#p nImage=%u pUuid=%#p {%RTuuid}\n",
9018 pDisk, nImage, pUuid, pUuid));
9019 do
9020 {
9021 /* sanity check */
9022 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
9023 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
9024
9025 AssertMsgBreakStmt(VALID_PTR(pUuid) || pUuid == NULL,
9026 ("pUuid=%#p\n", pUuid),
9027 rc = VERR_INVALID_PARAMETER);
9028
9029 rc2 = vdThreadStartWrite(pDisk);
9030 AssertRC(rc2);
9031 fLockWrite = true;
9032
9033 PVDIMAGE pImage = vdGetImageByNumber(pDisk, nImage);
9034 AssertPtrBreakStmt(pImage, rc = VERR_VD_IMAGE_NOT_FOUND);
9035
9036 RTUUID Uuid;
9037 if (!pUuid)
9038 {
9039 RTUuidCreate(&Uuid);
9040 pUuid = &Uuid;
9041 }
9042 rc = pImage->Backend->pfnSetUuid(pImage->pBackendData, pUuid);
9043 } while (0);
9044
9045 if (RT_UNLIKELY(fLockWrite))
9046 {
9047 rc2 = vdThreadFinishWrite(pDisk);
9048 AssertRC(rc2);
9049 }
9050
9051 LogFlowFunc(("returns %Rrc\n", rc));
9052 return rc;
9053}
9054
9055/**
9056 * Get last modification UUID of image in HDD container.
9057 *
9058 * @returns VBox status code.
9059 * @returns VERR_VD_IMAGE_NOT_FOUND if image with specified number was not opened.
9060 * @param pDisk Pointer to HDD container.
9061 * @param nImage Image number, counts from 0. 0 is always base image of container.
9062 * @param pUuid Where to store the image modification UUID.
9063 */
9064VBOXDDU_DECL(int) VDGetModificationUuid(PVBOXHDD pDisk, unsigned nImage, PRTUUID pUuid)
9065{
9066 int rc = VINF_SUCCESS;
9067 int rc2;
9068 bool fLockRead = false;
9069
9070 LogFlowFunc(("pDisk=%#p nImage=%u pUuid=%#p\n", pDisk, nImage, pUuid));
9071 do
9072 {
9073 /* sanity check */
9074 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
9075 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
9076
9077 /* Check arguments. */
9078 AssertMsgBreakStmt(VALID_PTR(pUuid),
9079 ("pUuid=%#p\n", pUuid),
9080 rc = VERR_INVALID_PARAMETER);
9081
9082 rc2 = vdThreadStartRead(pDisk);
9083 AssertRC(rc2);
9084 fLockRead = true;
9085
9086 PVDIMAGE pImage = vdGetImageByNumber(pDisk, nImage);
9087 AssertPtrBreakStmt(pImage, rc = VERR_VD_IMAGE_NOT_FOUND);
9088
9089 rc = pImage->Backend->pfnGetModificationUuid(pImage->pBackendData,
9090 pUuid);
9091 } while (0);
9092
9093 if (RT_UNLIKELY(fLockRead))
9094 {
9095 rc2 = vdThreadFinishRead(pDisk);
9096 AssertRC(rc2);
9097 }
9098
9099 LogFlowFunc(("returns %Rrc, Uuid={%RTuuid}\n", rc, pUuid));
9100 return rc;
9101}
9102
9103/**
9104 * Set the image's last modification UUID. Should not be used by normal applications.
9105 *
9106 * @returns VBox status code.
9107 * @returns VERR_VD_IMAGE_NOT_FOUND if image with specified number was not opened.
9108 * @param pDisk Pointer to HDD container.
9109 * @param nImage Image number, counts from 0. 0 is always base image of container.
9110 * @param pUuid New modification UUID of the image. If NULL, a new UUID is created.
9111 */
9112VBOXDDU_DECL(int) VDSetModificationUuid(PVBOXHDD pDisk, unsigned nImage, PCRTUUID pUuid)
9113{
9114 int rc;
9115 int rc2;
9116 bool fLockWrite = false;
9117
9118 LogFlowFunc(("pDisk=%#p nImage=%u pUuid=%#p {%RTuuid}\n",
9119 pDisk, nImage, pUuid, pUuid));
9120 do
9121 {
9122 /* sanity check */
9123 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
9124 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
9125
9126 /* Check arguments. */
9127 AssertMsgBreakStmt(VALID_PTR(pUuid) || pUuid == NULL,
9128 ("pUuid=%#p\n", pUuid),
9129 rc = VERR_INVALID_PARAMETER);
9130
9131 rc2 = vdThreadStartWrite(pDisk);
9132 AssertRC(rc2);
9133 fLockWrite = true;
9134
9135 PVDIMAGE pImage = vdGetImageByNumber(pDisk, nImage);
9136 AssertPtrBreakStmt(pImage, rc = VERR_VD_IMAGE_NOT_FOUND);
9137
9138 RTUUID Uuid;
9139 if (!pUuid)
9140 {
9141 RTUuidCreate(&Uuid);
9142 pUuid = &Uuid;
9143 }
9144 rc = pImage->Backend->pfnSetModificationUuid(pImage->pBackendData,
9145 pUuid);
9146 } while (0);
9147
9148 if (RT_UNLIKELY(fLockWrite))
9149 {
9150 rc2 = vdThreadFinishWrite(pDisk);
9151 AssertRC(rc2);
9152 }
9153
9154 LogFlowFunc(("returns %Rrc\n", rc));
9155 return rc;
9156}
9157
9158/**
9159 * Get parent UUID of image in HDD container.
9160 *
9161 * @returns VBox status code.
9162 * @returns VERR_VD_IMAGE_NOT_FOUND if image with specified number was not opened.
9163 * @param pDisk Pointer to HDD container.
9164 * @param nImage Image number, counts from 0. 0 is always base image of container.
9165 * @param pUuid Where to store the parent image UUID.
9166 */
9167VBOXDDU_DECL(int) VDGetParentUuid(PVBOXHDD pDisk, unsigned nImage,
9168 PRTUUID pUuid)
9169{
9170 int rc = VINF_SUCCESS;
9171 int rc2;
9172 bool fLockRead = false;
9173
9174 LogFlowFunc(("pDisk=%#p nImage=%u pUuid=%#p\n", pDisk, nImage, pUuid));
9175 do
9176 {
9177 /* sanity check */
9178 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
9179 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
9180
9181 /* Check arguments. */
9182 AssertMsgBreakStmt(VALID_PTR(pUuid),
9183 ("pUuid=%#p\n", pUuid),
9184 rc = VERR_INVALID_PARAMETER);
9185
9186 rc2 = vdThreadStartRead(pDisk);
9187 AssertRC(rc2);
9188 fLockRead = true;
9189
9190 PVDIMAGE pImage = vdGetImageByNumber(pDisk, nImage);
9191 AssertPtrBreakStmt(pImage, rc = VERR_VD_IMAGE_NOT_FOUND);
9192
9193 rc = pImage->Backend->pfnGetParentUuid(pImage->pBackendData, pUuid);
9194 } while (0);
9195
9196 if (RT_UNLIKELY(fLockRead))
9197 {
9198 rc2 = vdThreadFinishRead(pDisk);
9199 AssertRC(rc2);
9200 }
9201
9202 LogFlowFunc(("returns %Rrc, Uuid={%RTuuid}\n", rc, pUuid));
9203 return rc;
9204}
9205
9206/**
9207 * Set the image's parent UUID. Should not be used by normal applications.
9208 *
9209 * @returns VBox status code.
9210 * @param pDisk Pointer to HDD container.
9211 * @param nImage Image number, counts from 0. 0 is always base image of container.
9212 * @param pUuid New parent UUID of the image. If NULL, a new UUID is created.
9213 */
9214VBOXDDU_DECL(int) VDSetParentUuid(PVBOXHDD pDisk, unsigned nImage,
9215 PCRTUUID pUuid)
9216{
9217 int rc;
9218 int rc2;
9219 bool fLockWrite = false;
9220
9221 LogFlowFunc(("pDisk=%#p nImage=%u pUuid=%#p {%RTuuid}\n",
9222 pDisk, nImage, pUuid, pUuid));
9223 do
9224 {
9225 /* sanity check */
9226 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
9227 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
9228
9229 /* Check arguments. */
9230 AssertMsgBreakStmt(VALID_PTR(pUuid) || pUuid == NULL,
9231 ("pUuid=%#p\n", pUuid),
9232 rc = VERR_INVALID_PARAMETER);
9233
9234 rc2 = vdThreadStartWrite(pDisk);
9235 AssertRC(rc2);
9236 fLockWrite = true;
9237
9238 PVDIMAGE pImage = vdGetImageByNumber(pDisk, nImage);
9239 AssertPtrBreakStmt(pImage, rc = VERR_VD_IMAGE_NOT_FOUND);
9240
9241 RTUUID Uuid;
9242 if (!pUuid)
9243 {
9244 RTUuidCreate(&Uuid);
9245 pUuid = &Uuid;
9246 }
9247 rc = pImage->Backend->pfnSetParentUuid(pImage->pBackendData, pUuid);
9248 } while (0);
9249
9250 if (RT_UNLIKELY(fLockWrite))
9251 {
9252 rc2 = vdThreadFinishWrite(pDisk);
9253 AssertRC(rc2);
9254 }
9255
9256 LogFlowFunc(("returns %Rrc\n", rc));
9257 return rc;
9258}
9259
9260
9261/**
9262 * Debug helper - dumps all opened images in HDD container into the log file.
9263 *
9264 * @param pDisk Pointer to HDD container.
9265 */
9266VBOXDDU_DECL(void) VDDumpImages(PVBOXHDD pDisk)
9267{
9268 int rc2;
9269 bool fLockRead = false;
9270
9271 do
9272 {
9273 /* sanity check */
9274 AssertPtrBreak(pDisk);
9275 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
9276
9277 if (!pDisk->pInterfaceError || !VALID_PTR(pDisk->pInterfaceError->pfnMessage))
9278 pDisk->pInterfaceError->pfnMessage = vdLogMessage;
9279
9280 rc2 = vdThreadStartRead(pDisk);
9281 AssertRC(rc2);
9282 fLockRead = true;
9283
9284 vdMessageWrapper(pDisk, "--- Dumping VD Disk, Images=%u\n", pDisk->cImages);
9285 for (PVDIMAGE pImage = pDisk->pBase; pImage; pImage = pImage->pNext)
9286 {
9287 vdMessageWrapper(pDisk, "Dumping VD image \"%s\" (Backend=%s)\n",
9288 pImage->pszFilename, pImage->Backend->pszBackendName);
9289 pImage->Backend->pfnDump(pImage->pBackendData);
9290 }
9291 } while (0);
9292
9293 if (RT_UNLIKELY(fLockRead))
9294 {
9295 rc2 = vdThreadFinishRead(pDisk);
9296 AssertRC(rc2);
9297 }
9298}
9299
9300
9301VBOXDDU_DECL(int) VDDiscardRanges(PVBOXHDD pDisk, PCRTRANGE paRanges, unsigned cRanges)
9302{
9303 int rc;
9304 int rc2;
9305 bool fLockWrite = false;
9306
9307 LogFlowFunc(("pDisk=%#p paRanges=%#p cRanges=%u\n",
9308 pDisk, paRanges, cRanges));
9309 do
9310 {
9311 /* sanity check */
9312 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
9313 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
9314
9315 /* Check arguments. */
9316 AssertMsgBreakStmt(cRanges,
9317 ("cRanges=%u\n", cRanges),
9318 rc = VERR_INVALID_PARAMETER);
9319 AssertMsgBreakStmt(VALID_PTR(paRanges),
9320 ("paRanges=%#p\n", paRanges),
9321 rc = VERR_INVALID_PARAMETER);
9322
9323 rc2 = vdThreadStartWrite(pDisk);
9324 AssertRC(rc2);
9325 fLockWrite = true;
9326
9327 AssertPtrBreakStmt(pDisk->pLast, rc = VERR_VD_NOT_OPENED);
9328
9329 AssertMsgBreakStmt(pDisk->pLast->uOpenFlags & VD_OPEN_FLAGS_DISCARD,
9330 ("Discarding not supported\n"),
9331 rc = VERR_NOT_SUPPORTED);
9332
9333 vdSetModifiedFlag(pDisk);
9334 rc = vdDiscardHelper(pDisk, paRanges, cRanges);
9335 } while (0);
9336
9337 if (RT_UNLIKELY(fLockWrite))
9338 {
9339 rc2 = vdThreadFinishWrite(pDisk);
9340 AssertRC(rc2);
9341 }
9342
9343 LogFlowFunc(("returns %Rrc\n", rc));
9344 return rc;
9345}
9346
9347
9348VBOXDDU_DECL(int) VDAsyncRead(PVBOXHDD pDisk, uint64_t uOffset, size_t cbRead,
9349 PCRTSGBUF pcSgBuf,
9350 PFNVDASYNCTRANSFERCOMPLETE pfnComplete,
9351 void *pvUser1, void *pvUser2)
9352{
9353 int rc = VERR_VD_BLOCK_FREE;
9354 int rc2;
9355 bool fLockRead = false;
9356 PVDIOCTX pIoCtx = NULL;
9357
9358 LogFlowFunc(("pDisk=%#p uOffset=%llu pcSgBuf=%#p cbRead=%zu pvUser1=%#p pvUser2=%#p\n",
9359 pDisk, uOffset, pcSgBuf, cbRead, pvUser1, pvUser2));
9360
9361 do
9362 {
9363 /* sanity check */
9364 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
9365 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
9366
9367 /* Check arguments. */
9368 AssertMsgBreakStmt(cbRead,
9369 ("cbRead=%zu\n", cbRead),
9370 rc = VERR_INVALID_PARAMETER);
9371 AssertMsgBreakStmt(VALID_PTR(pcSgBuf),
9372 ("pcSgBuf=%#p\n", pcSgBuf),
9373 rc = VERR_INVALID_PARAMETER);
9374
9375 rc2 = vdThreadStartRead(pDisk);
9376 AssertRC(rc2);
9377 fLockRead = true;
9378
9379 AssertMsgBreakStmt(uOffset + cbRead <= pDisk->cbSize,
9380 ("uOffset=%llu cbRead=%zu pDisk->cbSize=%llu\n",
9381 uOffset, cbRead, pDisk->cbSize),
9382 rc = VERR_INVALID_PARAMETER);
9383 AssertPtrBreakStmt(pDisk->pLast, rc = VERR_VD_NOT_OPENED);
9384
9385 pIoCtx = vdIoCtxRootAlloc(pDisk, VDIOCTXTXDIR_READ, uOffset,
9386 cbRead, pDisk->pLast, pcSgBuf,
9387 pfnComplete, pvUser1, pvUser2,
9388 NULL, vdReadHelperAsync);
9389 if (!pIoCtx)
9390 {
9391 rc = VERR_NO_MEMORY;
9392 break;
9393 }
9394
9395#if 0
9396 rc = vdIoCtxProcessTryLockDefer(pIoCtx);
9397#else
9398 rc = vdIoCtxProcess(pIoCtx);
9399#endif
9400 if (rc == VINF_VD_ASYNC_IO_FINISHED)
9401 {
9402 if (ASMAtomicCmpXchgBool(&pIoCtx->fComplete, true, false))
9403 vdIoCtxFree(pDisk, pIoCtx);
9404 else
9405 rc = VERR_VD_ASYNC_IO_IN_PROGRESS; /* Let the other handler complete the request. */
9406 }
9407 else if (rc != VERR_VD_ASYNC_IO_IN_PROGRESS) /* Another error */
9408 vdIoCtxFree(pDisk, pIoCtx);
9409
9410 } while (0);
9411
9412 if (RT_UNLIKELY(fLockRead) && ( rc == VINF_VD_ASYNC_IO_FINISHED
9413 || rc != VERR_VD_ASYNC_IO_IN_PROGRESS))
9414 {
9415 rc2 = vdThreadFinishRead(pDisk);
9416 AssertRC(rc2);
9417 }
9418
9419 LogFlowFunc(("returns %Rrc\n", rc));
9420 return rc;
9421}
9422
9423
9424VBOXDDU_DECL(int) VDAsyncWrite(PVBOXHDD pDisk, uint64_t uOffset, size_t cbWrite,
9425 PCRTSGBUF pcSgBuf,
9426 PFNVDASYNCTRANSFERCOMPLETE pfnComplete,
9427 void *pvUser1, void *pvUser2)
9428{
9429 int rc;
9430 int rc2;
9431 bool fLockWrite = false;
9432 PVDIOCTX pIoCtx = NULL;
9433
9434 LogFlowFunc(("pDisk=%#p uOffset=%llu cSgBuf=%#p cbWrite=%zu pvUser1=%#p pvUser2=%#p\n",
9435 pDisk, uOffset, pcSgBuf, cbWrite, pvUser1, pvUser2));
9436 do
9437 {
9438 /* sanity check */
9439 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
9440 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
9441
9442 /* Check arguments. */
9443 AssertMsgBreakStmt(cbWrite,
9444 ("cbWrite=%zu\n", cbWrite),
9445 rc = VERR_INVALID_PARAMETER);
9446 AssertMsgBreakStmt(VALID_PTR(pcSgBuf),
9447 ("pcSgBuf=%#p\n", pcSgBuf),
9448 rc = VERR_INVALID_PARAMETER);
9449
9450 rc2 = vdThreadStartWrite(pDisk);
9451 AssertRC(rc2);
9452 fLockWrite = true;
9453
9454 AssertMsgBreakStmt(uOffset + cbWrite <= pDisk->cbSize,
9455 ("uOffset=%llu cbWrite=%zu pDisk->cbSize=%llu\n",
9456 uOffset, cbWrite, pDisk->cbSize),
9457 rc = VERR_INVALID_PARAMETER);
9458 AssertPtrBreakStmt(pDisk->pLast, rc = VERR_VD_NOT_OPENED);
9459
9460 pIoCtx = vdIoCtxRootAlloc(pDisk, VDIOCTXTXDIR_WRITE, uOffset,
9461 cbWrite, pDisk->pLast, pcSgBuf,
9462 pfnComplete, pvUser1, pvUser2,
9463 NULL, vdWriteHelperAsync);
9464 if (!pIoCtx)
9465 {
9466 rc = VERR_NO_MEMORY;
9467 break;
9468 }
9469
9470#if 0
9471 rc = vdIoCtxProcessTryLockDefer(pIoCtx);
9472#else
9473 rc = vdIoCtxProcess(pIoCtx);
9474#endif
9475 if (rc == VINF_VD_ASYNC_IO_FINISHED)
9476 {
9477 if (ASMAtomicCmpXchgBool(&pIoCtx->fComplete, true, false))
9478 vdIoCtxFree(pDisk, pIoCtx);
9479 else
9480 rc = VERR_VD_ASYNC_IO_IN_PROGRESS; /* Let the other handler complete the request. */
9481 }
9482 else if (rc != VERR_VD_ASYNC_IO_IN_PROGRESS) /* Another error */
9483 vdIoCtxFree(pDisk, pIoCtx);
9484 } while (0);
9485
9486 if (RT_UNLIKELY(fLockWrite) && ( rc == VINF_VD_ASYNC_IO_FINISHED
9487 || rc != VERR_VD_ASYNC_IO_IN_PROGRESS))
9488 {
9489 rc2 = vdThreadFinishWrite(pDisk);
9490 AssertRC(rc2);
9491 }
9492
9493 LogFlowFunc(("returns %Rrc\n", rc));
9494 return rc;
9495}
9496
9497
9498VBOXDDU_DECL(int) VDAsyncFlush(PVBOXHDD pDisk, PFNVDASYNCTRANSFERCOMPLETE pfnComplete,
9499 void *pvUser1, void *pvUser2)
9500{
9501 int rc;
9502 int rc2;
9503 bool fLockWrite = false;
9504 PVDIOCTX pIoCtx = NULL;
9505
9506 LogFlowFunc(("pDisk=%#p\n", pDisk));
9507
9508 do
9509 {
9510 /* sanity check */
9511 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
9512 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
9513
9514 rc2 = vdThreadStartWrite(pDisk);
9515 AssertRC(rc2);
9516 fLockWrite = true;
9517
9518 AssertPtrBreakStmt(pDisk->pLast, rc = VERR_VD_NOT_OPENED);
9519
9520 pIoCtx = vdIoCtxRootAlloc(pDisk, VDIOCTXTXDIR_FLUSH, 0,
9521 0, pDisk->pLast, NULL,
9522 pfnComplete, pvUser1, pvUser2,
9523 NULL, vdFlushHelperAsync);
9524 if (!pIoCtx)
9525 {
9526 rc = VERR_NO_MEMORY;
9527 break;
9528 }
9529
9530#if 0
9531 rc = vdIoCtxProcessTryLockDefer(pIoCtx);
9532#else
9533 rc = vdIoCtxProcess(pIoCtx);
9534#endif
9535 if (rc == VINF_VD_ASYNC_IO_FINISHED)
9536 {
9537 if (ASMAtomicCmpXchgBool(&pIoCtx->fComplete, true, false))
9538 vdIoCtxFree(pDisk, pIoCtx);
9539 else
9540 rc = VERR_VD_ASYNC_IO_IN_PROGRESS; /* Let the other handler complete the request. */
9541 }
9542 else if (rc != VERR_VD_ASYNC_IO_IN_PROGRESS) /* Another error */
9543 vdIoCtxFree(pDisk, pIoCtx);
9544 } while (0);
9545
9546 if (RT_UNLIKELY(fLockWrite) && ( rc == VINF_VD_ASYNC_IO_FINISHED
9547 || rc != VERR_VD_ASYNC_IO_IN_PROGRESS))
9548 {
9549 rc2 = vdThreadFinishWrite(pDisk);
9550 AssertRC(rc2);
9551 }
9552
9553 LogFlowFunc(("returns %Rrc\n", rc));
9554 return rc;
9555}
9556
9557VBOXDDU_DECL(int) VDAsyncDiscardRanges(PVBOXHDD pDisk, PCRTRANGE paRanges, unsigned cRanges,
9558 PFNVDASYNCTRANSFERCOMPLETE pfnComplete,
9559 void *pvUser1, void *pvUser2)
9560{
9561 int rc;
9562 int rc2;
9563 bool fLockWrite = false;
9564 PVDIOCTX pIoCtx = NULL;
9565
9566 LogFlowFunc(("pDisk=%#p\n", pDisk));
9567
9568 do
9569 {
9570 /* sanity check */
9571 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
9572 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
9573
9574 rc2 = vdThreadStartWrite(pDisk);
9575 AssertRC(rc2);
9576 fLockWrite = true;
9577
9578 AssertPtrBreakStmt(pDisk->pLast, rc = VERR_VD_NOT_OPENED);
9579
9580 pIoCtx = vdIoCtxDiscardAlloc(pDisk, paRanges, cRanges,
9581 pfnComplete, pvUser1, pvUser2, NULL,
9582 vdDiscardHelperAsync);
9583 if (!pIoCtx)
9584 {
9585 rc = VERR_NO_MEMORY;
9586 break;
9587 }
9588
9589#if 0
9590 rc = vdIoCtxProcessTryLockDefer(pIoCtx);
9591#else
9592 rc = vdIoCtxProcess(pIoCtx);
9593#endif
9594 if (rc == VINF_VD_ASYNC_IO_FINISHED)
9595 {
9596 if (ASMAtomicCmpXchgBool(&pIoCtx->fComplete, true, false))
9597 vdIoCtxFree(pDisk, pIoCtx);
9598 else
9599 rc = VERR_VD_ASYNC_IO_IN_PROGRESS; /* Let the other handler complete the request. */
9600 }
9601 else if (rc != VERR_VD_ASYNC_IO_IN_PROGRESS) /* Another error */
9602 vdIoCtxFree(pDisk, pIoCtx);
9603 } while (0);
9604
9605 if (RT_UNLIKELY(fLockWrite) && ( rc == VINF_VD_ASYNC_IO_FINISHED
9606 || rc != VERR_VD_ASYNC_IO_IN_PROGRESS))
9607 {
9608 rc2 = vdThreadFinishWrite(pDisk);
9609 AssertRC(rc2);
9610 }
9611
9612 LogFlowFunc(("returns %Rrc\n", rc));
9613 return rc;
9614}
9615
9616VBOXDDU_DECL(int) VDRepair(PVDINTERFACE pVDIfsDisk, PVDINTERFACE pVDIfsImage,
9617 const char *pszFilename, const char *pszBackend,
9618 uint32_t fFlags)
9619{
9620 int rc = VERR_NOT_SUPPORTED;
9621 PCVBOXHDDBACKEND pBackend = NULL;
9622 VDINTERFACEIOINT VDIfIoInt;
9623 VDINTERFACEIO VDIfIoFallback;
9624 PVDINTERFACEIO pInterfaceIo;
9625
9626 LogFlowFunc(("pszFilename=\"%s\"\n", pszFilename));
9627 /* Check arguments. */
9628 AssertMsgReturn(VALID_PTR(pszFilename) && *pszFilename,
9629 ("pszFilename=%#p \"%s\"\n", pszFilename, pszFilename),
9630 VERR_INVALID_PARAMETER);
9631 AssertMsgReturn(VALID_PTR(pszBackend),
9632 ("pszBackend=%#p\n", pszBackend),
9633 VERR_INVALID_PARAMETER);
9634 AssertMsgReturn((fFlags & ~VD_REPAIR_FLAGS_MASK) == 0,
9635 ("fFlags=%#x\n", fFlags),
9636 VERR_INVALID_PARAMETER);
9637
9638 pInterfaceIo = VDIfIoGet(pVDIfsImage);
9639 if (!pInterfaceIo)
9640 {
9641 /*
9642 * Caller doesn't provide an I/O interface, create our own using the
9643 * native file API.
9644 */
9645 vdIfIoFallbackCallbacksSetup(&VDIfIoFallback);
9646 pInterfaceIo = &VDIfIoFallback;
9647 }
9648
9649 /* Set up the internal I/O interface. */
9650 AssertReturn(!VDIfIoIntGet(pVDIfsImage), VERR_INVALID_PARAMETER);
9651 VDIfIoInt.pfnOpen = vdIOIntOpenLimited;
9652 VDIfIoInt.pfnClose = vdIOIntCloseLimited;
9653 VDIfIoInt.pfnDelete = vdIOIntDeleteLimited;
9654 VDIfIoInt.pfnMove = vdIOIntMoveLimited;
9655 VDIfIoInt.pfnGetFreeSpace = vdIOIntGetFreeSpaceLimited;
9656 VDIfIoInt.pfnGetModificationTime = vdIOIntGetModificationTimeLimited;
9657 VDIfIoInt.pfnGetSize = vdIOIntGetSizeLimited;
9658 VDIfIoInt.pfnSetSize = vdIOIntSetSizeLimited;
9659 VDIfIoInt.pfnReadSync = vdIOIntReadSyncLimited;
9660 VDIfIoInt.pfnWriteSync = vdIOIntWriteSyncLimited;
9661 VDIfIoInt.pfnFlushSync = vdIOIntFlushSyncLimited;
9662 VDIfIoInt.pfnReadUserAsync = NULL;
9663 VDIfIoInt.pfnWriteUserAsync = NULL;
9664 VDIfIoInt.pfnReadMetaAsync = NULL;
9665 VDIfIoInt.pfnWriteMetaAsync = NULL;
9666 VDIfIoInt.pfnFlushAsync = NULL;
9667 rc = VDInterfaceAdd(&VDIfIoInt.Core, "VD_IOINT", VDINTERFACETYPE_IOINT,
9668 pInterfaceIo, sizeof(VDINTERFACEIOINT), &pVDIfsImage);
9669 AssertRC(rc);
9670
9671 rc = vdFindBackend(pszBackend, &pBackend);
9672 if (RT_SUCCESS(rc))
9673 {
9674 if (pBackend->pfnRepair)
9675 rc = pBackend->pfnRepair(pszFilename, pVDIfsDisk, pVDIfsImage, fFlags);
9676 else
9677 rc = VERR_VD_IMAGE_REPAIR_NOT_SUPPORTED;
9678 }
9679
9680 LogFlowFunc(("returns %Rrc\n", rc));
9681 return rc;
9682}
9683
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