VirtualBox

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

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

Storage: Fix regression introduced when adding VD_OPEN_FLAGS_SKIP_CONSISTENCY_CHECKS resulting in non working online merging of snapshots

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 344.3 KB
Line 
1/* $Id: VD.cpp 44232 2013-01-04 14:30:20Z 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 AssertMsgBreakStmt( !(uOpenFlags & VD_OPEN_FLAGS_SKIP_CONSISTENCY_CHECKS)
5362 || (uOpenFlags & VD_OPEN_FLAGS_READONLY),
5363 ("uOpenFlags=%#x\n", uOpenFlags),
5364 rc = VERR_INVALID_PARAMETER);
5365
5366 /*
5367 * Destroy the current discard state first which might still have pending blocks
5368 * for the currently opened image which will be switched to readonly mode.
5369 */
5370 /* Lock disk for writing, as we modify pDisk information below. */
5371 rc2 = vdThreadStartWrite(pDisk);
5372 AssertRC(rc2);
5373 fLockWrite = true;
5374 rc = vdDiscardStateDestroy(pDisk);
5375 if (RT_FAILURE(rc))
5376 break;
5377 rc2 = vdThreadFinishWrite(pDisk);
5378 AssertRC(rc2);
5379 fLockWrite = false;
5380
5381 /* Set up image descriptor. */
5382 pImage = (PVDIMAGE)RTMemAllocZ(sizeof(VDIMAGE));
5383 if (!pImage)
5384 {
5385 rc = VERR_NO_MEMORY;
5386 break;
5387 }
5388 pImage->pszFilename = RTStrDup(pszFilename);
5389 if (!pImage->pszFilename)
5390 {
5391 rc = VERR_NO_MEMORY;
5392 break;
5393 }
5394
5395 pImage->VDIo.pDisk = pDisk;
5396 pImage->pVDIfsImage = pVDIfsImage;
5397
5398 rc = vdFindBackend(pszBackend, &pImage->Backend);
5399 if (RT_FAILURE(rc))
5400 break;
5401 if (!pImage->Backend)
5402 {
5403 rc = vdError(pDisk, VERR_INVALID_PARAMETER, RT_SRC_POS,
5404 N_("VD: unknown backend name '%s'"), pszBackend);
5405 break;
5406 }
5407
5408 /*
5409 * Fail if the backend can't do async I/O but the
5410 * flag is set.
5411 */
5412 if ( !(pImage->Backend->uBackendCaps & VD_CAP_ASYNC)
5413 && (uOpenFlags & VD_OPEN_FLAGS_ASYNC_IO))
5414 {
5415 rc = vdError(pDisk, VERR_NOT_SUPPORTED, RT_SRC_POS,
5416 N_("VD: Backend '%s' does not support async I/O"), pszBackend);
5417 break;
5418 }
5419
5420 /*
5421 * Fail if the backend doesn't support the discard operation but the
5422 * flag is set.
5423 */
5424 if ( !(pImage->Backend->uBackendCaps & VD_CAP_DISCARD)
5425 && (uOpenFlags & VD_OPEN_FLAGS_DISCARD))
5426 {
5427 rc = vdError(pDisk, VERR_VD_DISCARD_NOT_SUPPORTED, RT_SRC_POS,
5428 N_("VD: Backend '%s' does not support discard"), pszBackend);
5429 break;
5430 }
5431
5432 /* Set up the I/O interface. */
5433 pImage->VDIo.pInterfaceIo = VDIfIoGet(pVDIfsImage);
5434 if (!pImage->VDIo.pInterfaceIo)
5435 {
5436 vdIfIoFallbackCallbacksSetup(&pImage->VDIo.VDIfIo);
5437 rc = VDInterfaceAdd(&pImage->VDIo.VDIfIo.Core, "VD_IO", VDINTERFACETYPE_IO,
5438 pDisk, sizeof(VDINTERFACEIO), &pVDIfsImage);
5439 pImage->VDIo.pInterfaceIo = &pImage->VDIo.VDIfIo;
5440 }
5441
5442 /* Set up the internal I/O interface. */
5443 AssertBreakStmt(!VDIfIoIntGet(pVDIfsImage), rc = VERR_INVALID_PARAMETER);
5444 vdIfIoIntCallbacksSetup(&pImage->VDIo.VDIfIoInt);
5445 rc = VDInterfaceAdd(&pImage->VDIo.VDIfIoInt.Core, "VD_IOINT", VDINTERFACETYPE_IOINT,
5446 &pImage->VDIo, sizeof(VDINTERFACEIOINT), &pImage->pVDIfsImage);
5447 AssertRC(rc);
5448
5449 pImage->uOpenFlags = uOpenFlags & (VD_OPEN_FLAGS_HONOR_SAME | VD_OPEN_FLAGS_DISCARD | VD_OPEN_FLAGS_IGNORE_FLUSH | VD_OPEN_FLAGS_INFORM_ABOUT_ZERO_BLOCKS);
5450 pImage->VDIo.fIgnoreFlush = (uOpenFlags & VD_OPEN_FLAGS_IGNORE_FLUSH) != 0;
5451 rc = pImage->Backend->pfnOpen(pImage->pszFilename,
5452 uOpenFlags & ~(VD_OPEN_FLAGS_HONOR_SAME | VD_OPEN_FLAGS_IGNORE_FLUSH | VD_OPEN_FLAGS_INFORM_ABOUT_ZERO_BLOCKS),
5453 pDisk->pVDIfsDisk,
5454 pImage->pVDIfsImage,
5455 pDisk->enmType,
5456 &pImage->pBackendData);
5457 /*
5458 * If the image is corrupted and there is a repair method try to repair it
5459 * first if it was openend in read-write mode and open again afterwards.
5460 */
5461 if ( RT_UNLIKELY(rc == VERR_VD_IMAGE_CORRUPTED)
5462 && pImage->Backend->pfnRepair)
5463 {
5464 rc = pImage->Backend->pfnRepair(pszFilename, pDisk->pVDIfsDisk, pImage->pVDIfsImage, 0 /* fFlags */);
5465 if (RT_SUCCESS(rc))
5466 rc = pImage->Backend->pfnOpen(pImage->pszFilename,
5467 uOpenFlags & ~(VD_OPEN_FLAGS_HONOR_SAME | VD_OPEN_FLAGS_IGNORE_FLUSH | VD_OPEN_FLAGS_INFORM_ABOUT_ZERO_BLOCKS),
5468 pDisk->pVDIfsDisk,
5469 pImage->pVDIfsImage,
5470 pDisk->enmType,
5471 &pImage->pBackendData);
5472 else
5473 {
5474 rc = vdError(pDisk, rc, RT_SRC_POS,
5475 N_("VD: error %Rrc repairing corrupted image file '%s'"), rc, pszFilename);
5476 break;
5477 }
5478 }
5479 else if (RT_UNLIKELY(rc == VERR_VD_IMAGE_CORRUPTED))
5480 {
5481 rc = vdError(pDisk, rc, RT_SRC_POS,
5482 N_("VD: Image file '%s' is corrupted and can't be opened"), pszFilename);
5483 break;
5484 }
5485
5486 /* If the open in read-write mode failed, retry in read-only mode. */
5487 if (RT_FAILURE(rc))
5488 {
5489 if (!(uOpenFlags & VD_OPEN_FLAGS_READONLY)
5490 && ( rc == VERR_ACCESS_DENIED
5491 || rc == VERR_PERMISSION_DENIED
5492 || rc == VERR_WRITE_PROTECT
5493 || rc == VERR_SHARING_VIOLATION
5494 || rc == VERR_FILE_LOCK_FAILED))
5495 rc = pImage->Backend->pfnOpen(pImage->pszFilename,
5496 (uOpenFlags & ~(VD_OPEN_FLAGS_HONOR_SAME | VD_OPEN_FLAGS_INFORM_ABOUT_ZERO_BLOCKS))
5497 | VD_OPEN_FLAGS_READONLY,
5498 pDisk->pVDIfsDisk,
5499 pImage->pVDIfsImage,
5500 pDisk->enmType,
5501 &pImage->pBackendData);
5502 if (RT_FAILURE(rc))
5503 {
5504 rc = vdError(pDisk, rc, RT_SRC_POS,
5505 N_("VD: error %Rrc opening image file '%s'"), rc, pszFilename);
5506 break;
5507 }
5508 }
5509
5510 /* Lock disk for writing, as we modify pDisk information below. */
5511 rc2 = vdThreadStartWrite(pDisk);
5512 AssertRC(rc2);
5513 fLockWrite = true;
5514
5515 pImage->VDIo.pBackendData = pImage->pBackendData;
5516
5517 /* Check image type. As the image itself has only partial knowledge
5518 * whether it's a base image or not, this info is derived here. The
5519 * base image can be fixed or normal, all others must be normal or
5520 * diff images. Some image formats don't distinguish between normal
5521 * and diff images, so this must be corrected here. */
5522 unsigned uImageFlags;
5523 uImageFlags = pImage->Backend->pfnGetImageFlags(pImage->pBackendData);
5524 if (RT_FAILURE(rc))
5525 uImageFlags = VD_IMAGE_FLAGS_NONE;
5526 if ( RT_SUCCESS(rc)
5527 && !(uOpenFlags & VD_OPEN_FLAGS_INFO))
5528 {
5529 if ( pDisk->cImages == 0
5530 && (uImageFlags & VD_IMAGE_FLAGS_DIFF))
5531 {
5532 rc = VERR_VD_INVALID_TYPE;
5533 break;
5534 }
5535 else if (pDisk->cImages != 0)
5536 {
5537 if (uImageFlags & VD_IMAGE_FLAGS_FIXED)
5538 {
5539 rc = VERR_VD_INVALID_TYPE;
5540 break;
5541 }
5542 else
5543 uImageFlags |= VD_IMAGE_FLAGS_DIFF;
5544 }
5545 }
5546
5547 /* Ensure we always get correct diff information, even if the backend
5548 * doesn't actually have a stored flag for this. It must not return
5549 * bogus information for the parent UUID if it is not a diff image. */
5550 RTUUID parentUuid;
5551 RTUuidClear(&parentUuid);
5552 rc2 = pImage->Backend->pfnGetParentUuid(pImage->pBackendData, &parentUuid);
5553 if (RT_SUCCESS(rc2) && !RTUuidIsNull(&parentUuid))
5554 uImageFlags |= VD_IMAGE_FLAGS_DIFF;
5555
5556 pImage->uImageFlags = uImageFlags;
5557
5558 /* Force sane optimization settings. It's not worth avoiding writes
5559 * to fixed size images. The overhead would have almost no payback. */
5560 if (uImageFlags & VD_IMAGE_FLAGS_FIXED)
5561 pImage->uOpenFlags |= VD_OPEN_FLAGS_HONOR_SAME;
5562
5563 /** @todo optionally check UUIDs */
5564
5565 /* Cache disk information. */
5566 pDisk->cbSize = pImage->Backend->pfnGetSize(pImage->pBackendData);
5567
5568 /* Cache PCHS geometry. */
5569 rc2 = pImage->Backend->pfnGetPCHSGeometry(pImage->pBackendData,
5570 &pDisk->PCHSGeometry);
5571 if (RT_FAILURE(rc2))
5572 {
5573 pDisk->PCHSGeometry.cCylinders = 0;
5574 pDisk->PCHSGeometry.cHeads = 0;
5575 pDisk->PCHSGeometry.cSectors = 0;
5576 }
5577 else
5578 {
5579 /* Make sure the PCHS geometry is properly clipped. */
5580 pDisk->PCHSGeometry.cCylinders = RT_MIN(pDisk->PCHSGeometry.cCylinders, 16383);
5581 pDisk->PCHSGeometry.cHeads = RT_MIN(pDisk->PCHSGeometry.cHeads, 16);
5582 pDisk->PCHSGeometry.cSectors = RT_MIN(pDisk->PCHSGeometry.cSectors, 63);
5583 }
5584
5585 /* Cache LCHS geometry. */
5586 rc2 = pImage->Backend->pfnGetLCHSGeometry(pImage->pBackendData,
5587 &pDisk->LCHSGeometry);
5588 if (RT_FAILURE(rc2))
5589 {
5590 pDisk->LCHSGeometry.cCylinders = 0;
5591 pDisk->LCHSGeometry.cHeads = 0;
5592 pDisk->LCHSGeometry.cSectors = 0;
5593 }
5594 else
5595 {
5596 /* Make sure the LCHS geometry is properly clipped. */
5597 pDisk->LCHSGeometry.cHeads = RT_MIN(pDisk->LCHSGeometry.cHeads, 255);
5598 pDisk->LCHSGeometry.cSectors = RT_MIN(pDisk->LCHSGeometry.cSectors, 63);
5599 }
5600
5601 if (pDisk->cImages != 0)
5602 {
5603 /* Switch previous image to read-only mode. */
5604 unsigned uOpenFlagsPrevImg;
5605 uOpenFlagsPrevImg = pDisk->pLast->Backend->pfnGetOpenFlags(pDisk->pLast->pBackendData);
5606 if (!(uOpenFlagsPrevImg & VD_OPEN_FLAGS_READONLY))
5607 {
5608 uOpenFlagsPrevImg |= VD_OPEN_FLAGS_READONLY;
5609 rc = pDisk->pLast->Backend->pfnSetOpenFlags(pDisk->pLast->pBackendData, uOpenFlagsPrevImg);
5610 }
5611 }
5612
5613 if (RT_SUCCESS(rc))
5614 {
5615 /* Image successfully opened, make it the last image. */
5616 vdAddImageToList(pDisk, pImage);
5617 if (!(uOpenFlags & VD_OPEN_FLAGS_READONLY))
5618 pDisk->uModified = VD_IMAGE_MODIFIED_FIRST;
5619 }
5620 else
5621 {
5622 /* Error detected, but image opened. Close image. */
5623 rc2 = pImage->Backend->pfnClose(pImage->pBackendData, false);
5624 AssertRC(rc2);
5625 pImage->pBackendData = NULL;
5626 }
5627 } while (0);
5628
5629 if (RT_UNLIKELY(fLockWrite))
5630 {
5631 rc2 = vdThreadFinishWrite(pDisk);
5632 AssertRC(rc2);
5633 }
5634
5635 if (RT_FAILURE(rc))
5636 {
5637 if (pImage)
5638 {
5639 if (pImage->pszFilename)
5640 RTStrFree(pImage->pszFilename);
5641 RTMemFree(pImage);
5642 }
5643 }
5644
5645 LogFlowFunc(("returns %Rrc\n", rc));
5646 return rc;
5647}
5648
5649/**
5650 * Opens a cache image.
5651 *
5652 * @return VBox status code.
5653 * @param pDisk Pointer to the HDD container which should use the cache image.
5654 * @param pszBackend Name of the cache file backend to use (case insensitive).
5655 * @param pszFilename Name of the cache image to open.
5656 * @param uOpenFlags Image file open mode, see VD_OPEN_FLAGS_* constants.
5657 * @param pVDIfsCache Pointer to the per-cache VD interface list.
5658 */
5659VBOXDDU_DECL(int) VDCacheOpen(PVBOXHDD pDisk, const char *pszBackend,
5660 const char *pszFilename, unsigned uOpenFlags,
5661 PVDINTERFACE pVDIfsCache)
5662{
5663 int rc = VINF_SUCCESS;
5664 int rc2;
5665 bool fLockWrite = false;
5666 PVDCACHE pCache = NULL;
5667
5668 LogFlowFunc(("pDisk=%#p pszBackend=\"%s\" pszFilename=\"%s\" uOpenFlags=%#x, pVDIfsCache=%#p\n",
5669 pDisk, pszBackend, pszFilename, uOpenFlags, pVDIfsCache));
5670
5671 do
5672 {
5673 /* sanity check */
5674 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
5675 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
5676
5677 /* Check arguments. */
5678 AssertMsgBreakStmt(VALID_PTR(pszBackend) && *pszBackend,
5679 ("pszBackend=%#p \"%s\"\n", pszBackend, pszBackend),
5680 rc = VERR_INVALID_PARAMETER);
5681 AssertMsgBreakStmt(VALID_PTR(pszFilename) && *pszFilename,
5682 ("pszFilename=%#p \"%s\"\n", pszFilename, pszFilename),
5683 rc = VERR_INVALID_PARAMETER);
5684 AssertMsgBreakStmt((uOpenFlags & ~VD_OPEN_FLAGS_MASK) == 0,
5685 ("uOpenFlags=%#x\n", uOpenFlags),
5686 rc = VERR_INVALID_PARAMETER);
5687
5688 /* Set up image descriptor. */
5689 pCache = (PVDCACHE)RTMemAllocZ(sizeof(VDCACHE));
5690 if (!pCache)
5691 {
5692 rc = VERR_NO_MEMORY;
5693 break;
5694 }
5695 pCache->pszFilename = RTStrDup(pszFilename);
5696 if (!pCache->pszFilename)
5697 {
5698 rc = VERR_NO_MEMORY;
5699 break;
5700 }
5701
5702 pCache->VDIo.pDisk = pDisk;
5703 pCache->pVDIfsCache = pVDIfsCache;
5704
5705 rc = vdFindCacheBackend(pszBackend, &pCache->Backend);
5706 if (RT_FAILURE(rc))
5707 break;
5708 if (!pCache->Backend)
5709 {
5710 rc = vdError(pDisk, VERR_INVALID_PARAMETER, RT_SRC_POS,
5711 N_("VD: unknown backend name '%s'"), pszBackend);
5712 break;
5713 }
5714
5715 /* Set up the I/O interface. */
5716 pCache->VDIo.pInterfaceIo = VDIfIoGet(pVDIfsCache);
5717 if (!pCache->VDIo.pInterfaceIo)
5718 {
5719 vdIfIoFallbackCallbacksSetup(&pCache->VDIo.VDIfIo);
5720 rc = VDInterfaceAdd(&pCache->VDIo.VDIfIo.Core, "VD_IO", VDINTERFACETYPE_IO,
5721 pDisk, sizeof(VDINTERFACEIO), &pVDIfsCache);
5722 pCache->VDIo.pInterfaceIo = &pCache->VDIo.VDIfIo;
5723 }
5724
5725 /* Set up the internal I/O interface. */
5726 AssertBreakStmt(!VDIfIoIntGet(pVDIfsCache), rc = VERR_INVALID_PARAMETER);
5727 vdIfIoIntCallbacksSetup(&pCache->VDIo.VDIfIoInt);
5728 rc = VDInterfaceAdd(&pCache->VDIo.VDIfIoInt.Core, "VD_IOINT", VDINTERFACETYPE_IOINT,
5729 &pCache->VDIo, sizeof(VDINTERFACEIOINT), &pCache->pVDIfsCache);
5730 AssertRC(rc);
5731
5732 pCache->uOpenFlags = uOpenFlags & VD_OPEN_FLAGS_HONOR_SAME;
5733 rc = pCache->Backend->pfnOpen(pCache->pszFilename,
5734 uOpenFlags & ~VD_OPEN_FLAGS_HONOR_SAME,
5735 pDisk->pVDIfsDisk,
5736 pCache->pVDIfsCache,
5737 &pCache->pBackendData);
5738 /* If the open in read-write mode failed, retry in read-only mode. */
5739 if (RT_FAILURE(rc))
5740 {
5741 if (!(uOpenFlags & VD_OPEN_FLAGS_READONLY)
5742 && ( rc == VERR_ACCESS_DENIED
5743 || rc == VERR_PERMISSION_DENIED
5744 || rc == VERR_WRITE_PROTECT
5745 || rc == VERR_SHARING_VIOLATION
5746 || rc == VERR_FILE_LOCK_FAILED))
5747 rc = pCache->Backend->pfnOpen(pCache->pszFilename,
5748 (uOpenFlags & ~VD_OPEN_FLAGS_HONOR_SAME)
5749 | VD_OPEN_FLAGS_READONLY,
5750 pDisk->pVDIfsDisk,
5751 pCache->pVDIfsCache,
5752 &pCache->pBackendData);
5753 if (RT_FAILURE(rc))
5754 {
5755 rc = vdError(pDisk, rc, RT_SRC_POS,
5756 N_("VD: error %Rrc opening image file '%s'"), rc, pszFilename);
5757 break;
5758 }
5759 }
5760
5761 /* Lock disk for writing, as we modify pDisk information below. */
5762 rc2 = vdThreadStartWrite(pDisk);
5763 AssertRC(rc2);
5764 fLockWrite = true;
5765
5766 /*
5767 * Check that the modification UUID of the cache and last image
5768 * match. If not the image was modified in-between without the cache.
5769 * The cache might contain stale data.
5770 */
5771 RTUUID UuidImage, UuidCache;
5772
5773 rc = pCache->Backend->pfnGetModificationUuid(pCache->pBackendData,
5774 &UuidCache);
5775 if (RT_SUCCESS(rc))
5776 {
5777 rc = pDisk->pLast->Backend->pfnGetModificationUuid(pDisk->pLast->pBackendData,
5778 &UuidImage);
5779 if (RT_SUCCESS(rc))
5780 {
5781 if (RTUuidCompare(&UuidImage, &UuidCache))
5782 rc = VERR_VD_CACHE_NOT_UP_TO_DATE;
5783 }
5784 }
5785
5786 /*
5787 * We assume that the user knows what he is doing if one of the images
5788 * doesn't support the modification uuid.
5789 */
5790 if (rc == VERR_NOT_SUPPORTED)
5791 rc = VINF_SUCCESS;
5792
5793 if (RT_SUCCESS(rc))
5794 {
5795 /* Cache successfully opened, make it the current one. */
5796 if (!pDisk->pCache)
5797 pDisk->pCache = pCache;
5798 else
5799 rc = VERR_VD_CACHE_ALREADY_EXISTS;
5800 }
5801
5802 if (RT_FAILURE(rc))
5803 {
5804 /* Error detected, but image opened. Close image. */
5805 rc2 = pCache->Backend->pfnClose(pCache->pBackendData, false);
5806 AssertRC(rc2);
5807 pCache->pBackendData = NULL;
5808 }
5809 } while (0);
5810
5811 if (RT_UNLIKELY(fLockWrite))
5812 {
5813 rc2 = vdThreadFinishWrite(pDisk);
5814 AssertRC(rc2);
5815 }
5816
5817 if (RT_FAILURE(rc))
5818 {
5819 if (pCache)
5820 {
5821 if (pCache->pszFilename)
5822 RTStrFree(pCache->pszFilename);
5823 RTMemFree(pCache);
5824 }
5825 }
5826
5827 LogFlowFunc(("returns %Rrc\n", rc));
5828 return rc;
5829}
5830
5831/**
5832 * Creates and opens a new base image file.
5833 *
5834 * @returns VBox status code.
5835 * @param pDisk Pointer to HDD container.
5836 * @param pszBackend Name of the image file backend to use.
5837 * @param pszFilename Name of the image file to create.
5838 * @param cbSize Image size in bytes.
5839 * @param uImageFlags Flags specifying special image features.
5840 * @param pszComment Pointer to image comment. NULL is ok.
5841 * @param pPCHSGeometry Pointer to physical disk geometry <= (16383,16,63). Not NULL.
5842 * @param pLCHSGeometry Pointer to logical disk geometry <= (x,255,63). Not NULL.
5843 * @param pUuid New UUID of the image. If NULL, a new UUID is created.
5844 * @param uOpenFlags Image file open mode, see VD_OPEN_FLAGS_* constants.
5845 * @param pVDIfsImage Pointer to the per-image VD interface list.
5846 * @param pVDIfsOperation Pointer to the per-operation VD interface list.
5847 */
5848VBOXDDU_DECL(int) VDCreateBase(PVBOXHDD pDisk, const char *pszBackend,
5849 const char *pszFilename, uint64_t cbSize,
5850 unsigned uImageFlags, const char *pszComment,
5851 PCVDGEOMETRY pPCHSGeometry,
5852 PCVDGEOMETRY pLCHSGeometry,
5853 PCRTUUID pUuid, unsigned uOpenFlags,
5854 PVDINTERFACE pVDIfsImage,
5855 PVDINTERFACE pVDIfsOperation)
5856{
5857 int rc = VINF_SUCCESS;
5858 int rc2;
5859 bool fLockWrite = false, fLockRead = false;
5860 PVDIMAGE pImage = NULL;
5861 RTUUID uuid;
5862
5863 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",
5864 pDisk, pszBackend, pszFilename, cbSize, uImageFlags, pszComment,
5865 pPCHSGeometry->cCylinders, pPCHSGeometry->cHeads,
5866 pPCHSGeometry->cSectors, pLCHSGeometry->cCylinders,
5867 pLCHSGeometry->cHeads, pLCHSGeometry->cSectors, pUuid,
5868 uOpenFlags, pVDIfsImage, pVDIfsOperation));
5869
5870 PVDINTERFACEPROGRESS pIfProgress = VDIfProgressGet(pVDIfsOperation);
5871
5872 do
5873 {
5874 /* sanity check */
5875 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
5876 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
5877
5878 /* Check arguments. */
5879 AssertMsgBreakStmt(VALID_PTR(pszBackend) && *pszBackend,
5880 ("pszBackend=%#p \"%s\"\n", pszBackend, pszBackend),
5881 rc = VERR_INVALID_PARAMETER);
5882 AssertMsgBreakStmt(VALID_PTR(pszFilename) && *pszFilename,
5883 ("pszFilename=%#p \"%s\"\n", pszFilename, pszFilename),
5884 rc = VERR_INVALID_PARAMETER);
5885 AssertMsgBreakStmt(cbSize,
5886 ("cbSize=%llu\n", cbSize),
5887 rc = VERR_INVALID_PARAMETER);
5888 AssertMsgBreakStmt( ((uImageFlags & ~VD_IMAGE_FLAGS_MASK) == 0)
5889 || ((uImageFlags & (VD_IMAGE_FLAGS_FIXED | VD_IMAGE_FLAGS_DIFF)) != VD_IMAGE_FLAGS_FIXED),
5890 ("uImageFlags=%#x\n", uImageFlags),
5891 rc = VERR_INVALID_PARAMETER);
5892 /* The PCHS geometry fields may be 0 to leave it for later. */
5893 AssertMsgBreakStmt( VALID_PTR(pPCHSGeometry)
5894 && pPCHSGeometry->cHeads <= 16
5895 && pPCHSGeometry->cSectors <= 63,
5896 ("pPCHSGeometry=%#p PCHS=%u/%u/%u\n", pPCHSGeometry,
5897 pPCHSGeometry->cCylinders, pPCHSGeometry->cHeads,
5898 pPCHSGeometry->cSectors),
5899 rc = VERR_INVALID_PARAMETER);
5900 /* The LCHS geometry fields may be 0 to leave it to later autodetection. */
5901 AssertMsgBreakStmt( VALID_PTR(pLCHSGeometry)
5902 && pLCHSGeometry->cHeads <= 255
5903 && pLCHSGeometry->cSectors <= 63,
5904 ("pLCHSGeometry=%#p LCHS=%u/%u/%u\n", pLCHSGeometry,
5905 pLCHSGeometry->cCylinders, pLCHSGeometry->cHeads,
5906 pLCHSGeometry->cSectors),
5907 rc = VERR_INVALID_PARAMETER);
5908 /* The UUID may be NULL. */
5909 AssertMsgBreakStmt(pUuid == NULL || VALID_PTR(pUuid),
5910 ("pUuid=%#p UUID=%RTuuid\n", pUuid, pUuid),
5911 rc = VERR_INVALID_PARAMETER);
5912 AssertMsgBreakStmt((uOpenFlags & ~VD_OPEN_FLAGS_MASK) == 0,
5913 ("uOpenFlags=%#x\n", uOpenFlags),
5914 rc = VERR_INVALID_PARAMETER);
5915
5916 /* Check state. Needs a temporary read lock. Holding the write lock
5917 * all the time would be blocking other activities for too long. */
5918 rc2 = vdThreadStartRead(pDisk);
5919 AssertRC(rc2);
5920 fLockRead = true;
5921 AssertMsgBreakStmt(pDisk->cImages == 0,
5922 ("Create base image cannot be done with other images open\n"),
5923 rc = VERR_VD_INVALID_STATE);
5924 rc2 = vdThreadFinishRead(pDisk);
5925 AssertRC(rc2);
5926 fLockRead = false;
5927
5928 /* Set up image descriptor. */
5929 pImage = (PVDIMAGE)RTMemAllocZ(sizeof(VDIMAGE));
5930 if (!pImage)
5931 {
5932 rc = VERR_NO_MEMORY;
5933 break;
5934 }
5935 pImage->pszFilename = RTStrDup(pszFilename);
5936 if (!pImage->pszFilename)
5937 {
5938 rc = VERR_NO_MEMORY;
5939 break;
5940 }
5941 pImage->VDIo.pDisk = pDisk;
5942 pImage->pVDIfsImage = pVDIfsImage;
5943
5944 /* Set up the I/O interface. */
5945 pImage->VDIo.pInterfaceIo = VDIfIoGet(pVDIfsImage);
5946 if (!pImage->VDIo.pInterfaceIo)
5947 {
5948 vdIfIoFallbackCallbacksSetup(&pImage->VDIo.VDIfIo);
5949 rc = VDInterfaceAdd(&pImage->VDIo.VDIfIo.Core, "VD_IO", VDINTERFACETYPE_IO,
5950 pDisk, sizeof(VDINTERFACEIO), &pVDIfsImage);
5951 pImage->VDIo.pInterfaceIo = &pImage->VDIo.VDIfIo;
5952 }
5953
5954 /* Set up the internal I/O interface. */
5955 AssertBreakStmt(!VDIfIoIntGet(pVDIfsImage), rc = VERR_INVALID_PARAMETER);
5956 vdIfIoIntCallbacksSetup(&pImage->VDIo.VDIfIoInt);
5957 rc = VDInterfaceAdd(&pImage->VDIo.VDIfIoInt.Core, "VD_IOINT", VDINTERFACETYPE_IOINT,
5958 &pImage->VDIo, sizeof(VDINTERFACEIOINT), &pImage->pVDIfsImage);
5959 AssertRC(rc);
5960
5961 rc = vdFindBackend(pszBackend, &pImage->Backend);
5962 if (RT_FAILURE(rc))
5963 break;
5964 if (!pImage->Backend)
5965 {
5966 rc = vdError(pDisk, VERR_INVALID_PARAMETER, RT_SRC_POS,
5967 N_("VD: unknown backend name '%s'"), pszBackend);
5968 break;
5969 }
5970 if (!(pImage->Backend->uBackendCaps & ( VD_CAP_CREATE_FIXED
5971 | VD_CAP_CREATE_DYNAMIC)))
5972 {
5973 rc = vdError(pDisk, VERR_INVALID_PARAMETER, RT_SRC_POS,
5974 N_("VD: backend '%s' cannot create base images"), pszBackend);
5975 break;
5976 }
5977
5978 /* Create UUID if the caller didn't specify one. */
5979 if (!pUuid)
5980 {
5981 rc = RTUuidCreate(&uuid);
5982 if (RT_FAILURE(rc))
5983 {
5984 rc = vdError(pDisk, rc, RT_SRC_POS,
5985 N_("VD: cannot generate UUID for image '%s'"),
5986 pszFilename);
5987 break;
5988 }
5989 pUuid = &uuid;
5990 }
5991
5992 pImage->uOpenFlags = uOpenFlags & VD_OPEN_FLAGS_HONOR_SAME;
5993 uImageFlags &= ~VD_IMAGE_FLAGS_DIFF;
5994 pImage->VDIo.fIgnoreFlush = (uOpenFlags & VD_OPEN_FLAGS_IGNORE_FLUSH) != 0;
5995 rc = pImage->Backend->pfnCreate(pImage->pszFilename, cbSize,
5996 uImageFlags, pszComment, pPCHSGeometry,
5997 pLCHSGeometry, pUuid,
5998 uOpenFlags & ~VD_OPEN_FLAGS_HONOR_SAME,
5999 0, 99,
6000 pDisk->pVDIfsDisk,
6001 pImage->pVDIfsImage,
6002 pVDIfsOperation,
6003 &pImage->pBackendData);
6004
6005 if (RT_SUCCESS(rc))
6006 {
6007 pImage->VDIo.pBackendData = pImage->pBackendData;
6008 pImage->uImageFlags = uImageFlags;
6009
6010 /* Force sane optimization settings. It's not worth avoiding writes
6011 * to fixed size images. The overhead would have almost no payback. */
6012 if (uImageFlags & VD_IMAGE_FLAGS_FIXED)
6013 pImage->uOpenFlags |= VD_OPEN_FLAGS_HONOR_SAME;
6014
6015 /* Lock disk for writing, as we modify pDisk information below. */
6016 rc2 = vdThreadStartWrite(pDisk);
6017 AssertRC(rc2);
6018 fLockWrite = true;
6019
6020 /** @todo optionally check UUIDs */
6021
6022 /* Re-check state, as the lock wasn't held and another image
6023 * creation call could have been done by another thread. */
6024 AssertMsgStmt(pDisk->cImages == 0,
6025 ("Create base image cannot be done with other images open\n"),
6026 rc = VERR_VD_INVALID_STATE);
6027 }
6028
6029 if (RT_SUCCESS(rc))
6030 {
6031 /* Cache disk information. */
6032 pDisk->cbSize = pImage->Backend->pfnGetSize(pImage->pBackendData);
6033
6034 /* Cache PCHS geometry. */
6035 rc2 = pImage->Backend->pfnGetPCHSGeometry(pImage->pBackendData,
6036 &pDisk->PCHSGeometry);
6037 if (RT_FAILURE(rc2))
6038 {
6039 pDisk->PCHSGeometry.cCylinders = 0;
6040 pDisk->PCHSGeometry.cHeads = 0;
6041 pDisk->PCHSGeometry.cSectors = 0;
6042 }
6043 else
6044 {
6045 /* Make sure the CHS geometry is properly clipped. */
6046 pDisk->PCHSGeometry.cCylinders = RT_MIN(pDisk->PCHSGeometry.cCylinders, 16383);
6047 pDisk->PCHSGeometry.cHeads = RT_MIN(pDisk->PCHSGeometry.cHeads, 16);
6048 pDisk->PCHSGeometry.cSectors = RT_MIN(pDisk->PCHSGeometry.cSectors, 63);
6049 }
6050
6051 /* Cache LCHS geometry. */
6052 rc2 = pImage->Backend->pfnGetLCHSGeometry(pImage->pBackendData,
6053 &pDisk->LCHSGeometry);
6054 if (RT_FAILURE(rc2))
6055 {
6056 pDisk->LCHSGeometry.cCylinders = 0;
6057 pDisk->LCHSGeometry.cHeads = 0;
6058 pDisk->LCHSGeometry.cSectors = 0;
6059 }
6060 else
6061 {
6062 /* Make sure the CHS geometry is properly clipped. */
6063 pDisk->LCHSGeometry.cHeads = RT_MIN(pDisk->LCHSGeometry.cHeads, 255);
6064 pDisk->LCHSGeometry.cSectors = RT_MIN(pDisk->LCHSGeometry.cSectors, 63);
6065 }
6066
6067 /* Image successfully opened, make it the last image. */
6068 vdAddImageToList(pDisk, pImage);
6069 if (!(uOpenFlags & VD_OPEN_FLAGS_READONLY))
6070 pDisk->uModified = VD_IMAGE_MODIFIED_FIRST;
6071 }
6072 else
6073 {
6074 /* Error detected, image may or may not be opened. Close and delete
6075 * image if it was opened. */
6076 if (pImage->pBackendData)
6077 {
6078 rc2 = pImage->Backend->pfnClose(pImage->pBackendData, true);
6079 AssertRC(rc2);
6080 pImage->pBackendData = NULL;
6081 }
6082 }
6083 } while (0);
6084
6085 if (RT_UNLIKELY(fLockWrite))
6086 {
6087 rc2 = vdThreadFinishWrite(pDisk);
6088 AssertRC(rc2);
6089 }
6090 else if (RT_UNLIKELY(fLockRead))
6091 {
6092 rc2 = vdThreadFinishRead(pDisk);
6093 AssertRC(rc2);
6094 }
6095
6096 if (RT_FAILURE(rc))
6097 {
6098 if (pImage)
6099 {
6100 if (pImage->pszFilename)
6101 RTStrFree(pImage->pszFilename);
6102 RTMemFree(pImage);
6103 }
6104 }
6105
6106 if (RT_SUCCESS(rc) && pIfProgress && pIfProgress->pfnProgress)
6107 pIfProgress->pfnProgress(pIfProgress->Core.pvUser, 100);
6108
6109 LogFlowFunc(("returns %Rrc\n", rc));
6110 return rc;
6111}
6112
6113/**
6114 * Creates and opens a new differencing image file in HDD container.
6115 * See comments for VDOpen function about differencing images.
6116 *
6117 * @returns VBox status code.
6118 * @param pDisk Pointer to HDD container.
6119 * @param pszBackend Name of the image file backend to use.
6120 * @param pszFilename Name of the differencing image file to create.
6121 * @param uImageFlags Flags specifying special image features.
6122 * @param pszComment Pointer to image comment. NULL is ok.
6123 * @param pUuid New UUID of the image. If NULL, a new UUID is created.
6124 * @param pParentUuid New parent UUID of the image. If NULL, the UUID is queried automatically.
6125 * @param uOpenFlags Image file open mode, see VD_OPEN_FLAGS_* constants.
6126 * @param pVDIfsImage Pointer to the per-image VD interface list.
6127 * @param pVDIfsOperation Pointer to the per-operation VD interface list.
6128 */
6129VBOXDDU_DECL(int) VDCreateDiff(PVBOXHDD pDisk, const char *pszBackend,
6130 const char *pszFilename, unsigned uImageFlags,
6131 const char *pszComment, PCRTUUID pUuid,
6132 PCRTUUID pParentUuid, unsigned uOpenFlags,
6133 PVDINTERFACE pVDIfsImage,
6134 PVDINTERFACE pVDIfsOperation)
6135{
6136 int rc = VINF_SUCCESS;
6137 int rc2;
6138 bool fLockWrite = false, fLockRead = false;
6139 PVDIMAGE pImage = NULL;
6140 RTUUID uuid;
6141
6142 LogFlowFunc(("pDisk=%#p pszBackend=\"%s\" pszFilename=\"%s\" uImageFlags=%#x pszComment=\"%s\" Uuid=%RTuuid uOpenFlags=%#x pVDIfsImage=%#p pVDIfsOperation=%#p\n",
6143 pDisk, pszBackend, pszFilename, uImageFlags, pszComment, pUuid, uOpenFlags, pVDIfsImage, pVDIfsOperation));
6144
6145 PVDINTERFACEPROGRESS pIfProgress = VDIfProgressGet(pVDIfsOperation);
6146
6147 do
6148 {
6149 /* sanity check */
6150 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
6151 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
6152
6153 /* Check arguments. */
6154 AssertMsgBreakStmt(VALID_PTR(pszBackend) && *pszBackend,
6155 ("pszBackend=%#p \"%s\"\n", pszBackend, pszBackend),
6156 rc = VERR_INVALID_PARAMETER);
6157 AssertMsgBreakStmt(VALID_PTR(pszFilename) && *pszFilename,
6158 ("pszFilename=%#p \"%s\"\n", pszFilename, pszFilename),
6159 rc = VERR_INVALID_PARAMETER);
6160 AssertMsgBreakStmt((uImageFlags & ~VD_IMAGE_FLAGS_MASK) == 0,
6161 ("uImageFlags=%#x\n", uImageFlags),
6162 rc = VERR_INVALID_PARAMETER);
6163 /* The UUID may be NULL. */
6164 AssertMsgBreakStmt(pUuid == NULL || VALID_PTR(pUuid),
6165 ("pUuid=%#p UUID=%RTuuid\n", pUuid, pUuid),
6166 rc = VERR_INVALID_PARAMETER);
6167 /* The parent UUID may be NULL. */
6168 AssertMsgBreakStmt(pParentUuid == NULL || VALID_PTR(pParentUuid),
6169 ("pParentUuid=%#p ParentUUID=%RTuuid\n", pParentUuid, pParentUuid),
6170 rc = VERR_INVALID_PARAMETER);
6171 AssertMsgBreakStmt((uOpenFlags & ~VD_OPEN_FLAGS_MASK) == 0,
6172 ("uOpenFlags=%#x\n", uOpenFlags),
6173 rc = VERR_INVALID_PARAMETER);
6174
6175 /* Check state. Needs a temporary read lock. Holding the write lock
6176 * all the time would be blocking other activities for too long. */
6177 rc2 = vdThreadStartRead(pDisk);
6178 AssertRC(rc2);
6179 fLockRead = true;
6180 AssertMsgBreakStmt(pDisk->cImages != 0,
6181 ("Create diff image cannot be done without other images open\n"),
6182 rc = VERR_VD_INVALID_STATE);
6183 rc2 = vdThreadFinishRead(pDisk);
6184 AssertRC(rc2);
6185 fLockRead = false;
6186
6187 /*
6188 * Destroy the current discard state first which might still have pending blocks
6189 * for the currently opened image which will be switched to readonly mode.
6190 */
6191 /* Lock disk for writing, as we modify pDisk information below. */
6192 rc2 = vdThreadStartWrite(pDisk);
6193 AssertRC(rc2);
6194 fLockWrite = true;
6195 rc = vdDiscardStateDestroy(pDisk);
6196 if (RT_FAILURE(rc))
6197 break;
6198 rc2 = vdThreadFinishWrite(pDisk);
6199 AssertRC(rc2);
6200 fLockWrite = false;
6201
6202 /* Set up image descriptor. */
6203 pImage = (PVDIMAGE)RTMemAllocZ(sizeof(VDIMAGE));
6204 if (!pImage)
6205 {
6206 rc = VERR_NO_MEMORY;
6207 break;
6208 }
6209 pImage->pszFilename = RTStrDup(pszFilename);
6210 if (!pImage->pszFilename)
6211 {
6212 rc = VERR_NO_MEMORY;
6213 break;
6214 }
6215
6216 rc = vdFindBackend(pszBackend, &pImage->Backend);
6217 if (RT_FAILURE(rc))
6218 break;
6219 if (!pImage->Backend)
6220 {
6221 rc = vdError(pDisk, VERR_INVALID_PARAMETER, RT_SRC_POS,
6222 N_("VD: unknown backend name '%s'"), pszBackend);
6223 break;
6224 }
6225 if ( !(pImage->Backend->uBackendCaps & VD_CAP_DIFF)
6226 || !(pImage->Backend->uBackendCaps & ( VD_CAP_CREATE_FIXED
6227 | VD_CAP_CREATE_DYNAMIC)))
6228 {
6229 rc = vdError(pDisk, VERR_INVALID_PARAMETER, RT_SRC_POS,
6230 N_("VD: backend '%s' cannot create diff images"), pszBackend);
6231 break;
6232 }
6233
6234 pImage->VDIo.pDisk = pDisk;
6235 pImage->pVDIfsImage = pVDIfsImage;
6236
6237 /* Set up the I/O interface. */
6238 pImage->VDIo.pInterfaceIo = VDIfIoGet(pVDIfsImage);
6239 if (!pImage->VDIo.pInterfaceIo)
6240 {
6241 vdIfIoFallbackCallbacksSetup(&pImage->VDIo.VDIfIo);
6242 rc = VDInterfaceAdd(&pImage->VDIo.VDIfIo.Core, "VD_IO", VDINTERFACETYPE_IO,
6243 pDisk, sizeof(VDINTERFACEIO), &pVDIfsImage);
6244 pImage->VDIo.pInterfaceIo = &pImage->VDIo.VDIfIo;
6245 }
6246
6247 /* Set up the internal I/O interface. */
6248 AssertBreakStmt(!VDIfIoIntGet(pVDIfsImage), rc = VERR_INVALID_PARAMETER);
6249 vdIfIoIntCallbacksSetup(&pImage->VDIo.VDIfIoInt);
6250 rc = VDInterfaceAdd(&pImage->VDIo.VDIfIoInt.Core, "VD_IOINT", VDINTERFACETYPE_IOINT,
6251 &pImage->VDIo, sizeof(VDINTERFACEIOINT), &pImage->pVDIfsImage);
6252 AssertRC(rc);
6253
6254 /* Create UUID if the caller didn't specify one. */
6255 if (!pUuid)
6256 {
6257 rc = RTUuidCreate(&uuid);
6258 if (RT_FAILURE(rc))
6259 {
6260 rc = vdError(pDisk, rc, RT_SRC_POS,
6261 N_("VD: cannot generate UUID for image '%s'"),
6262 pszFilename);
6263 break;
6264 }
6265 pUuid = &uuid;
6266 }
6267
6268 pImage->uOpenFlags = uOpenFlags & VD_OPEN_FLAGS_HONOR_SAME;
6269 pImage->VDIo.fIgnoreFlush = (uOpenFlags & VD_OPEN_FLAGS_IGNORE_FLUSH) != 0;
6270 uImageFlags |= VD_IMAGE_FLAGS_DIFF;
6271 rc = pImage->Backend->pfnCreate(pImage->pszFilename, pDisk->cbSize,
6272 uImageFlags | VD_IMAGE_FLAGS_DIFF,
6273 pszComment, &pDisk->PCHSGeometry,
6274 &pDisk->LCHSGeometry, pUuid,
6275 uOpenFlags & ~VD_OPEN_FLAGS_HONOR_SAME,
6276 0, 99,
6277 pDisk->pVDIfsDisk,
6278 pImage->pVDIfsImage,
6279 pVDIfsOperation,
6280 &pImage->pBackendData);
6281
6282 if (RT_SUCCESS(rc))
6283 {
6284 pImage->VDIo.pBackendData = pImage->pBackendData;
6285 pImage->uImageFlags = uImageFlags;
6286
6287 /* Lock disk for writing, as we modify pDisk information below. */
6288 rc2 = vdThreadStartWrite(pDisk);
6289 AssertRC(rc2);
6290 fLockWrite = true;
6291
6292 /* Switch previous image to read-only mode. */
6293 unsigned uOpenFlagsPrevImg;
6294 uOpenFlagsPrevImg = pDisk->pLast->Backend->pfnGetOpenFlags(pDisk->pLast->pBackendData);
6295 if (!(uOpenFlagsPrevImg & VD_OPEN_FLAGS_READONLY))
6296 {
6297 uOpenFlagsPrevImg |= VD_OPEN_FLAGS_READONLY;
6298 rc = pDisk->pLast->Backend->pfnSetOpenFlags(pDisk->pLast->pBackendData, uOpenFlagsPrevImg);
6299 }
6300
6301 /** @todo optionally check UUIDs */
6302
6303 /* Re-check state, as the lock wasn't held and another image
6304 * creation call could have been done by another thread. */
6305 AssertMsgStmt(pDisk->cImages != 0,
6306 ("Create diff image cannot be done without other images open\n"),
6307 rc = VERR_VD_INVALID_STATE);
6308 }
6309
6310 if (RT_SUCCESS(rc))
6311 {
6312 RTUUID Uuid;
6313 RTTIMESPEC ts;
6314
6315 if (pParentUuid && !RTUuidIsNull(pParentUuid))
6316 {
6317 Uuid = *pParentUuid;
6318 pImage->Backend->pfnSetParentUuid(pImage->pBackendData, &Uuid);
6319 }
6320 else
6321 {
6322 rc2 = pDisk->pLast->Backend->pfnGetUuid(pDisk->pLast->pBackendData,
6323 &Uuid);
6324 if (RT_SUCCESS(rc2))
6325 pImage->Backend->pfnSetParentUuid(pImage->pBackendData, &Uuid);
6326 }
6327 rc2 = pDisk->pLast->Backend->pfnGetModificationUuid(pDisk->pLast->pBackendData,
6328 &Uuid);
6329 if (RT_SUCCESS(rc2))
6330 pImage->Backend->pfnSetParentModificationUuid(pImage->pBackendData,
6331 &Uuid);
6332 if (pDisk->pLast->Backend->pfnGetTimeStamp)
6333 rc2 = pDisk->pLast->Backend->pfnGetTimeStamp(pDisk->pLast->pBackendData,
6334 &ts);
6335 else
6336 rc2 = VERR_NOT_IMPLEMENTED;
6337 if (RT_SUCCESS(rc2) && pImage->Backend->pfnSetParentTimeStamp)
6338 pImage->Backend->pfnSetParentTimeStamp(pImage->pBackendData, &ts);
6339
6340 if (pImage->Backend->pfnSetParentFilename)
6341 rc2 = pImage->Backend->pfnSetParentFilename(pImage->pBackendData, pDisk->pLast->pszFilename);
6342 }
6343
6344 if (RT_SUCCESS(rc))
6345 {
6346 /* Image successfully opened, make it the last image. */
6347 vdAddImageToList(pDisk, pImage);
6348 if (!(uOpenFlags & VD_OPEN_FLAGS_READONLY))
6349 pDisk->uModified = VD_IMAGE_MODIFIED_FIRST;
6350 }
6351 else
6352 {
6353 /* Error detected, but image opened. Close and delete image. */
6354 rc2 = pImage->Backend->pfnClose(pImage->pBackendData, true);
6355 AssertRC(rc2);
6356 pImage->pBackendData = NULL;
6357 }
6358 } while (0);
6359
6360 if (RT_UNLIKELY(fLockWrite))
6361 {
6362 rc2 = vdThreadFinishWrite(pDisk);
6363 AssertRC(rc2);
6364 }
6365 else if (RT_UNLIKELY(fLockRead))
6366 {
6367 rc2 = vdThreadFinishRead(pDisk);
6368 AssertRC(rc2);
6369 }
6370
6371 if (RT_FAILURE(rc))
6372 {
6373 if (pImage)
6374 {
6375 if (pImage->pszFilename)
6376 RTStrFree(pImage->pszFilename);
6377 RTMemFree(pImage);
6378 }
6379 }
6380
6381 if (RT_SUCCESS(rc) && pIfProgress && pIfProgress->pfnProgress)
6382 pIfProgress->pfnProgress(pIfProgress->Core.pvUser, 100);
6383
6384 LogFlowFunc(("returns %Rrc\n", rc));
6385 return rc;
6386}
6387
6388
6389/**
6390 * Creates and opens new cache image file in HDD container.
6391 *
6392 * @return VBox status code.
6393 * @param pDisk Name of the cache file backend to use (case insensitive).
6394 * @param pszFilename Name of the differencing cache file to create.
6395 * @param cbSize Maximum size of the cache.
6396 * @param uImageFlags Flags specifying special cache features.
6397 * @param pszComment Pointer to image comment. NULL is ok.
6398 * @param pUuid New UUID of the image. If NULL, a new UUID is created.
6399 * @param uOpenFlags Image file open mode, see VD_OPEN_FLAGS_* constants.
6400 * @param pVDIfsCache Pointer to the per-cache VD interface list.
6401 * @param pVDIfsOperation Pointer to the per-operation VD interface list.
6402 */
6403VBOXDDU_DECL(int) VDCreateCache(PVBOXHDD pDisk, const char *pszBackend,
6404 const char *pszFilename, uint64_t cbSize,
6405 unsigned uImageFlags, const char *pszComment,
6406 PCRTUUID pUuid, unsigned uOpenFlags,
6407 PVDINTERFACE pVDIfsCache, PVDINTERFACE pVDIfsOperation)
6408{
6409 int rc = VINF_SUCCESS;
6410 int rc2;
6411 bool fLockWrite = false, fLockRead = false;
6412 PVDCACHE pCache = NULL;
6413 RTUUID uuid;
6414
6415 LogFlowFunc(("pDisk=%#p pszBackend=\"%s\" pszFilename=\"%s\" cbSize=%llu uImageFlags=%#x pszComment=\"%s\" Uuid=%RTuuid uOpenFlags=%#x pVDIfsImage=%#p pVDIfsOperation=%#p\n",
6416 pDisk, pszBackend, pszFilename, cbSize, uImageFlags, pszComment, pUuid, uOpenFlags, pVDIfsCache, pVDIfsOperation));
6417
6418 PVDINTERFACEPROGRESS pIfProgress = VDIfProgressGet(pVDIfsOperation);
6419
6420 do
6421 {
6422 /* sanity check */
6423 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
6424 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
6425
6426 /* Check arguments. */
6427 AssertMsgBreakStmt(VALID_PTR(pszBackend) && *pszBackend,
6428 ("pszBackend=%#p \"%s\"\n", pszBackend, pszBackend),
6429 rc = VERR_INVALID_PARAMETER);
6430 AssertMsgBreakStmt(VALID_PTR(pszFilename) && *pszFilename,
6431 ("pszFilename=%#p \"%s\"\n", pszFilename, pszFilename),
6432 rc = VERR_INVALID_PARAMETER);
6433 AssertMsgBreakStmt(cbSize,
6434 ("cbSize=%llu\n", cbSize),
6435 rc = VERR_INVALID_PARAMETER);
6436 AssertMsgBreakStmt((uImageFlags & ~VD_IMAGE_FLAGS_MASK) == 0,
6437 ("uImageFlags=%#x\n", uImageFlags),
6438 rc = VERR_INVALID_PARAMETER);
6439 /* The UUID may be NULL. */
6440 AssertMsgBreakStmt(pUuid == NULL || VALID_PTR(pUuid),
6441 ("pUuid=%#p UUID=%RTuuid\n", pUuid, pUuid),
6442 rc = VERR_INVALID_PARAMETER);
6443 AssertMsgBreakStmt((uOpenFlags & ~VD_OPEN_FLAGS_MASK) == 0,
6444 ("uOpenFlags=%#x\n", uOpenFlags),
6445 rc = VERR_INVALID_PARAMETER);
6446
6447 /* Check state. Needs a temporary read lock. Holding the write lock
6448 * all the time would be blocking other activities for too long. */
6449 rc2 = vdThreadStartRead(pDisk);
6450 AssertRC(rc2);
6451 fLockRead = true;
6452 AssertMsgBreakStmt(!pDisk->pCache,
6453 ("Create cache image cannot be done with a cache already attached\n"),
6454 rc = VERR_VD_CACHE_ALREADY_EXISTS);
6455 rc2 = vdThreadFinishRead(pDisk);
6456 AssertRC(rc2);
6457 fLockRead = false;
6458
6459 /* Set up image descriptor. */
6460 pCache = (PVDCACHE)RTMemAllocZ(sizeof(VDCACHE));
6461 if (!pCache)
6462 {
6463 rc = VERR_NO_MEMORY;
6464 break;
6465 }
6466 pCache->pszFilename = RTStrDup(pszFilename);
6467 if (!pCache->pszFilename)
6468 {
6469 rc = VERR_NO_MEMORY;
6470 break;
6471 }
6472
6473 rc = vdFindCacheBackend(pszBackend, &pCache->Backend);
6474 if (RT_FAILURE(rc))
6475 break;
6476 if (!pCache->Backend)
6477 {
6478 rc = vdError(pDisk, VERR_INVALID_PARAMETER, RT_SRC_POS,
6479 N_("VD: unknown backend name '%s'"), pszBackend);
6480 break;
6481 }
6482
6483 pCache->VDIo.pDisk = pDisk;
6484 pCache->pVDIfsCache = pVDIfsCache;
6485
6486 /* Set up the I/O interface. */
6487 pCache->VDIo.pInterfaceIo = VDIfIoGet(pVDIfsCache);
6488 if (!pCache->VDIo.pInterfaceIo)
6489 {
6490 vdIfIoFallbackCallbacksSetup(&pCache->VDIo.VDIfIo);
6491 rc = VDInterfaceAdd(&pCache->VDIo.VDIfIo.Core, "VD_IO", VDINTERFACETYPE_IO,
6492 pDisk, sizeof(VDINTERFACEIO), &pVDIfsCache);
6493 pCache->VDIo.pInterfaceIo = &pCache->VDIo.VDIfIo;
6494 }
6495
6496 /* Set up the internal I/O interface. */
6497 AssertBreakStmt(!VDIfIoIntGet(pVDIfsCache), rc = VERR_INVALID_PARAMETER);
6498 vdIfIoIntCallbacksSetup(&pCache->VDIo.VDIfIoInt);
6499 rc = VDInterfaceAdd(&pCache->VDIo.VDIfIoInt.Core, "VD_IOINT", VDINTERFACETYPE_IOINT,
6500 &pCache->VDIo, sizeof(VDINTERFACEIOINT), &pCache->pVDIfsCache);
6501 AssertRC(rc);
6502
6503 /* Create UUID if the caller didn't specify one. */
6504 if (!pUuid)
6505 {
6506 rc = RTUuidCreate(&uuid);
6507 if (RT_FAILURE(rc))
6508 {
6509 rc = vdError(pDisk, rc, RT_SRC_POS,
6510 N_("VD: cannot generate UUID for image '%s'"),
6511 pszFilename);
6512 break;
6513 }
6514 pUuid = &uuid;
6515 }
6516
6517 pCache->uOpenFlags = uOpenFlags & VD_OPEN_FLAGS_HONOR_SAME;
6518 pCache->VDIo.fIgnoreFlush = (uOpenFlags & VD_OPEN_FLAGS_IGNORE_FLUSH) != 0;
6519 rc = pCache->Backend->pfnCreate(pCache->pszFilename, cbSize,
6520 uImageFlags,
6521 pszComment, pUuid,
6522 uOpenFlags & ~VD_OPEN_FLAGS_HONOR_SAME,
6523 0, 99,
6524 pDisk->pVDIfsDisk,
6525 pCache->pVDIfsCache,
6526 pVDIfsOperation,
6527 &pCache->pBackendData);
6528
6529 if (RT_SUCCESS(rc))
6530 {
6531 /* Lock disk for writing, as we modify pDisk information below. */
6532 rc2 = vdThreadStartWrite(pDisk);
6533 AssertRC(rc2);
6534 fLockWrite = true;
6535
6536 pCache->VDIo.pBackendData = pCache->pBackendData;
6537
6538 /* Re-check state, as the lock wasn't held and another image
6539 * creation call could have been done by another thread. */
6540 AssertMsgStmt(!pDisk->pCache,
6541 ("Create cache image cannot be done with another cache open\n"),
6542 rc = VERR_VD_CACHE_ALREADY_EXISTS);
6543 }
6544
6545 if ( RT_SUCCESS(rc)
6546 && pDisk->pLast)
6547 {
6548 RTUUID UuidModification;
6549
6550 /* Set same modification Uuid as the last image. */
6551 rc = pDisk->pLast->Backend->pfnGetModificationUuid(pDisk->pLast->pBackendData,
6552 &UuidModification);
6553 if (RT_SUCCESS(rc))
6554 {
6555 rc = pCache->Backend->pfnSetModificationUuid(pCache->pBackendData,
6556 &UuidModification);
6557 }
6558
6559 if (rc == VERR_NOT_SUPPORTED)
6560 rc = VINF_SUCCESS;
6561 }
6562
6563 if (RT_SUCCESS(rc))
6564 {
6565 /* Cache successfully created. */
6566 pDisk->pCache = pCache;
6567 }
6568 else
6569 {
6570 /* Error detected, but image opened. Close and delete image. */
6571 rc2 = pCache->Backend->pfnClose(pCache->pBackendData, true);
6572 AssertRC(rc2);
6573 pCache->pBackendData = NULL;
6574 }
6575 } while (0);
6576
6577 if (RT_UNLIKELY(fLockWrite))
6578 {
6579 rc2 = vdThreadFinishWrite(pDisk);
6580 AssertRC(rc2);
6581 }
6582 else if (RT_UNLIKELY(fLockRead))
6583 {
6584 rc2 = vdThreadFinishRead(pDisk);
6585 AssertRC(rc2);
6586 }
6587
6588 if (RT_FAILURE(rc))
6589 {
6590 if (pCache)
6591 {
6592 if (pCache->pszFilename)
6593 RTStrFree(pCache->pszFilename);
6594 RTMemFree(pCache);
6595 }
6596 }
6597
6598 if (RT_SUCCESS(rc) && pIfProgress && pIfProgress->pfnProgress)
6599 pIfProgress->pfnProgress(pIfProgress->Core.pvUser, 100);
6600
6601 LogFlowFunc(("returns %Rrc\n", rc));
6602 return rc;
6603}
6604
6605/**
6606 * Merges two images (not necessarily with direct parent/child relationship).
6607 * As a side effect the source image and potentially the other images which
6608 * are also merged to the destination are deleted from both the disk and the
6609 * images in the HDD container.
6610 *
6611 * @returns VBox status code.
6612 * @returns VERR_VD_IMAGE_NOT_FOUND if image with specified number was not opened.
6613 * @param pDisk Pointer to HDD container.
6614 * @param nImageFrom Name of the image file to merge from.
6615 * @param nImageTo Name of the image file to merge to.
6616 * @param pVDIfsOperation Pointer to the per-operation VD interface list.
6617 */
6618VBOXDDU_DECL(int) VDMerge(PVBOXHDD pDisk, unsigned nImageFrom,
6619 unsigned nImageTo, PVDINTERFACE pVDIfsOperation)
6620{
6621 int rc = VINF_SUCCESS;
6622 int rc2;
6623 bool fLockWrite = false, fLockRead = false;
6624 void *pvBuf = NULL;
6625
6626 LogFlowFunc(("pDisk=%#p nImageFrom=%u nImageTo=%u pVDIfsOperation=%#p\n",
6627 pDisk, nImageFrom, nImageTo, pVDIfsOperation));
6628
6629 PVDINTERFACEPROGRESS pIfProgress = VDIfProgressGet(pVDIfsOperation);
6630
6631 do
6632 {
6633 /* sanity check */
6634 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
6635 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
6636
6637 /* For simplicity reasons lock for writing as the image reopen below
6638 * might need it. After all the reopen is usually needed. */
6639 rc2 = vdThreadStartWrite(pDisk);
6640 AssertRC(rc2);
6641 fLockWrite = true;
6642 PVDIMAGE pImageFrom = vdGetImageByNumber(pDisk, nImageFrom);
6643 PVDIMAGE pImageTo = vdGetImageByNumber(pDisk, nImageTo);
6644 if (!pImageFrom || !pImageTo)
6645 {
6646 rc = VERR_VD_IMAGE_NOT_FOUND;
6647 break;
6648 }
6649 AssertBreakStmt(pImageFrom != pImageTo, rc = VERR_INVALID_PARAMETER);
6650
6651 /* Make sure destination image is writable. */
6652 unsigned uOpenFlags = pImageTo->Backend->pfnGetOpenFlags(pImageTo->pBackendData);
6653 if (uOpenFlags & VD_OPEN_FLAGS_READONLY)
6654 {
6655 /*
6656 * Clear skip consistency checks because the image is made writable now and
6657 * skipping consistency checks is only possible for readonly images.
6658 */
6659 uOpenFlags &= ~(VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_SKIP_CONSISTENCY_CHECKS);
6660 rc = pImageTo->Backend->pfnSetOpenFlags(pImageTo->pBackendData,
6661 uOpenFlags);
6662 if (RT_FAILURE(rc))
6663 break;
6664 }
6665
6666 /* Get size of destination image. */
6667 uint64_t cbSize = pImageTo->Backend->pfnGetSize(pImageTo->pBackendData);
6668 rc2 = vdThreadFinishWrite(pDisk);
6669 AssertRC(rc2);
6670 fLockWrite = false;
6671
6672 /* Allocate tmp buffer. */
6673 pvBuf = RTMemTmpAlloc(VD_MERGE_BUFFER_SIZE);
6674 if (!pvBuf)
6675 {
6676 rc = VERR_NO_MEMORY;
6677 break;
6678 }
6679
6680 /* Merging is done directly on the images itself. This potentially
6681 * causes trouble if the disk is full in the middle of operation. */
6682 if (nImageFrom < nImageTo)
6683 {
6684 /* Merge parent state into child. This means writing all not
6685 * allocated blocks in the destination image which are allocated in
6686 * the images to be merged. */
6687 uint64_t uOffset = 0;
6688 uint64_t cbRemaining = cbSize;
6689 do
6690 {
6691 size_t cbThisRead = RT_MIN(VD_MERGE_BUFFER_SIZE, cbRemaining);
6692
6693 /* Need to hold the write lock during a read-write operation. */
6694 rc2 = vdThreadStartWrite(pDisk);
6695 AssertRC(rc2);
6696 fLockWrite = true;
6697
6698 rc = pImageTo->Backend->pfnRead(pImageTo->pBackendData,
6699 uOffset, pvBuf, cbThisRead,
6700 &cbThisRead);
6701 if (rc == VERR_VD_BLOCK_FREE)
6702 {
6703 /* Search for image with allocated block. Do not attempt to
6704 * read more than the previous reads marked as valid.
6705 * Otherwise this would return stale data when different
6706 * block sizes are used for the images. */
6707 for (PVDIMAGE pCurrImage = pImageTo->pPrev;
6708 pCurrImage != NULL && pCurrImage != pImageFrom->pPrev && rc == VERR_VD_BLOCK_FREE;
6709 pCurrImage = pCurrImage->pPrev)
6710 {
6711 rc = pCurrImage->Backend->pfnRead(pCurrImage->pBackendData,
6712 uOffset, pvBuf,
6713 cbThisRead,
6714 &cbThisRead);
6715 }
6716
6717 if (rc != VERR_VD_BLOCK_FREE)
6718 {
6719 if (RT_FAILURE(rc))
6720 break;
6721 /* Updating the cache is required because this might be a live merge. */
6722 rc = vdWriteHelperEx(pDisk, pImageTo, pImageFrom->pPrev,
6723 uOffset, pvBuf, cbThisRead,
6724 true /* fUpdateCache */, 0);
6725 if (RT_FAILURE(rc))
6726 break;
6727 }
6728 else
6729 rc = VINF_SUCCESS;
6730 }
6731 else if (RT_FAILURE(rc))
6732 break;
6733
6734 rc2 = vdThreadFinishWrite(pDisk);
6735 AssertRC(rc2);
6736 fLockWrite = false;
6737
6738 uOffset += cbThisRead;
6739 cbRemaining -= cbThisRead;
6740
6741 if (pIfProgress && pIfProgress->pfnProgress)
6742 {
6743 /** @todo r=klaus: this can update the progress to the same
6744 * percentage over and over again if the image format makes
6745 * relatively small increments. */
6746 rc = pIfProgress->pfnProgress(pIfProgress->Core.pvUser,
6747 uOffset * 99 / cbSize);
6748 if (RT_FAILURE(rc))
6749 break;
6750 }
6751 } while (uOffset < cbSize);
6752 }
6753 else
6754 {
6755 /*
6756 * We may need to update the parent uuid of the child coming after
6757 * the last image to be merged. We have to reopen it read/write.
6758 *
6759 * This is done before we do the actual merge to prevent an
6760 * inconsistent chain if the mode change fails for some reason.
6761 */
6762 if (pImageFrom->pNext)
6763 {
6764 PVDIMAGE pImageChild = pImageFrom->pNext;
6765
6766 /* Take the write lock. */
6767 rc2 = vdThreadStartWrite(pDisk);
6768 AssertRC(rc2);
6769 fLockWrite = true;
6770
6771 /* We need to open the image in read/write mode. */
6772 uOpenFlags = pImageChild->Backend->pfnGetOpenFlags(pImageChild->pBackendData);
6773
6774 if (uOpenFlags & VD_OPEN_FLAGS_READONLY)
6775 {
6776 uOpenFlags &= ~VD_OPEN_FLAGS_READONLY;
6777 rc = pImageChild->Backend->pfnSetOpenFlags(pImageChild->pBackendData,
6778 uOpenFlags);
6779 if (RT_FAILURE(rc))
6780 break;
6781 }
6782
6783 rc2 = vdThreadFinishWrite(pDisk);
6784 AssertRC(rc2);
6785 fLockWrite = false;
6786 }
6787
6788 /* If the merge is from the last image we have to relay all writes
6789 * to the merge destination as well, so that concurrent writes
6790 * (in case of a live merge) are handled correctly. */
6791 if (!pImageFrom->pNext)
6792 {
6793 /* Take the write lock. */
6794 rc2 = vdThreadStartWrite(pDisk);
6795 AssertRC(rc2);
6796 fLockWrite = true;
6797
6798 pDisk->pImageRelay = pImageTo;
6799
6800 rc2 = vdThreadFinishWrite(pDisk);
6801 AssertRC(rc2);
6802 fLockWrite = false;
6803 }
6804
6805 /* Merge child state into parent. This means writing all blocks
6806 * which are allocated in the image up to the source image to the
6807 * destination image. */
6808 uint64_t uOffset = 0;
6809 uint64_t cbRemaining = cbSize;
6810 do
6811 {
6812 size_t cbThisRead = RT_MIN(VD_MERGE_BUFFER_SIZE, cbRemaining);
6813 rc = VERR_VD_BLOCK_FREE;
6814
6815 /* Need to hold the write lock during a read-write operation. */
6816 rc2 = vdThreadStartWrite(pDisk);
6817 AssertRC(rc2);
6818 fLockWrite = true;
6819
6820 /* Search for image with allocated block. Do not attempt to
6821 * read more than the previous reads marked as valid. Otherwise
6822 * this would return stale data when different block sizes are
6823 * used for the images. */
6824 for (PVDIMAGE pCurrImage = pImageFrom;
6825 pCurrImage != NULL && pCurrImage != pImageTo && rc == VERR_VD_BLOCK_FREE;
6826 pCurrImage = pCurrImage->pPrev)
6827 {
6828 rc = pCurrImage->Backend->pfnRead(pCurrImage->pBackendData,
6829 uOffset, pvBuf,
6830 cbThisRead, &cbThisRead);
6831 }
6832
6833 if (rc != VERR_VD_BLOCK_FREE)
6834 {
6835 if (RT_FAILURE(rc))
6836 break;
6837 rc = vdWriteHelper(pDisk, pImageTo, uOffset, pvBuf,
6838 cbThisRead, true /* fUpdateCache */);
6839 if (RT_FAILURE(rc))
6840 break;
6841 }
6842 else
6843 rc = VINF_SUCCESS;
6844
6845 rc2 = vdThreadFinishWrite(pDisk);
6846 AssertRC(rc2);
6847 fLockWrite = false;
6848
6849 uOffset += cbThisRead;
6850 cbRemaining -= cbThisRead;
6851
6852 if (pIfProgress && pIfProgress->pfnProgress)
6853 {
6854 /** @todo r=klaus: this can update the progress to the same
6855 * percentage over and over again if the image format makes
6856 * relatively small increments. */
6857 rc = pIfProgress->pfnProgress(pIfProgress->Core.pvUser,
6858 uOffset * 99 / cbSize);
6859 if (RT_FAILURE(rc))
6860 break;
6861 }
6862 } while (uOffset < cbSize);
6863
6864 /* In case we set up a "write proxy" image above we must clear
6865 * this again now to prevent stray writes. Failure or not. */
6866 if (!pImageFrom->pNext)
6867 {
6868 /* Take the write lock. */
6869 rc2 = vdThreadStartWrite(pDisk);
6870 AssertRC(rc2);
6871 fLockWrite = true;
6872
6873 pDisk->pImageRelay = NULL;
6874
6875 rc2 = vdThreadFinishWrite(pDisk);
6876 AssertRC(rc2);
6877 fLockWrite = false;
6878 }
6879 }
6880
6881 /*
6882 * Leave in case of an error to avoid corrupted data in the image chain
6883 * (includes cancelling the operation by the user).
6884 */
6885 if (RT_FAILURE(rc))
6886 break;
6887
6888 /* Need to hold the write lock while finishing the merge. */
6889 rc2 = vdThreadStartWrite(pDisk);
6890 AssertRC(rc2);
6891 fLockWrite = true;
6892
6893 /* Update parent UUID so that image chain is consistent.
6894 * The two attempts work around the problem that some backends
6895 * (e.g. iSCSI) do not support UUIDs, so we exploit the fact that
6896 * so far there can only be one such image in the chain. */
6897 /** @todo needs a better long-term solution, passing the UUID
6898 * knowledge from the caller or some such */
6899 RTUUID Uuid;
6900 PVDIMAGE pImageChild = NULL;
6901 if (nImageFrom < nImageTo)
6902 {
6903 if (pImageFrom->pPrev)
6904 {
6905 /* plan A: ask the parent itself for its UUID */
6906 rc = pImageFrom->pPrev->Backend->pfnGetUuid(pImageFrom->pPrev->pBackendData,
6907 &Uuid);
6908 if (RT_FAILURE(rc))
6909 {
6910 /* plan B: ask the child of the parent for parent UUID */
6911 rc = pImageFrom->Backend->pfnGetParentUuid(pImageFrom->pBackendData,
6912 &Uuid);
6913 }
6914 AssertRC(rc);
6915 }
6916 else
6917 RTUuidClear(&Uuid);
6918 rc = pImageTo->Backend->pfnSetParentUuid(pImageTo->pBackendData,
6919 &Uuid);
6920 AssertRC(rc);
6921 }
6922 else
6923 {
6924 /* Update the parent uuid of the child of the last merged image. */
6925 if (pImageFrom->pNext)
6926 {
6927 /* plan A: ask the parent itself for its UUID */
6928 rc = pImageTo->Backend->pfnGetUuid(pImageTo->pBackendData,
6929 &Uuid);
6930 if (RT_FAILURE(rc))
6931 {
6932 /* plan B: ask the child of the parent for parent UUID */
6933 rc = pImageTo->pNext->Backend->pfnGetParentUuid(pImageTo->pNext->pBackendData,
6934 &Uuid);
6935 }
6936 AssertRC(rc);
6937
6938 rc = pImageFrom->Backend->pfnSetParentUuid(pImageFrom->pNext->pBackendData,
6939 &Uuid);
6940 AssertRC(rc);
6941
6942 pImageChild = pImageFrom->pNext;
6943 }
6944 }
6945
6946 /* Delete the no longer needed images. */
6947 PVDIMAGE pImg = pImageFrom, pTmp;
6948 while (pImg != pImageTo)
6949 {
6950 if (nImageFrom < nImageTo)
6951 pTmp = pImg->pNext;
6952 else
6953 pTmp = pImg->pPrev;
6954 vdRemoveImageFromList(pDisk, pImg);
6955 pImg->Backend->pfnClose(pImg->pBackendData, true);
6956 RTMemFree(pImg->pszFilename);
6957 RTMemFree(pImg);
6958 pImg = pTmp;
6959 }
6960
6961 /* Make sure destination image is back to read only if necessary. */
6962 if (pImageTo != pDisk->pLast)
6963 {
6964 uOpenFlags = pImageTo->Backend->pfnGetOpenFlags(pImageTo->pBackendData);
6965 uOpenFlags |= VD_OPEN_FLAGS_READONLY;
6966 rc = pImageTo->Backend->pfnSetOpenFlags(pImageTo->pBackendData,
6967 uOpenFlags);
6968 if (RT_FAILURE(rc))
6969 break;
6970 }
6971
6972 /*
6973 * Make sure the child is readonly
6974 * for the child -> parent merge direction
6975 * if necessary.
6976 */
6977 if ( nImageFrom > nImageTo
6978 && pImageChild
6979 && pImageChild != pDisk->pLast)
6980 {
6981 uOpenFlags = pImageChild->Backend->pfnGetOpenFlags(pImageChild->pBackendData);
6982 uOpenFlags |= VD_OPEN_FLAGS_READONLY;
6983 rc = pImageChild->Backend->pfnSetOpenFlags(pImageChild->pBackendData,
6984 uOpenFlags);
6985 if (RT_FAILURE(rc))
6986 break;
6987 }
6988 } while (0);
6989
6990 if (RT_UNLIKELY(fLockWrite))
6991 {
6992 rc2 = vdThreadFinishWrite(pDisk);
6993 AssertRC(rc2);
6994 }
6995 else if (RT_UNLIKELY(fLockRead))
6996 {
6997 rc2 = vdThreadFinishRead(pDisk);
6998 AssertRC(rc2);
6999 }
7000
7001 if (pvBuf)
7002 RTMemTmpFree(pvBuf);
7003
7004 if (RT_SUCCESS(rc) && pIfProgress && pIfProgress->pfnProgress)
7005 pIfProgress->pfnProgress(pIfProgress->Core.pvUser, 100);
7006
7007 LogFlowFunc(("returns %Rrc\n", rc));
7008 return rc;
7009}
7010
7011/**
7012 * Copies an image from one HDD container to another - extended version.
7013 * The copy is opened in the target HDD container.
7014 * It is possible to convert between different image formats, because the
7015 * backend for the destination may be different from the source.
7016 * If both the source and destination reference the same HDD container,
7017 * then the image is moved (by copying/deleting or renaming) to the new location.
7018 * The source container is unchanged if the move operation fails, otherwise
7019 * the image at the new location is opened in the same way as the old one was.
7020 *
7021 * @note The read/write accesses across disks are not synchronized, just the
7022 * accesses to each disk. Once there is a use case which requires a defined
7023 * read/write behavior in this situation this needs to be extended.
7024 *
7025 * @return VBox status code.
7026 * @return VERR_VD_IMAGE_NOT_FOUND if image with specified number was not opened.
7027 * @param pDiskFrom Pointer to source HDD container.
7028 * @param nImage Image number, counts from 0. 0 is always base image of container.
7029 * @param pDiskTo Pointer to destination HDD container.
7030 * @param pszBackend Name of the image file backend to use (may be NULL to use the same as the source, case insensitive).
7031 * @param pszFilename New name of the image (may be NULL to specify that the
7032 * copy destination is the destination container, or
7033 * if pDiskFrom == pDiskTo, i.e. when moving).
7034 * @param fMoveByRename If true, attempt to perform a move by renaming (if successful the new size is ignored).
7035 * @param cbSize New image size (0 means leave unchanged).
7036 * @param nImageSameFrom todo
7037 * @param nImageSameTo todo
7038 * @param uImageFlags Flags specifying special destination image features.
7039 * @param pDstUuid New UUID of the destination image. If NULL, a new UUID is created.
7040 * This parameter is used if and only if a true copy is created.
7041 * In all rename/move cases or copy to existing image cases the modification UUIDs are copied over.
7042 * @param uOpenFlags Image file open mode, see VD_OPEN_FLAGS_* constants.
7043 * Only used if the destination image is created.
7044 * @param pVDIfsOperation Pointer to the per-operation VD interface list.
7045 * @param pDstVDIfsImage Pointer to the per-image VD interface list, for the
7046 * destination image.
7047 * @param pDstVDIfsOperation Pointer to the per-operation VD interface list,
7048 * for the destination operation.
7049 */
7050VBOXDDU_DECL(int) VDCopyEx(PVBOXHDD pDiskFrom, unsigned nImage, PVBOXHDD pDiskTo,
7051 const char *pszBackend, const char *pszFilename,
7052 bool fMoveByRename, uint64_t cbSize,
7053 unsigned nImageFromSame, unsigned nImageToSame,
7054 unsigned uImageFlags, PCRTUUID pDstUuid,
7055 unsigned uOpenFlags, PVDINTERFACE pVDIfsOperation,
7056 PVDINTERFACE pDstVDIfsImage,
7057 PVDINTERFACE pDstVDIfsOperation)
7058{
7059 int rc = VINF_SUCCESS;
7060 int rc2;
7061 bool fLockReadFrom = false, fLockWriteFrom = false, fLockWriteTo = false;
7062 PVDIMAGE pImageTo = NULL;
7063
7064 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",
7065 pDiskFrom, nImage, pDiskTo, pszBackend, pszFilename, fMoveByRename, cbSize, nImageFromSame, nImageToSame, uImageFlags, pDstUuid, uOpenFlags, pVDIfsOperation, pDstVDIfsImage, pDstVDIfsOperation));
7066
7067 PVDINTERFACEPROGRESS pIfProgress = VDIfProgressGet(pVDIfsOperation);
7068 PVDINTERFACEPROGRESS pDstIfProgress = VDIfProgressGet(pDstVDIfsOperation);
7069
7070 do {
7071 /* Check arguments. */
7072 AssertMsgBreakStmt(VALID_PTR(pDiskFrom), ("pDiskFrom=%#p\n", pDiskFrom),
7073 rc = VERR_INVALID_PARAMETER);
7074 AssertMsg(pDiskFrom->u32Signature == VBOXHDDDISK_SIGNATURE,
7075 ("u32Signature=%08x\n", pDiskFrom->u32Signature));
7076
7077 rc2 = vdThreadStartRead(pDiskFrom);
7078 AssertRC(rc2);
7079 fLockReadFrom = true;
7080 PVDIMAGE pImageFrom = vdGetImageByNumber(pDiskFrom, nImage);
7081 AssertPtrBreakStmt(pImageFrom, rc = VERR_VD_IMAGE_NOT_FOUND);
7082 AssertMsgBreakStmt(VALID_PTR(pDiskTo), ("pDiskTo=%#p\n", pDiskTo),
7083 rc = VERR_INVALID_PARAMETER);
7084 AssertMsg(pDiskTo->u32Signature == VBOXHDDDISK_SIGNATURE,
7085 ("u32Signature=%08x\n", pDiskTo->u32Signature));
7086 AssertMsgBreakStmt( (nImageFromSame < nImage || nImageFromSame == VD_IMAGE_CONTENT_UNKNOWN)
7087 && (nImageToSame < pDiskTo->cImages || nImageToSame == VD_IMAGE_CONTENT_UNKNOWN)
7088 && ( (nImageFromSame == VD_IMAGE_CONTENT_UNKNOWN && nImageToSame == VD_IMAGE_CONTENT_UNKNOWN)
7089 || (nImageFromSame != VD_IMAGE_CONTENT_UNKNOWN && nImageToSame != VD_IMAGE_CONTENT_UNKNOWN)),
7090 ("nImageFromSame=%u nImageToSame=%u\n", nImageFromSame, nImageToSame),
7091 rc = VERR_INVALID_PARAMETER);
7092
7093 /* Move the image. */
7094 if (pDiskFrom == pDiskTo)
7095 {
7096 /* Rename only works when backends are the same, are file based
7097 * and the rename method is implemented. */
7098 if ( fMoveByRename
7099 && !RTStrICmp(pszBackend, pImageFrom->Backend->pszBackendName)
7100 && pImageFrom->Backend->uBackendCaps & VD_CAP_FILE
7101 && pImageFrom->Backend->pfnRename)
7102 {
7103 rc2 = vdThreadFinishRead(pDiskFrom);
7104 AssertRC(rc2);
7105 fLockReadFrom = false;
7106
7107 rc2 = vdThreadStartWrite(pDiskFrom);
7108 AssertRC(rc2);
7109 fLockWriteFrom = true;
7110 rc = pImageFrom->Backend->pfnRename(pImageFrom->pBackendData, pszFilename ? pszFilename : pImageFrom->pszFilename);
7111 break;
7112 }
7113
7114 /** @todo Moving (including shrinking/growing) of the image is
7115 * requested, but the rename attempt failed or it wasn't possible.
7116 * Must now copy image to temp location. */
7117 AssertReleaseMsgFailed(("VDCopy: moving by copy/delete not implemented\n"));
7118 }
7119
7120 /* pszFilename is allowed to be NULL, as this indicates copy to the existing image. */
7121 AssertMsgBreakStmt(pszFilename == NULL || (VALID_PTR(pszFilename) && *pszFilename),
7122 ("pszFilename=%#p \"%s\"\n", pszFilename, pszFilename),
7123 rc = VERR_INVALID_PARAMETER);
7124
7125 uint64_t cbSizeFrom;
7126 cbSizeFrom = pImageFrom->Backend->pfnGetSize(pImageFrom->pBackendData);
7127 if (cbSizeFrom == 0)
7128 {
7129 rc = VERR_VD_VALUE_NOT_FOUND;
7130 break;
7131 }
7132
7133 VDGEOMETRY PCHSGeometryFrom = {0, 0, 0};
7134 VDGEOMETRY LCHSGeometryFrom = {0, 0, 0};
7135 pImageFrom->Backend->pfnGetPCHSGeometry(pImageFrom->pBackendData, &PCHSGeometryFrom);
7136 pImageFrom->Backend->pfnGetLCHSGeometry(pImageFrom->pBackendData, &LCHSGeometryFrom);
7137
7138 RTUUID ImageUuid, ImageModificationUuid;
7139 if (pDiskFrom != pDiskTo)
7140 {
7141 if (pDstUuid)
7142 ImageUuid = *pDstUuid;
7143 else
7144 RTUuidCreate(&ImageUuid);
7145 }
7146 else
7147 {
7148 rc = pImageFrom->Backend->pfnGetUuid(pImageFrom->pBackendData, &ImageUuid);
7149 if (RT_FAILURE(rc))
7150 RTUuidCreate(&ImageUuid);
7151 }
7152 rc = pImageFrom->Backend->pfnGetModificationUuid(pImageFrom->pBackendData, &ImageModificationUuid);
7153 if (RT_FAILURE(rc))
7154 RTUuidClear(&ImageModificationUuid);
7155
7156 char szComment[1024];
7157 rc = pImageFrom->Backend->pfnGetComment(pImageFrom->pBackendData, szComment, sizeof(szComment));
7158 if (RT_FAILURE(rc))
7159 szComment[0] = '\0';
7160 else
7161 szComment[sizeof(szComment) - 1] = '\0';
7162
7163 rc2 = vdThreadFinishRead(pDiskFrom);
7164 AssertRC(rc2);
7165 fLockReadFrom = false;
7166
7167 rc2 = vdThreadStartRead(pDiskTo);
7168 AssertRC(rc2);
7169 unsigned cImagesTo = pDiskTo->cImages;
7170 rc2 = vdThreadFinishRead(pDiskTo);
7171 AssertRC(rc2);
7172
7173 if (pszFilename)
7174 {
7175 if (cbSize == 0)
7176 cbSize = cbSizeFrom;
7177
7178 /* Create destination image with the properties of source image. */
7179 /** @todo replace the VDCreateDiff/VDCreateBase calls by direct
7180 * calls to the backend. Unifies the code and reduces the API
7181 * dependencies. Would also make the synchronization explicit. */
7182 if (cImagesTo > 0)
7183 {
7184 rc = VDCreateDiff(pDiskTo, pszBackend, pszFilename,
7185 uImageFlags, szComment, &ImageUuid,
7186 NULL /* pParentUuid */,
7187 uOpenFlags & ~VD_OPEN_FLAGS_READONLY,
7188 pDstVDIfsImage, NULL);
7189
7190 rc2 = vdThreadStartWrite(pDiskTo);
7191 AssertRC(rc2);
7192 fLockWriteTo = true;
7193 } else {
7194 /** @todo hack to force creation of a fixed image for
7195 * the RAW backend, which can't handle anything else. */
7196 if (!RTStrICmp(pszBackend, "RAW"))
7197 uImageFlags |= VD_IMAGE_FLAGS_FIXED;
7198
7199 vdFixupPCHSGeometry(&PCHSGeometryFrom, cbSize);
7200 vdFixupLCHSGeometry(&LCHSGeometryFrom, cbSize);
7201
7202 rc = VDCreateBase(pDiskTo, pszBackend, pszFilename, cbSize,
7203 uImageFlags, szComment,
7204 &PCHSGeometryFrom, &LCHSGeometryFrom,
7205 NULL, uOpenFlags & ~VD_OPEN_FLAGS_READONLY,
7206 pDstVDIfsImage, NULL);
7207
7208 rc2 = vdThreadStartWrite(pDiskTo);
7209 AssertRC(rc2);
7210 fLockWriteTo = true;
7211
7212 if (RT_SUCCESS(rc) && !RTUuidIsNull(&ImageUuid))
7213 pDiskTo->pLast->Backend->pfnSetUuid(pDiskTo->pLast->pBackendData, &ImageUuid);
7214 }
7215 if (RT_FAILURE(rc))
7216 break;
7217
7218 pImageTo = pDiskTo->pLast;
7219 AssertPtrBreakStmt(pImageTo, rc = VERR_VD_IMAGE_NOT_FOUND);
7220
7221 cbSize = RT_MIN(cbSize, cbSizeFrom);
7222 }
7223 else
7224 {
7225 pImageTo = pDiskTo->pLast;
7226 AssertPtrBreakStmt(pImageTo, rc = VERR_VD_IMAGE_NOT_FOUND);
7227
7228 uint64_t cbSizeTo;
7229 cbSizeTo = pImageTo->Backend->pfnGetSize(pImageTo->pBackendData);
7230 if (cbSizeTo == 0)
7231 {
7232 rc = VERR_VD_VALUE_NOT_FOUND;
7233 break;
7234 }
7235
7236 if (cbSize == 0)
7237 cbSize = RT_MIN(cbSizeFrom, cbSizeTo);
7238
7239 vdFixupPCHSGeometry(&PCHSGeometryFrom, cbSize);
7240 vdFixupLCHSGeometry(&LCHSGeometryFrom, cbSize);
7241
7242 /* Update the geometry in the destination image. */
7243 pImageTo->Backend->pfnSetPCHSGeometry(pImageTo->pBackendData, &PCHSGeometryFrom);
7244 pImageTo->Backend->pfnSetLCHSGeometry(pImageTo->pBackendData, &LCHSGeometryFrom);
7245 }
7246
7247 rc2 = vdThreadFinishWrite(pDiskTo);
7248 AssertRC(rc2);
7249 fLockWriteTo = false;
7250
7251 /* Whether we can take the optimized copy path (false) or not.
7252 * Don't optimize if the image existed or if it is a child image. */
7253 bool fSuppressRedundantIo = ( !(pszFilename == NULL || cImagesTo > 0)
7254 || (nImageToSame != VD_IMAGE_CONTENT_UNKNOWN));
7255 unsigned cImagesFromReadBack, cImagesToReadBack;
7256
7257 if (nImageFromSame == VD_IMAGE_CONTENT_UNKNOWN)
7258 cImagesFromReadBack = 0;
7259 else
7260 {
7261 if (nImage == VD_LAST_IMAGE)
7262 cImagesFromReadBack = pDiskFrom->cImages - nImageFromSame - 1;
7263 else
7264 cImagesFromReadBack = nImage - nImageFromSame;
7265 }
7266
7267 if (nImageToSame == VD_IMAGE_CONTENT_UNKNOWN)
7268 cImagesToReadBack = 0;
7269 else
7270 cImagesToReadBack = pDiskTo->cImages - nImageToSame - 1;
7271
7272 /* Copy the data. */
7273 rc = vdCopyHelper(pDiskFrom, pImageFrom, pDiskTo, cbSize,
7274 cImagesFromReadBack, cImagesToReadBack,
7275 fSuppressRedundantIo, pIfProgress, pDstIfProgress);
7276
7277 if (RT_SUCCESS(rc))
7278 {
7279 rc2 = vdThreadStartWrite(pDiskTo);
7280 AssertRC(rc2);
7281 fLockWriteTo = true;
7282
7283 /* Only set modification UUID if it is non-null, since the source
7284 * backend might not provide a valid modification UUID. */
7285 if (!RTUuidIsNull(&ImageModificationUuid))
7286 pImageTo->Backend->pfnSetModificationUuid(pImageTo->pBackendData, &ImageModificationUuid);
7287
7288 /* Set the requested open flags if they differ from the value
7289 * required for creating the image and copying the contents. */
7290 if ( pImageTo && pszFilename
7291 && uOpenFlags != (uOpenFlags & ~VD_OPEN_FLAGS_READONLY))
7292 rc = pImageTo->Backend->pfnSetOpenFlags(pImageTo->pBackendData,
7293 uOpenFlags);
7294 }
7295 } while (0);
7296
7297 if (RT_FAILURE(rc) && pImageTo && pszFilename)
7298 {
7299 /* Take the write lock only if it is not taken. Not worth making the
7300 * above code even more complicated. */
7301 if (RT_UNLIKELY(!fLockWriteTo))
7302 {
7303 rc2 = vdThreadStartWrite(pDiskTo);
7304 AssertRC(rc2);
7305 fLockWriteTo = true;
7306 }
7307 /* Error detected, but new image created. Remove image from list. */
7308 vdRemoveImageFromList(pDiskTo, pImageTo);
7309
7310 /* Close and delete image. */
7311 rc2 = pImageTo->Backend->pfnClose(pImageTo->pBackendData, true);
7312 AssertRC(rc2);
7313 pImageTo->pBackendData = NULL;
7314
7315 /* Free remaining resources. */
7316 if (pImageTo->pszFilename)
7317 RTStrFree(pImageTo->pszFilename);
7318
7319 RTMemFree(pImageTo);
7320 }
7321
7322 if (RT_UNLIKELY(fLockWriteTo))
7323 {
7324 rc2 = vdThreadFinishWrite(pDiskTo);
7325 AssertRC(rc2);
7326 }
7327 if (RT_UNLIKELY(fLockWriteFrom))
7328 {
7329 rc2 = vdThreadFinishWrite(pDiskFrom);
7330 AssertRC(rc2);
7331 }
7332 else if (RT_UNLIKELY(fLockReadFrom))
7333 {
7334 rc2 = vdThreadFinishRead(pDiskFrom);
7335 AssertRC(rc2);
7336 }
7337
7338 if (RT_SUCCESS(rc))
7339 {
7340 if (pIfProgress && pIfProgress->pfnProgress)
7341 pIfProgress->pfnProgress(pIfProgress->Core.pvUser, 100);
7342 if (pDstIfProgress && pDstIfProgress->pfnProgress)
7343 pDstIfProgress->pfnProgress(pDstIfProgress->Core.pvUser, 100);
7344 }
7345
7346 LogFlowFunc(("returns %Rrc\n", rc));
7347 return rc;
7348}
7349
7350/**
7351 * Copies an image from one HDD container to another.
7352 * The copy is opened in the target HDD container.
7353 * It is possible to convert between different image formats, because the
7354 * backend for the destination may be different from the source.
7355 * If both the source and destination reference the same HDD container,
7356 * then the image is moved (by copying/deleting or renaming) to the new location.
7357 * The source container is unchanged if the move operation fails, otherwise
7358 * the image at the new location is opened in the same way as the old one was.
7359 *
7360 * @returns VBox status code.
7361 * @returns VERR_VD_IMAGE_NOT_FOUND if image with specified number was not opened.
7362 * @param pDiskFrom Pointer to source HDD container.
7363 * @param nImage Image number, counts from 0. 0 is always base image of container.
7364 * @param pDiskTo Pointer to destination HDD container.
7365 * @param pszBackend Name of the image file backend to use.
7366 * @param pszFilename New name of the image (may be NULL if pDiskFrom == pDiskTo).
7367 * @param fMoveByRename If true, attempt to perform a move by renaming (if successful the new size is ignored).
7368 * @param cbSize New image size (0 means leave unchanged).
7369 * @param uImageFlags Flags specifying special destination image features.
7370 * @param pDstUuid New UUID of the destination image. If NULL, a new UUID is created.
7371 * This parameter is used if and only if a true copy is created.
7372 * In all rename/move cases the UUIDs are copied over.
7373 * @param uOpenFlags Image file open mode, see VD_OPEN_FLAGS_* constants.
7374 * Only used if the destination image is created.
7375 * @param pVDIfsOperation Pointer to the per-operation VD interface list.
7376 * @param pDstVDIfsImage Pointer to the per-image VD interface list, for the
7377 * destination image.
7378 * @param pDstVDIfsOperation Pointer to the per-image VD interface list,
7379 * for the destination image.
7380 */
7381VBOXDDU_DECL(int) VDCopy(PVBOXHDD pDiskFrom, unsigned nImage, PVBOXHDD pDiskTo,
7382 const char *pszBackend, const char *pszFilename,
7383 bool fMoveByRename, uint64_t cbSize,
7384 unsigned uImageFlags, PCRTUUID pDstUuid,
7385 unsigned uOpenFlags, PVDINTERFACE pVDIfsOperation,
7386 PVDINTERFACE pDstVDIfsImage,
7387 PVDINTERFACE pDstVDIfsOperation)
7388{
7389 return VDCopyEx(pDiskFrom, nImage, pDiskTo, pszBackend, pszFilename, fMoveByRename,
7390 cbSize, VD_IMAGE_CONTENT_UNKNOWN, VD_IMAGE_CONTENT_UNKNOWN,
7391 uImageFlags, pDstUuid, uOpenFlags, pVDIfsOperation,
7392 pDstVDIfsImage, pDstVDIfsOperation);
7393}
7394
7395/**
7396 * Optimizes the storage consumption of an image. Typically the unused blocks
7397 * have to be wiped with zeroes to achieve a substantial reduced storage use.
7398 * Another optimization done is reordering the image blocks, which can provide
7399 * a significant performance boost, as reads and writes tend to use less random
7400 * file offsets.
7401 *
7402 * @return VBox status code.
7403 * @return VERR_VD_IMAGE_NOT_FOUND if image with specified number was not opened.
7404 * @return VERR_VD_IMAGE_READ_ONLY if image is not writable.
7405 * @return VERR_NOT_SUPPORTED if this kind of image can be compacted, but
7406 * the code for this isn't implemented yet.
7407 * @param pDisk Pointer to HDD container.
7408 * @param nImage Image number, counts from 0. 0 is always base image of container.
7409 * @param pVDIfsOperation Pointer to the per-operation VD interface list.
7410 */
7411VBOXDDU_DECL(int) VDCompact(PVBOXHDD pDisk, unsigned nImage,
7412 PVDINTERFACE pVDIfsOperation)
7413{
7414 int rc = VINF_SUCCESS;
7415 int rc2;
7416 bool fLockRead = false, fLockWrite = false;
7417 void *pvBuf = NULL;
7418 void *pvTmp = NULL;
7419
7420 LogFlowFunc(("pDisk=%#p nImage=%u pVDIfsOperation=%#p\n",
7421 pDisk, nImage, pVDIfsOperation));
7422
7423 PVDINTERFACEPROGRESS pIfProgress = VDIfProgressGet(pVDIfsOperation);
7424
7425 do {
7426 /* Check arguments. */
7427 AssertMsgBreakStmt(VALID_PTR(pDisk), ("pDisk=%#p\n", pDisk),
7428 rc = VERR_INVALID_PARAMETER);
7429 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE,
7430 ("u32Signature=%08x\n", pDisk->u32Signature));
7431
7432 rc2 = vdThreadStartRead(pDisk);
7433 AssertRC(rc2);
7434 fLockRead = true;
7435
7436 PVDIMAGE pImage = vdGetImageByNumber(pDisk, nImage);
7437 AssertPtrBreakStmt(pImage, rc = VERR_VD_IMAGE_NOT_FOUND);
7438
7439 /* If there is no compact callback for not file based backends then
7440 * the backend doesn't need compaction. No need to make much fuss about
7441 * this. For file based ones signal this as not yet supported. */
7442 if (!pImage->Backend->pfnCompact)
7443 {
7444 if (pImage->Backend->uBackendCaps & VD_CAP_FILE)
7445 rc = VERR_NOT_SUPPORTED;
7446 else
7447 rc = VINF_SUCCESS;
7448 break;
7449 }
7450
7451 /* Insert interface for reading parent state into per-operation list,
7452 * if there is a parent image. */
7453 VDINTERFACEPARENTSTATE VDIfParent;
7454 VDPARENTSTATEDESC ParentUser;
7455 if (pImage->pPrev)
7456 {
7457 VDIfParent.pfnParentRead = vdParentRead;
7458 ParentUser.pDisk = pDisk;
7459 ParentUser.pImage = pImage->pPrev;
7460 rc = VDInterfaceAdd(&VDIfParent.Core, "VDCompact_ParentState", VDINTERFACETYPE_PARENTSTATE,
7461 &ParentUser, sizeof(VDINTERFACEPARENTSTATE), &pVDIfsOperation);
7462 AssertRC(rc);
7463 }
7464
7465 rc2 = vdThreadFinishRead(pDisk);
7466 AssertRC(rc2);
7467 fLockRead = false;
7468
7469 rc2 = vdThreadStartWrite(pDisk);
7470 AssertRC(rc2);
7471 fLockWrite = true;
7472
7473 rc = pImage->Backend->pfnCompact(pImage->pBackendData,
7474 0, 99,
7475 pDisk->pVDIfsDisk,
7476 pImage->pVDIfsImage,
7477 pVDIfsOperation);
7478 } while (0);
7479
7480 if (RT_UNLIKELY(fLockWrite))
7481 {
7482 rc2 = vdThreadFinishWrite(pDisk);
7483 AssertRC(rc2);
7484 }
7485 else if (RT_UNLIKELY(fLockRead))
7486 {
7487 rc2 = vdThreadFinishRead(pDisk);
7488 AssertRC(rc2);
7489 }
7490
7491 if (pvBuf)
7492 RTMemTmpFree(pvBuf);
7493 if (pvTmp)
7494 RTMemTmpFree(pvTmp);
7495
7496 if (RT_SUCCESS(rc))
7497 {
7498 if (pIfProgress && pIfProgress->pfnProgress)
7499 pIfProgress->pfnProgress(pIfProgress->Core.pvUser, 100);
7500 }
7501
7502 LogFlowFunc(("returns %Rrc\n", rc));
7503 return rc;
7504}
7505
7506/**
7507 * Resizes the given disk image to the given size.
7508 *
7509 * @return VBox status
7510 * @return VERR_VD_IMAGE_READ_ONLY if image is not writable.
7511 * @return VERR_NOT_SUPPORTED if this kind of image can be compacted, but
7512 *
7513 * @param pDisk Pointer to the HDD container.
7514 * @param cbSize New size of the image.
7515 * @param pPCHSGeometry Pointer to the new physical disk geometry <= (16383,16,63). Not NULL.
7516 * @param pLCHSGeometry Pointer to the new logical disk geometry <= (x,255,63). Not NULL.
7517 * @param pVDIfsOperation Pointer to the per-operation VD interface list.
7518 */
7519VBOXDDU_DECL(int) VDResize(PVBOXHDD pDisk, uint64_t cbSize,
7520 PCVDGEOMETRY pPCHSGeometry,
7521 PCVDGEOMETRY pLCHSGeometry,
7522 PVDINTERFACE pVDIfsOperation)
7523{
7524 /** @todo r=klaus resizing was designed to be part of VDCopy, so having a separate function is not desirable. */
7525 int rc = VINF_SUCCESS;
7526 int rc2;
7527 bool fLockRead = false, fLockWrite = false;
7528
7529 LogFlowFunc(("pDisk=%#p cbSize=%llu pVDIfsOperation=%#p\n",
7530 pDisk, cbSize, pVDIfsOperation));
7531
7532 PVDINTERFACEPROGRESS pIfProgress = VDIfProgressGet(pVDIfsOperation);
7533
7534 do {
7535 /* Check arguments. */
7536 AssertMsgBreakStmt(VALID_PTR(pDisk), ("pDisk=%#p\n", pDisk),
7537 rc = VERR_INVALID_PARAMETER);
7538 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE,
7539 ("u32Signature=%08x\n", pDisk->u32Signature));
7540
7541 rc2 = vdThreadStartRead(pDisk);
7542 AssertRC(rc2);
7543 fLockRead = true;
7544
7545 /* Not supported if the disk has child images attached. */
7546 AssertMsgBreakStmt(pDisk->cImages == 1, ("cImages=%u\n", pDisk->cImages),
7547 rc = VERR_NOT_SUPPORTED);
7548
7549 PVDIMAGE pImage = pDisk->pBase;
7550
7551 /* If there is no compact callback for not file based backends then
7552 * the backend doesn't need compaction. No need to make much fuss about
7553 * this. For file based ones signal this as not yet supported. */
7554 if (!pImage->Backend->pfnResize)
7555 {
7556 if (pImage->Backend->uBackendCaps & VD_CAP_FILE)
7557 rc = VERR_NOT_SUPPORTED;
7558 else
7559 rc = VINF_SUCCESS;
7560 break;
7561 }
7562
7563 rc2 = vdThreadFinishRead(pDisk);
7564 AssertRC(rc2);
7565 fLockRead = false;
7566
7567 rc2 = vdThreadStartWrite(pDisk);
7568 AssertRC(rc2);
7569 fLockWrite = true;
7570
7571 VDGEOMETRY PCHSGeometryOld;
7572 VDGEOMETRY LCHSGeometryOld;
7573 PCVDGEOMETRY pPCHSGeometryNew;
7574 PCVDGEOMETRY pLCHSGeometryNew;
7575
7576 if (pPCHSGeometry->cCylinders == 0)
7577 {
7578 /* Auto-detect marker, calculate new value ourself. */
7579 rc = pImage->Backend->pfnGetPCHSGeometry(pImage->pBackendData, &PCHSGeometryOld);
7580 if (RT_SUCCESS(rc) && (PCHSGeometryOld.cCylinders != 0))
7581 PCHSGeometryOld.cCylinders = RT_MIN(cbSize / 512 / PCHSGeometryOld.cHeads / PCHSGeometryOld.cSectors, 16383);
7582 else if (rc == VERR_VD_GEOMETRY_NOT_SET)
7583 rc = VINF_SUCCESS;
7584
7585 pPCHSGeometryNew = &PCHSGeometryOld;
7586 }
7587 else
7588 pPCHSGeometryNew = pPCHSGeometry;
7589
7590 if (pLCHSGeometry->cCylinders == 0)
7591 {
7592 /* Auto-detect marker, calculate new value ourself. */
7593 rc = pImage->Backend->pfnGetLCHSGeometry(pImage->pBackendData, &LCHSGeometryOld);
7594 if (RT_SUCCESS(rc) && (LCHSGeometryOld.cCylinders != 0))
7595 LCHSGeometryOld.cCylinders = cbSize / 512 / LCHSGeometryOld.cHeads / LCHSGeometryOld.cSectors;
7596 else if (rc == VERR_VD_GEOMETRY_NOT_SET)
7597 rc = VINF_SUCCESS;
7598
7599 pLCHSGeometryNew = &LCHSGeometryOld;
7600 }
7601 else
7602 pLCHSGeometryNew = pLCHSGeometry;
7603
7604 if (RT_SUCCESS(rc))
7605 rc = pImage->Backend->pfnResize(pImage->pBackendData,
7606 cbSize,
7607 pPCHSGeometryNew,
7608 pLCHSGeometryNew,
7609 0, 99,
7610 pDisk->pVDIfsDisk,
7611 pImage->pVDIfsImage,
7612 pVDIfsOperation);
7613 } while (0);
7614
7615 if (RT_UNLIKELY(fLockWrite))
7616 {
7617 rc2 = vdThreadFinishWrite(pDisk);
7618 AssertRC(rc2);
7619 }
7620 else if (RT_UNLIKELY(fLockRead))
7621 {
7622 rc2 = vdThreadFinishRead(pDisk);
7623 AssertRC(rc2);
7624 }
7625
7626 if (RT_SUCCESS(rc))
7627 {
7628 if (pIfProgress && pIfProgress->pfnProgress)
7629 pIfProgress->pfnProgress(pIfProgress->Core.pvUser, 100);
7630
7631 pDisk->cbSize = cbSize;
7632 }
7633
7634 LogFlowFunc(("returns %Rrc\n", rc));
7635 return rc;
7636}
7637
7638/**
7639 * Closes the last opened image file in HDD container.
7640 * If previous image file was opened in read-only mode (the normal case) and
7641 * the last opened image is in read-write mode then the previous image will be
7642 * reopened in read/write mode.
7643 *
7644 * @returns VBox status code.
7645 * @returns VERR_VD_NOT_OPENED if no image is opened in HDD container.
7646 * @param pDisk Pointer to HDD container.
7647 * @param fDelete If true, delete the image from the host disk.
7648 */
7649VBOXDDU_DECL(int) VDClose(PVBOXHDD pDisk, bool fDelete)
7650{
7651 int rc = VINF_SUCCESS;
7652 int rc2;
7653 bool fLockWrite = false;
7654
7655 LogFlowFunc(("pDisk=%#p fDelete=%d\n", pDisk, fDelete));
7656 do
7657 {
7658 /* sanity check */
7659 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
7660 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
7661
7662 /* Not worth splitting this up into a read lock phase and write
7663 * lock phase, as closing an image is a relatively fast operation
7664 * dominated by the part which needs the write lock. */
7665 rc2 = vdThreadStartWrite(pDisk);
7666 AssertRC(rc2);
7667 fLockWrite = true;
7668
7669 PVDIMAGE pImage = pDisk->pLast;
7670 if (!pImage)
7671 {
7672 rc = VERR_VD_NOT_OPENED;
7673 break;
7674 }
7675
7676 /* Destroy the current discard state first which might still have pending blocks. */
7677 rc = vdDiscardStateDestroy(pDisk);
7678 if (RT_FAILURE(rc))
7679 break;
7680
7681 unsigned uOpenFlags = pImage->Backend->pfnGetOpenFlags(pImage->pBackendData);
7682 /* Remove image from list of opened images. */
7683 vdRemoveImageFromList(pDisk, pImage);
7684 /* Close (and optionally delete) image. */
7685 rc = pImage->Backend->pfnClose(pImage->pBackendData, fDelete);
7686 /* Free remaining resources related to the image. */
7687 RTStrFree(pImage->pszFilename);
7688 RTMemFree(pImage);
7689
7690 pImage = pDisk->pLast;
7691 if (!pImage)
7692 break;
7693
7694 /* If disk was previously in read/write mode, make sure it will stay
7695 * like this (if possible) after closing this image. Set the open flags
7696 * accordingly. */
7697 if (!(uOpenFlags & VD_OPEN_FLAGS_READONLY))
7698 {
7699 uOpenFlags = pImage->Backend->pfnGetOpenFlags(pImage->pBackendData);
7700 uOpenFlags &= ~ VD_OPEN_FLAGS_READONLY;
7701 rc = pImage->Backend->pfnSetOpenFlags(pImage->pBackendData, uOpenFlags);
7702 }
7703
7704 /* Cache disk information. */
7705 pDisk->cbSize = pImage->Backend->pfnGetSize(pImage->pBackendData);
7706
7707 /* Cache PCHS geometry. */
7708 rc2 = pImage->Backend->pfnGetPCHSGeometry(pImage->pBackendData,
7709 &pDisk->PCHSGeometry);
7710 if (RT_FAILURE(rc2))
7711 {
7712 pDisk->PCHSGeometry.cCylinders = 0;
7713 pDisk->PCHSGeometry.cHeads = 0;
7714 pDisk->PCHSGeometry.cSectors = 0;
7715 }
7716 else
7717 {
7718 /* Make sure the PCHS geometry is properly clipped. */
7719 pDisk->PCHSGeometry.cCylinders = RT_MIN(pDisk->PCHSGeometry.cCylinders, 16383);
7720 pDisk->PCHSGeometry.cHeads = RT_MIN(pDisk->PCHSGeometry.cHeads, 16);
7721 pDisk->PCHSGeometry.cSectors = RT_MIN(pDisk->PCHSGeometry.cSectors, 63);
7722 }
7723
7724 /* Cache LCHS geometry. */
7725 rc2 = pImage->Backend->pfnGetLCHSGeometry(pImage->pBackendData,
7726 &pDisk->LCHSGeometry);
7727 if (RT_FAILURE(rc2))
7728 {
7729 pDisk->LCHSGeometry.cCylinders = 0;
7730 pDisk->LCHSGeometry.cHeads = 0;
7731 pDisk->LCHSGeometry.cSectors = 0;
7732 }
7733 else
7734 {
7735 /* Make sure the LCHS geometry is properly clipped. */
7736 pDisk->LCHSGeometry.cHeads = RT_MIN(pDisk->LCHSGeometry.cHeads, 255);
7737 pDisk->LCHSGeometry.cSectors = RT_MIN(pDisk->LCHSGeometry.cSectors, 63);
7738 }
7739 } while (0);
7740
7741 if (RT_UNLIKELY(fLockWrite))
7742 {
7743 rc2 = vdThreadFinishWrite(pDisk);
7744 AssertRC(rc2);
7745 }
7746
7747 LogFlowFunc(("returns %Rrc\n", rc));
7748 return rc;
7749}
7750
7751/**
7752 * Closes the currently opened cache image file in HDD container.
7753 *
7754 * @return VBox status code.
7755 * @return VERR_VD_NOT_OPENED if no cache is opened in HDD container.
7756 * @param pDisk Pointer to HDD container.
7757 * @param fDelete If true, delete the image from the host disk.
7758 */
7759VBOXDDU_DECL(int) VDCacheClose(PVBOXHDD pDisk, bool fDelete)
7760{
7761 int rc = VINF_SUCCESS;
7762 int rc2;
7763 bool fLockWrite = false;
7764 PVDCACHE pCache = NULL;
7765
7766 LogFlowFunc(("pDisk=%#p fDelete=%d\n", pDisk, fDelete));
7767
7768 do
7769 {
7770 /* sanity check */
7771 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
7772 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
7773
7774 rc2 = vdThreadStartWrite(pDisk);
7775 AssertRC(rc2);
7776 fLockWrite = true;
7777
7778 AssertPtrBreakStmt(pDisk->pCache, rc = VERR_VD_CACHE_NOT_FOUND);
7779
7780 pCache = pDisk->pCache;
7781 pDisk->pCache = NULL;
7782
7783 pCache->Backend->pfnClose(pCache->pBackendData, fDelete);
7784 if (pCache->pszFilename)
7785 RTStrFree(pCache->pszFilename);
7786 RTMemFree(pCache);
7787 } while (0);
7788
7789 if (RT_LIKELY(fLockWrite))
7790 {
7791 rc2 = vdThreadFinishWrite(pDisk);
7792 AssertRC(rc2);
7793 }
7794
7795 LogFlowFunc(("returns %Rrc\n", rc));
7796 return rc;
7797}
7798
7799/**
7800 * Closes all opened image files in HDD container.
7801 *
7802 * @returns VBox status code.
7803 * @param pDisk Pointer to HDD container.
7804 */
7805VBOXDDU_DECL(int) VDCloseAll(PVBOXHDD pDisk)
7806{
7807 int rc = VINF_SUCCESS;
7808 int rc2;
7809 bool fLockWrite = false;
7810
7811 LogFlowFunc(("pDisk=%#p\n", pDisk));
7812 do
7813 {
7814 /* sanity check */
7815 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
7816 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
7817
7818 /* Lock the entire operation. */
7819 rc2 = vdThreadStartWrite(pDisk);
7820 AssertRC(rc2);
7821 fLockWrite = true;
7822
7823 PVDCACHE pCache = pDisk->pCache;
7824 if (pCache)
7825 {
7826 rc2 = pCache->Backend->pfnClose(pCache->pBackendData, false);
7827 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
7828 rc = rc2;
7829
7830 if (pCache->pszFilename)
7831 RTStrFree(pCache->pszFilename);
7832 RTMemFree(pCache);
7833 }
7834
7835 PVDIMAGE pImage = pDisk->pLast;
7836 while (VALID_PTR(pImage))
7837 {
7838 PVDIMAGE pPrev = pImage->pPrev;
7839 /* Remove image from list of opened images. */
7840 vdRemoveImageFromList(pDisk, pImage);
7841 /* Close image. */
7842 rc2 = pImage->Backend->pfnClose(pImage->pBackendData, false);
7843 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
7844 rc = rc2;
7845 /* Free remaining resources related to the image. */
7846 RTStrFree(pImage->pszFilename);
7847 RTMemFree(pImage);
7848 pImage = pPrev;
7849 }
7850 Assert(!VALID_PTR(pDisk->pLast));
7851 } while (0);
7852
7853 if (RT_UNLIKELY(fLockWrite))
7854 {
7855 rc2 = vdThreadFinishWrite(pDisk);
7856 AssertRC(rc2);
7857 }
7858
7859 LogFlowFunc(("returns %Rrc\n", rc));
7860 return rc;
7861}
7862
7863/**
7864 * Read data from virtual HDD.
7865 *
7866 * @returns VBox status code.
7867 * @returns VERR_VD_NOT_OPENED if no image is opened in HDD container.
7868 * @param pDisk Pointer to HDD container.
7869 * @param uOffset Offset of first reading byte from start of disk.
7870 * @param pvBuf Pointer to buffer for reading data.
7871 * @param cbRead Number of bytes to read.
7872 */
7873VBOXDDU_DECL(int) VDRead(PVBOXHDD pDisk, uint64_t uOffset, void *pvBuf,
7874 size_t cbRead)
7875{
7876 int rc = VINF_SUCCESS;
7877 int rc2;
7878 bool fLockRead = false;
7879
7880 LogFlowFunc(("pDisk=%#p uOffset=%llu pvBuf=%p cbRead=%zu\n",
7881 pDisk, uOffset, pvBuf, cbRead));
7882 do
7883 {
7884 /* sanity check */
7885 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
7886 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
7887
7888 /* Check arguments. */
7889 AssertMsgBreakStmt(VALID_PTR(pvBuf),
7890 ("pvBuf=%#p\n", pvBuf),
7891 rc = VERR_INVALID_PARAMETER);
7892 AssertMsgBreakStmt(cbRead,
7893 ("cbRead=%zu\n", cbRead),
7894 rc = VERR_INVALID_PARAMETER);
7895
7896 rc2 = vdThreadStartRead(pDisk);
7897 AssertRC(rc2);
7898 fLockRead = true;
7899
7900 AssertMsgBreakStmt(uOffset + cbRead <= pDisk->cbSize,
7901 ("uOffset=%llu cbRead=%zu pDisk->cbSize=%llu\n",
7902 uOffset, cbRead, pDisk->cbSize),
7903 rc = VERR_INVALID_PARAMETER);
7904
7905 PVDIMAGE pImage = pDisk->pLast;
7906 AssertPtrBreakStmt(pImage, rc = VERR_VD_NOT_OPENED);
7907
7908 rc = vdReadHelper(pDisk, pImage, uOffset, pvBuf, cbRead,
7909 true /* fUpdateCache */);
7910 } while (0);
7911
7912 if (RT_UNLIKELY(fLockRead))
7913 {
7914 rc2 = vdThreadFinishRead(pDisk);
7915 AssertRC(rc2);
7916 }
7917
7918 LogFlowFunc(("returns %Rrc\n", rc));
7919 return rc;
7920}
7921
7922/**
7923 * Write data to virtual HDD.
7924 *
7925 * @returns VBox status code.
7926 * @returns VERR_VD_NOT_OPENED if no image is opened in HDD container.
7927 * @param pDisk Pointer to HDD container.
7928 * @param uOffset Offset of the first byte being
7929 * written from start of disk.
7930 * @param pvBuf Pointer to buffer for writing data.
7931 * @param cbWrite Number of bytes to write.
7932 */
7933VBOXDDU_DECL(int) VDWrite(PVBOXHDD pDisk, uint64_t uOffset, const void *pvBuf,
7934 size_t cbWrite)
7935{
7936 int rc = VINF_SUCCESS;
7937 int rc2;
7938 bool fLockWrite = false;
7939
7940 LogFlowFunc(("pDisk=%#p uOffset=%llu pvBuf=%p cbWrite=%zu\n",
7941 pDisk, uOffset, pvBuf, cbWrite));
7942 do
7943 {
7944 /* sanity check */
7945 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
7946 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
7947
7948 /* Check arguments. */
7949 AssertMsgBreakStmt(VALID_PTR(pvBuf),
7950 ("pvBuf=%#p\n", pvBuf),
7951 rc = VERR_INVALID_PARAMETER);
7952 AssertMsgBreakStmt(cbWrite,
7953 ("cbWrite=%zu\n", cbWrite),
7954 rc = VERR_INVALID_PARAMETER);
7955
7956 rc2 = vdThreadStartWrite(pDisk);
7957 AssertRC(rc2);
7958 fLockWrite = true;
7959
7960 AssertMsgBreakStmt(uOffset + cbWrite <= pDisk->cbSize,
7961 ("uOffset=%llu cbWrite=%zu pDisk->cbSize=%llu\n",
7962 uOffset, cbWrite, pDisk->cbSize),
7963 rc = VERR_INVALID_PARAMETER);
7964
7965 PVDIMAGE pImage = pDisk->pLast;
7966 AssertPtrBreakStmt(pImage, rc = VERR_VD_NOT_OPENED);
7967
7968 vdSetModifiedFlag(pDisk);
7969 rc = vdWriteHelper(pDisk, pImage, uOffset, pvBuf, cbWrite,
7970 true /* fUpdateCache */);
7971 if (RT_FAILURE(rc))
7972 break;
7973
7974 /* If there is a merge (in the direction towards a parent) running
7975 * concurrently then we have to also "relay" the write to this parent,
7976 * as the merge position might be already past the position where
7977 * this write is going. The "context" of the write can come from the
7978 * natural chain, since merging either already did or will take care
7979 * of the "other" content which is might be needed to fill the block
7980 * to a full allocation size. The cache doesn't need to be touched
7981 * as this write is covered by the previous one. */
7982 if (RT_UNLIKELY(pDisk->pImageRelay))
7983 rc = vdWriteHelper(pDisk, pDisk->pImageRelay, uOffset,
7984 pvBuf, cbWrite, false /* fUpdateCache */);
7985 } while (0);
7986
7987 if (RT_UNLIKELY(fLockWrite))
7988 {
7989 rc2 = vdThreadFinishWrite(pDisk);
7990 AssertRC(rc2);
7991 }
7992
7993 LogFlowFunc(("returns %Rrc\n", rc));
7994 return rc;
7995}
7996
7997/**
7998 * Make sure the on disk representation of a virtual HDD is up to date.
7999 *
8000 * @returns VBox status code.
8001 * @returns VERR_VD_NOT_OPENED if no image is opened in HDD container.
8002 * @param pDisk Pointer to HDD container.
8003 */
8004VBOXDDU_DECL(int) VDFlush(PVBOXHDD pDisk)
8005{
8006 int rc = VINF_SUCCESS;
8007 int rc2;
8008 bool fLockWrite = false;
8009
8010 LogFlowFunc(("pDisk=%#p\n", pDisk));
8011 do
8012 {
8013 /* sanity check */
8014 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
8015 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
8016
8017 rc2 = vdThreadStartWrite(pDisk);
8018 AssertRC(rc2);
8019 fLockWrite = true;
8020
8021 PVDIMAGE pImage = pDisk->pLast;
8022 AssertPtrBreakStmt(pImage, rc = VERR_VD_NOT_OPENED);
8023
8024 vdResetModifiedFlag(pDisk);
8025 rc = pImage->Backend->pfnFlush(pImage->pBackendData);
8026
8027 if ( RT_SUCCESS(rc)
8028 && pDisk->pCache)
8029 rc = pDisk->pCache->Backend->pfnFlush(pDisk->pCache->pBackendData);
8030 } while (0);
8031
8032 if (RT_UNLIKELY(fLockWrite))
8033 {
8034 rc2 = vdThreadFinishWrite(pDisk);
8035 AssertRC(rc2);
8036 }
8037
8038 LogFlowFunc(("returns %Rrc\n", rc));
8039 return rc;
8040}
8041
8042/**
8043 * Get number of opened images in HDD container.
8044 *
8045 * @returns Number of opened images for HDD container. 0 if no images have been opened.
8046 * @param pDisk Pointer to HDD container.
8047 */
8048VBOXDDU_DECL(unsigned) VDGetCount(PVBOXHDD pDisk)
8049{
8050 unsigned cImages;
8051 int rc2;
8052 bool fLockRead = false;
8053
8054 LogFlowFunc(("pDisk=%#p\n", pDisk));
8055 do
8056 {
8057 /* sanity check */
8058 AssertPtrBreakStmt(pDisk, cImages = 0);
8059 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
8060
8061 rc2 = vdThreadStartRead(pDisk);
8062 AssertRC(rc2);
8063 fLockRead = true;
8064
8065 cImages = pDisk->cImages;
8066 } while (0);
8067
8068 if (RT_UNLIKELY(fLockRead))
8069 {
8070 rc2 = vdThreadFinishRead(pDisk);
8071 AssertRC(rc2);
8072 }
8073
8074 LogFlowFunc(("returns %u\n", cImages));
8075 return cImages;
8076}
8077
8078/**
8079 * Get read/write mode of HDD container.
8080 *
8081 * @returns Virtual disk ReadOnly status.
8082 * @returns true if no image is opened in HDD container.
8083 * @param pDisk Pointer to HDD container.
8084 */
8085VBOXDDU_DECL(bool) VDIsReadOnly(PVBOXHDD pDisk)
8086{
8087 bool fReadOnly;
8088 int rc2;
8089 bool fLockRead = false;
8090
8091 LogFlowFunc(("pDisk=%#p\n", pDisk));
8092 do
8093 {
8094 /* sanity check */
8095 AssertPtrBreakStmt(pDisk, fReadOnly = false);
8096 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
8097
8098 rc2 = vdThreadStartRead(pDisk);
8099 AssertRC(rc2);
8100 fLockRead = true;
8101
8102 PVDIMAGE pImage = pDisk->pLast;
8103 AssertPtrBreakStmt(pImage, fReadOnly = true);
8104
8105 unsigned uOpenFlags;
8106 uOpenFlags = pDisk->pLast->Backend->pfnGetOpenFlags(pDisk->pLast->pBackendData);
8107 fReadOnly = !!(uOpenFlags & VD_OPEN_FLAGS_READONLY);
8108 } while (0);
8109
8110 if (RT_UNLIKELY(fLockRead))
8111 {
8112 rc2 = vdThreadFinishRead(pDisk);
8113 AssertRC(rc2);
8114 }
8115
8116 LogFlowFunc(("returns %d\n", fReadOnly));
8117 return fReadOnly;
8118}
8119
8120/**
8121 * Get total capacity of an image in HDD container.
8122 *
8123 * @returns Virtual disk size in bytes.
8124 * @returns 0 if no image with specified number was not opened.
8125 * @param pDisk Pointer to HDD container.
8126 * @param nImage Image number, counts from 0. 0 is always base image of container.
8127 */
8128VBOXDDU_DECL(uint64_t) VDGetSize(PVBOXHDD pDisk, unsigned nImage)
8129{
8130 uint64_t cbSize;
8131 int rc2;
8132 bool fLockRead = false;
8133
8134 LogFlowFunc(("pDisk=%#p nImage=%u\n", pDisk, nImage));
8135 do
8136 {
8137 /* sanity check */
8138 AssertPtrBreakStmt(pDisk, cbSize = 0);
8139 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
8140
8141 rc2 = vdThreadStartRead(pDisk);
8142 AssertRC(rc2);
8143 fLockRead = true;
8144
8145 PVDIMAGE pImage = vdGetImageByNumber(pDisk, nImage);
8146 AssertPtrBreakStmt(pImage, cbSize = 0);
8147 cbSize = pImage->Backend->pfnGetSize(pImage->pBackendData);
8148 } while (0);
8149
8150 if (RT_UNLIKELY(fLockRead))
8151 {
8152 rc2 = vdThreadFinishRead(pDisk);
8153 AssertRC(rc2);
8154 }
8155
8156 LogFlowFunc(("returns %llu\n", cbSize));
8157 return cbSize;
8158}
8159
8160/**
8161 * Get total file size of an image in HDD container.
8162 *
8163 * @returns Virtual disk size in bytes.
8164 * @returns 0 if no image is opened in HDD container.
8165 * @param pDisk Pointer to HDD container.
8166 * @param nImage Image number, counts from 0. 0 is always base image of container.
8167 */
8168VBOXDDU_DECL(uint64_t) VDGetFileSize(PVBOXHDD pDisk, unsigned nImage)
8169{
8170 uint64_t cbSize;
8171 int rc2;
8172 bool fLockRead = false;
8173
8174 LogFlowFunc(("pDisk=%#p nImage=%u\n", pDisk, nImage));
8175 do
8176 {
8177 /* sanity check */
8178 AssertPtrBreakStmt(pDisk, cbSize = 0);
8179 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
8180
8181 rc2 = vdThreadStartRead(pDisk);
8182 AssertRC(rc2);
8183 fLockRead = true;
8184
8185 PVDIMAGE pImage = vdGetImageByNumber(pDisk, nImage);
8186 AssertPtrBreakStmt(pImage, cbSize = 0);
8187 cbSize = pImage->Backend->pfnGetFileSize(pImage->pBackendData);
8188 } while (0);
8189
8190 if (RT_UNLIKELY(fLockRead))
8191 {
8192 rc2 = vdThreadFinishRead(pDisk);
8193 AssertRC(rc2);
8194 }
8195
8196 LogFlowFunc(("returns %llu\n", cbSize));
8197 return cbSize;
8198}
8199
8200/**
8201 * Get virtual disk PCHS geometry stored in HDD container.
8202 *
8203 * @returns VBox status code.
8204 * @returns VERR_VD_IMAGE_NOT_FOUND if image with specified number was not opened.
8205 * @returns VERR_VD_GEOMETRY_NOT_SET if no geometry present in the HDD container.
8206 * @param pDisk Pointer to HDD container.
8207 * @param nImage Image number, counts from 0. 0 is always base image of container.
8208 * @param pPCHSGeometry Where to store PCHS geometry. Not NULL.
8209 */
8210VBOXDDU_DECL(int) VDGetPCHSGeometry(PVBOXHDD pDisk, unsigned nImage,
8211 PVDGEOMETRY pPCHSGeometry)
8212{
8213 int rc = VINF_SUCCESS;
8214 int rc2;
8215 bool fLockRead = false;
8216
8217 LogFlowFunc(("pDisk=%#p nImage=%u pPCHSGeometry=%#p\n",
8218 pDisk, nImage, pPCHSGeometry));
8219 do
8220 {
8221 /* sanity check */
8222 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
8223 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
8224
8225 /* Check arguments. */
8226 AssertMsgBreakStmt(VALID_PTR(pPCHSGeometry),
8227 ("pPCHSGeometry=%#p\n", pPCHSGeometry),
8228 rc = VERR_INVALID_PARAMETER);
8229
8230 rc2 = vdThreadStartRead(pDisk);
8231 AssertRC(rc2);
8232 fLockRead = true;
8233
8234 PVDIMAGE pImage = vdGetImageByNumber(pDisk, nImage);
8235 AssertPtrBreakStmt(pImage, rc = VERR_VD_IMAGE_NOT_FOUND);
8236
8237 if (pImage == pDisk->pLast)
8238 {
8239 /* Use cached information if possible. */
8240 if (pDisk->PCHSGeometry.cCylinders != 0)
8241 *pPCHSGeometry = pDisk->PCHSGeometry;
8242 else
8243 rc = VERR_VD_GEOMETRY_NOT_SET;
8244 }
8245 else
8246 rc = pImage->Backend->pfnGetPCHSGeometry(pImage->pBackendData,
8247 pPCHSGeometry);
8248 } while (0);
8249
8250 if (RT_UNLIKELY(fLockRead))
8251 {
8252 rc2 = vdThreadFinishRead(pDisk);
8253 AssertRC(rc2);
8254 }
8255
8256 LogFlowFunc(("%Rrc (PCHS=%u/%u/%u)\n", rc,
8257 pDisk->PCHSGeometry.cCylinders, pDisk->PCHSGeometry.cHeads,
8258 pDisk->PCHSGeometry.cSectors));
8259 return rc;
8260}
8261
8262/**
8263 * Store virtual disk PCHS geometry in HDD container.
8264 *
8265 * Note that in case of unrecoverable error all images in HDD container will be closed.
8266 *
8267 * @returns VBox status code.
8268 * @returns VERR_VD_IMAGE_NOT_FOUND if image with specified number was not opened.
8269 * @returns VERR_VD_GEOMETRY_NOT_SET if no geometry present in the HDD container.
8270 * @param pDisk Pointer to HDD container.
8271 * @param nImage Image number, counts from 0. 0 is always base image of container.
8272 * @param pPCHSGeometry Where to load PCHS geometry from. Not NULL.
8273 */
8274VBOXDDU_DECL(int) VDSetPCHSGeometry(PVBOXHDD pDisk, unsigned nImage,
8275 PCVDGEOMETRY pPCHSGeometry)
8276{
8277 int rc = VINF_SUCCESS;
8278 int rc2;
8279 bool fLockWrite = false;
8280
8281 LogFlowFunc(("pDisk=%#p nImage=%u pPCHSGeometry=%#p PCHS=%u/%u/%u\n",
8282 pDisk, nImage, pPCHSGeometry, pPCHSGeometry->cCylinders,
8283 pPCHSGeometry->cHeads, pPCHSGeometry->cSectors));
8284 do
8285 {
8286 /* sanity check */
8287 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
8288 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
8289
8290 /* Check arguments. */
8291 AssertMsgBreakStmt( VALID_PTR(pPCHSGeometry)
8292 && pPCHSGeometry->cHeads <= 16
8293 && pPCHSGeometry->cSectors <= 63,
8294 ("pPCHSGeometry=%#p PCHS=%u/%u/%u\n", pPCHSGeometry,
8295 pPCHSGeometry->cCylinders, pPCHSGeometry->cHeads,
8296 pPCHSGeometry->cSectors),
8297 rc = VERR_INVALID_PARAMETER);
8298
8299 rc2 = vdThreadStartWrite(pDisk);
8300 AssertRC(rc2);
8301 fLockWrite = true;
8302
8303 PVDIMAGE pImage = vdGetImageByNumber(pDisk, nImage);
8304 AssertPtrBreakStmt(pImage, rc = VERR_VD_IMAGE_NOT_FOUND);
8305
8306 if (pImage == pDisk->pLast)
8307 {
8308 if ( pPCHSGeometry->cCylinders != pDisk->PCHSGeometry.cCylinders
8309 || pPCHSGeometry->cHeads != pDisk->PCHSGeometry.cHeads
8310 || pPCHSGeometry->cSectors != pDisk->PCHSGeometry.cSectors)
8311 {
8312 /* Only update geometry if it is changed. Avoids similar checks
8313 * in every backend. Most of the time the new geometry is set
8314 * to the previous values, so no need to go through the hassle
8315 * of updating an image which could be opened in read-only mode
8316 * right now. */
8317 rc = pImage->Backend->pfnSetPCHSGeometry(pImage->pBackendData,
8318 pPCHSGeometry);
8319
8320 /* Cache new geometry values in any case. */
8321 rc2 = pImage->Backend->pfnGetPCHSGeometry(pImage->pBackendData,
8322 &pDisk->PCHSGeometry);
8323 if (RT_FAILURE(rc2))
8324 {
8325 pDisk->PCHSGeometry.cCylinders = 0;
8326 pDisk->PCHSGeometry.cHeads = 0;
8327 pDisk->PCHSGeometry.cSectors = 0;
8328 }
8329 else
8330 {
8331 /* Make sure the CHS geometry is properly clipped. */
8332 pDisk->PCHSGeometry.cHeads = RT_MIN(pDisk->PCHSGeometry.cHeads, 255);
8333 pDisk->PCHSGeometry.cSectors = RT_MIN(pDisk->PCHSGeometry.cSectors, 63);
8334 }
8335 }
8336 }
8337 else
8338 {
8339 VDGEOMETRY PCHS;
8340 rc = pImage->Backend->pfnGetPCHSGeometry(pImage->pBackendData,
8341 &PCHS);
8342 if ( RT_FAILURE(rc)
8343 || pPCHSGeometry->cCylinders != PCHS.cCylinders
8344 || pPCHSGeometry->cHeads != PCHS.cHeads
8345 || pPCHSGeometry->cSectors != PCHS.cSectors)
8346 {
8347 /* Only update geometry if it is changed. Avoids similar checks
8348 * in every backend. Most of the time the new geometry is set
8349 * to the previous values, so no need to go through the hassle
8350 * of updating an image which could be opened in read-only mode
8351 * right now. */
8352 rc = pImage->Backend->pfnSetPCHSGeometry(pImage->pBackendData,
8353 pPCHSGeometry);
8354 }
8355 }
8356 } while (0);
8357
8358 if (RT_UNLIKELY(fLockWrite))
8359 {
8360 rc2 = vdThreadFinishWrite(pDisk);
8361 AssertRC(rc2);
8362 }
8363
8364 LogFlowFunc(("returns %Rrc\n", rc));
8365 return rc;
8366}
8367
8368/**
8369 * Get virtual disk LCHS geometry stored in HDD container.
8370 *
8371 * @returns VBox status code.
8372 * @returns VERR_VD_IMAGE_NOT_FOUND if image with specified number was not opened.
8373 * @returns VERR_VD_GEOMETRY_NOT_SET if no geometry present in the HDD container.
8374 * @param pDisk Pointer to HDD container.
8375 * @param nImage Image number, counts from 0. 0 is always base image of container.
8376 * @param pLCHSGeometry Where to store LCHS geometry. Not NULL.
8377 */
8378VBOXDDU_DECL(int) VDGetLCHSGeometry(PVBOXHDD pDisk, unsigned nImage,
8379 PVDGEOMETRY pLCHSGeometry)
8380{
8381 int rc = VINF_SUCCESS;
8382 int rc2;
8383 bool fLockRead = false;
8384
8385 LogFlowFunc(("pDisk=%#p nImage=%u pLCHSGeometry=%#p\n",
8386 pDisk, nImage, pLCHSGeometry));
8387 do
8388 {
8389 /* sanity check */
8390 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
8391 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
8392
8393 /* Check arguments. */
8394 AssertMsgBreakStmt(VALID_PTR(pLCHSGeometry),
8395 ("pLCHSGeometry=%#p\n", pLCHSGeometry),
8396 rc = VERR_INVALID_PARAMETER);
8397
8398 rc2 = vdThreadStartRead(pDisk);
8399 AssertRC(rc2);
8400 fLockRead = true;
8401
8402 PVDIMAGE pImage = vdGetImageByNumber(pDisk, nImage);
8403 AssertPtrBreakStmt(pImage, rc = VERR_VD_IMAGE_NOT_FOUND);
8404
8405 if (pImage == pDisk->pLast)
8406 {
8407 /* Use cached information if possible. */
8408 if (pDisk->LCHSGeometry.cCylinders != 0)
8409 *pLCHSGeometry = pDisk->LCHSGeometry;
8410 else
8411 rc = VERR_VD_GEOMETRY_NOT_SET;
8412 }
8413 else
8414 rc = pImage->Backend->pfnGetLCHSGeometry(pImage->pBackendData,
8415 pLCHSGeometry);
8416 } while (0);
8417
8418 if (RT_UNLIKELY(fLockRead))
8419 {
8420 rc2 = vdThreadFinishRead(pDisk);
8421 AssertRC(rc2);
8422 }
8423
8424 LogFlowFunc((": %Rrc (LCHS=%u/%u/%u)\n", rc,
8425 pDisk->LCHSGeometry.cCylinders, pDisk->LCHSGeometry.cHeads,
8426 pDisk->LCHSGeometry.cSectors));
8427 return rc;
8428}
8429
8430/**
8431 * Store virtual disk LCHS geometry in HDD container.
8432 *
8433 * Note that in case of unrecoverable error all images in HDD container will be closed.
8434 *
8435 * @returns VBox status code.
8436 * @returns VERR_VD_IMAGE_NOT_FOUND if image with specified number was not opened.
8437 * @returns VERR_VD_GEOMETRY_NOT_SET if no geometry present in the HDD container.
8438 * @param pDisk Pointer to HDD container.
8439 * @param nImage Image number, counts from 0. 0 is always base image of container.
8440 * @param pLCHSGeometry Where to load LCHS geometry from. Not NULL.
8441 */
8442VBOXDDU_DECL(int) VDSetLCHSGeometry(PVBOXHDD pDisk, unsigned nImage,
8443 PCVDGEOMETRY pLCHSGeometry)
8444{
8445 int rc = VINF_SUCCESS;
8446 int rc2;
8447 bool fLockWrite = false;
8448
8449 LogFlowFunc(("pDisk=%#p nImage=%u pLCHSGeometry=%#p LCHS=%u/%u/%u\n",
8450 pDisk, nImage, pLCHSGeometry, pLCHSGeometry->cCylinders,
8451 pLCHSGeometry->cHeads, pLCHSGeometry->cSectors));
8452 do
8453 {
8454 /* sanity check */
8455 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
8456 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
8457
8458 /* Check arguments. */
8459 AssertMsgBreakStmt( VALID_PTR(pLCHSGeometry)
8460 && pLCHSGeometry->cHeads <= 255
8461 && pLCHSGeometry->cSectors <= 63,
8462 ("pLCHSGeometry=%#p LCHS=%u/%u/%u\n", pLCHSGeometry,
8463 pLCHSGeometry->cCylinders, pLCHSGeometry->cHeads,
8464 pLCHSGeometry->cSectors),
8465 rc = VERR_INVALID_PARAMETER);
8466
8467 rc2 = vdThreadStartWrite(pDisk);
8468 AssertRC(rc2);
8469 fLockWrite = true;
8470
8471 PVDIMAGE pImage = vdGetImageByNumber(pDisk, nImage);
8472 AssertPtrBreakStmt(pImage, rc = VERR_VD_IMAGE_NOT_FOUND);
8473
8474 if (pImage == pDisk->pLast)
8475 {
8476 if ( pLCHSGeometry->cCylinders != pDisk->LCHSGeometry.cCylinders
8477 || pLCHSGeometry->cHeads != pDisk->LCHSGeometry.cHeads
8478 || pLCHSGeometry->cSectors != pDisk->LCHSGeometry.cSectors)
8479 {
8480 /* Only update geometry if it is changed. Avoids similar checks
8481 * in every backend. Most of the time the new geometry is set
8482 * to the previous values, so no need to go through the hassle
8483 * of updating an image which could be opened in read-only mode
8484 * right now. */
8485 rc = pImage->Backend->pfnSetLCHSGeometry(pImage->pBackendData,
8486 pLCHSGeometry);
8487
8488 /* Cache new geometry values in any case. */
8489 rc2 = pImage->Backend->pfnGetLCHSGeometry(pImage->pBackendData,
8490 &pDisk->LCHSGeometry);
8491 if (RT_FAILURE(rc2))
8492 {
8493 pDisk->LCHSGeometry.cCylinders = 0;
8494 pDisk->LCHSGeometry.cHeads = 0;
8495 pDisk->LCHSGeometry.cSectors = 0;
8496 }
8497 else
8498 {
8499 /* Make sure the CHS geometry is properly clipped. */
8500 pDisk->LCHSGeometry.cHeads = RT_MIN(pDisk->LCHSGeometry.cHeads, 255);
8501 pDisk->LCHSGeometry.cSectors = RT_MIN(pDisk->LCHSGeometry.cSectors, 63);
8502 }
8503 }
8504 }
8505 else
8506 {
8507 VDGEOMETRY LCHS;
8508 rc = pImage->Backend->pfnGetLCHSGeometry(pImage->pBackendData,
8509 &LCHS);
8510 if ( RT_FAILURE(rc)
8511 || pLCHSGeometry->cCylinders != LCHS.cCylinders
8512 || pLCHSGeometry->cHeads != LCHS.cHeads
8513 || pLCHSGeometry->cSectors != LCHS.cSectors)
8514 {
8515 /* Only update geometry if it is changed. Avoids similar checks
8516 * in every backend. Most of the time the new geometry is set
8517 * to the previous values, so no need to go through the hassle
8518 * of updating an image which could be opened in read-only mode
8519 * right now. */
8520 rc = pImage->Backend->pfnSetLCHSGeometry(pImage->pBackendData,
8521 pLCHSGeometry);
8522 }
8523 }
8524 } while (0);
8525
8526 if (RT_UNLIKELY(fLockWrite))
8527 {
8528 rc2 = vdThreadFinishWrite(pDisk);
8529 AssertRC(rc2);
8530 }
8531
8532 LogFlowFunc(("returns %Rrc\n", rc));
8533 return rc;
8534}
8535
8536/**
8537 * Get version of image in HDD container.
8538 *
8539 * @returns VBox status code.
8540 * @returns VERR_VD_IMAGE_NOT_FOUND if image with specified number was not opened.
8541 * @param pDisk Pointer to HDD container.
8542 * @param nImage Image number, counts from 0. 0 is always base image of container.
8543 * @param puVersion Where to store the image version.
8544 */
8545VBOXDDU_DECL(int) VDGetVersion(PVBOXHDD pDisk, unsigned nImage,
8546 unsigned *puVersion)
8547{
8548 int rc = VINF_SUCCESS;
8549 int rc2;
8550 bool fLockRead = false;
8551
8552 LogFlowFunc(("pDisk=%#p nImage=%u puVersion=%#p\n",
8553 pDisk, nImage, puVersion));
8554 do
8555 {
8556 /* sanity check */
8557 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
8558 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
8559
8560 /* Check arguments. */
8561 AssertMsgBreakStmt(VALID_PTR(puVersion),
8562 ("puVersion=%#p\n", puVersion),
8563 rc = VERR_INVALID_PARAMETER);
8564
8565 rc2 = vdThreadStartRead(pDisk);
8566 AssertRC(rc2);
8567 fLockRead = true;
8568
8569 PVDIMAGE pImage = vdGetImageByNumber(pDisk, nImage);
8570 AssertPtrBreakStmt(pImage, rc = VERR_VD_IMAGE_NOT_FOUND);
8571
8572 *puVersion = pImage->Backend->pfnGetVersion(pImage->pBackendData);
8573 } while (0);
8574
8575 if (RT_UNLIKELY(fLockRead))
8576 {
8577 rc2 = vdThreadFinishRead(pDisk);
8578 AssertRC(rc2);
8579 }
8580
8581 LogFlowFunc(("returns %Rrc uVersion=%#x\n", rc, *puVersion));
8582 return rc;
8583}
8584
8585/**
8586 * List the capabilities of image backend in HDD container.
8587 *
8588 * @returns VBox status code.
8589 * @returns VERR_VD_IMAGE_NOT_FOUND if image with specified number was not opened.
8590 * @param pDisk Pointer to the HDD container.
8591 * @param nImage Image number, counts from 0. 0 is always base image of container.
8592 * @param pbackendInfo Where to store the backend information.
8593 */
8594VBOXDDU_DECL(int) VDBackendInfoSingle(PVBOXHDD pDisk, unsigned nImage,
8595 PVDBACKENDINFO pBackendInfo)
8596{
8597 int rc = VINF_SUCCESS;
8598 int rc2;
8599 bool fLockRead = false;
8600
8601 LogFlowFunc(("pDisk=%#p nImage=%u pBackendInfo=%#p\n",
8602 pDisk, nImage, pBackendInfo));
8603 do
8604 {
8605 /* sanity check */
8606 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
8607 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
8608
8609 /* Check arguments. */
8610 AssertMsgBreakStmt(VALID_PTR(pBackendInfo),
8611 ("pBackendInfo=%#p\n", pBackendInfo),
8612 rc = VERR_INVALID_PARAMETER);
8613
8614 rc2 = vdThreadStartRead(pDisk);
8615 AssertRC(rc2);
8616 fLockRead = true;
8617
8618 PVDIMAGE pImage = vdGetImageByNumber(pDisk, nImage);
8619 AssertPtrBreakStmt(pImage, rc = VERR_VD_IMAGE_NOT_FOUND);
8620
8621 pBackendInfo->pszBackend = pImage->Backend->pszBackendName;
8622 pBackendInfo->uBackendCaps = pImage->Backend->uBackendCaps;
8623 pBackendInfo->paFileExtensions = pImage->Backend->paFileExtensions;
8624 pBackendInfo->paConfigInfo = pImage->Backend->paConfigInfo;
8625 } while (0);
8626
8627 if (RT_UNLIKELY(fLockRead))
8628 {
8629 rc2 = vdThreadFinishRead(pDisk);
8630 AssertRC(rc2);
8631 }
8632
8633 LogFlowFunc(("returns %Rrc\n", rc));
8634 return rc;
8635}
8636
8637/**
8638 * Get flags of image in HDD container.
8639 *
8640 * @returns VBox status code.
8641 * @returns VERR_VD_IMAGE_NOT_FOUND if image with specified number was not opened.
8642 * @param pDisk Pointer to HDD container.
8643 * @param nImage Image number, counts from 0. 0 is always base image of container.
8644 * @param puImageFlags Where to store the image flags.
8645 */
8646VBOXDDU_DECL(int) VDGetImageFlags(PVBOXHDD pDisk, unsigned nImage,
8647 unsigned *puImageFlags)
8648{
8649 int rc = VINF_SUCCESS;
8650 int rc2;
8651 bool fLockRead = false;
8652
8653 LogFlowFunc(("pDisk=%#p nImage=%u puImageFlags=%#p\n",
8654 pDisk, nImage, puImageFlags));
8655 do
8656 {
8657 /* sanity check */
8658 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
8659 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
8660
8661 /* Check arguments. */
8662 AssertMsgBreakStmt(VALID_PTR(puImageFlags),
8663 ("puImageFlags=%#p\n", puImageFlags),
8664 rc = VERR_INVALID_PARAMETER);
8665
8666 rc2 = vdThreadStartRead(pDisk);
8667 AssertRC(rc2);
8668 fLockRead = true;
8669
8670 PVDIMAGE pImage = vdGetImageByNumber(pDisk, nImage);
8671 AssertPtrBreakStmt(pImage, rc = VERR_VD_IMAGE_NOT_FOUND);
8672
8673 *puImageFlags = pImage->uImageFlags;
8674 } while (0);
8675
8676 if (RT_UNLIKELY(fLockRead))
8677 {
8678 rc2 = vdThreadFinishRead(pDisk);
8679 AssertRC(rc2);
8680 }
8681
8682 LogFlowFunc(("returns %Rrc uImageFlags=%#x\n", rc, *puImageFlags));
8683 return rc;
8684}
8685
8686/**
8687 * Get open flags of image in HDD container.
8688 *
8689 * @returns VBox status code.
8690 * @returns VERR_VD_IMAGE_NOT_FOUND if image with specified number was not opened.
8691 * @param pDisk Pointer to HDD container.
8692 * @param nImage Image number, counts from 0. 0 is always base image of container.
8693 * @param puOpenFlags Where to store the image open flags.
8694 */
8695VBOXDDU_DECL(int) VDGetOpenFlags(PVBOXHDD pDisk, unsigned nImage,
8696 unsigned *puOpenFlags)
8697{
8698 int rc = VINF_SUCCESS;
8699 int rc2;
8700 bool fLockRead = false;
8701
8702 LogFlowFunc(("pDisk=%#p nImage=%u puOpenFlags=%#p\n",
8703 pDisk, nImage, puOpenFlags));
8704 do
8705 {
8706 /* sanity check */
8707 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
8708 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
8709
8710 /* Check arguments. */
8711 AssertMsgBreakStmt(VALID_PTR(puOpenFlags),
8712 ("puOpenFlags=%#p\n", puOpenFlags),
8713 rc = VERR_INVALID_PARAMETER);
8714
8715 rc2 = vdThreadStartRead(pDisk);
8716 AssertRC(rc2);
8717 fLockRead = true;
8718
8719 PVDIMAGE pImage = vdGetImageByNumber(pDisk, nImage);
8720 AssertPtrBreakStmt(pImage, rc = VERR_VD_IMAGE_NOT_FOUND);
8721
8722 *puOpenFlags = pImage->Backend->pfnGetOpenFlags(pImage->pBackendData);
8723 } while (0);
8724
8725 if (RT_UNLIKELY(fLockRead))
8726 {
8727 rc2 = vdThreadFinishRead(pDisk);
8728 AssertRC(rc2);
8729 }
8730
8731 LogFlowFunc(("returns %Rrc uOpenFlags=%#x\n", rc, *puOpenFlags));
8732 return rc;
8733}
8734
8735/**
8736 * Set open flags of image in HDD container.
8737 * This operation may cause file locking changes and/or files being reopened.
8738 * Note that in case of unrecoverable error all images in HDD container will be closed.
8739 *
8740 * @returns VBox status code.
8741 * @returns VERR_VD_IMAGE_NOT_FOUND if image with specified number was not opened.
8742 * @param pDisk Pointer to HDD container.
8743 * @param nImage Image number, counts from 0. 0 is always base image of container.
8744 * @param uOpenFlags Image file open mode, see VD_OPEN_FLAGS_* constants.
8745 */
8746VBOXDDU_DECL(int) VDSetOpenFlags(PVBOXHDD pDisk, unsigned nImage,
8747 unsigned uOpenFlags)
8748{
8749 int rc;
8750 int rc2;
8751 bool fLockWrite = false;
8752
8753 LogFlowFunc(("pDisk=%#p uOpenFlags=%#u\n", pDisk, uOpenFlags));
8754 do
8755 {
8756 /* sanity check */
8757 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
8758 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
8759
8760 /* Check arguments. */
8761 AssertMsgBreakStmt((uOpenFlags & ~VD_OPEN_FLAGS_MASK) == 0,
8762 ("uOpenFlags=%#x\n", uOpenFlags),
8763 rc = VERR_INVALID_PARAMETER);
8764
8765 rc2 = vdThreadStartWrite(pDisk);
8766 AssertRC(rc2);
8767 fLockWrite = true;
8768
8769 /* Destroy any discard state because the image might be changed to readonly mode. */
8770 rc = vdDiscardStateDestroy(pDisk);
8771 if (RT_FAILURE(rc))
8772 break;
8773
8774 PVDIMAGE pImage = vdGetImageByNumber(pDisk, nImage);
8775 AssertPtrBreakStmt(pImage, rc = VERR_VD_IMAGE_NOT_FOUND);
8776
8777 rc = pImage->Backend->pfnSetOpenFlags(pImage->pBackendData,
8778 uOpenFlags & ~(VD_OPEN_FLAGS_HONOR_SAME | VD_OPEN_FLAGS_IGNORE_FLUSH | VD_OPEN_FLAGS_INFORM_ABOUT_ZERO_BLOCKS));
8779 if (RT_SUCCESS(rc))
8780 pImage->uOpenFlags = uOpenFlags & (VD_OPEN_FLAGS_HONOR_SAME | VD_OPEN_FLAGS_DISCARD | VD_OPEN_FLAGS_IGNORE_FLUSH | VD_OPEN_FLAGS_INFORM_ABOUT_ZERO_BLOCKS);
8781 } while (0);
8782
8783 if (RT_UNLIKELY(fLockWrite))
8784 {
8785 rc2 = vdThreadFinishWrite(pDisk);
8786 AssertRC(rc2);
8787 }
8788
8789 LogFlowFunc(("returns %Rrc\n", rc));
8790 return rc;
8791}
8792
8793/**
8794 * Get base filename of image in HDD container. Some image formats use
8795 * other filenames as well, so don't use this for anything but informational
8796 * purposes.
8797 *
8798 * @returns VBox status code.
8799 * @returns VERR_VD_IMAGE_NOT_FOUND if image with specified number was not opened.
8800 * @returns VERR_BUFFER_OVERFLOW if pszFilename buffer too small to hold filename.
8801 * @param pDisk Pointer to HDD container.
8802 * @param nImage Image number, counts from 0. 0 is always base image of container.
8803 * @param pszFilename Where to store the image file name.
8804 * @param cbFilename Size of buffer pszFilename points to.
8805 */
8806VBOXDDU_DECL(int) VDGetFilename(PVBOXHDD pDisk, unsigned nImage,
8807 char *pszFilename, unsigned cbFilename)
8808{
8809 int rc;
8810 int rc2;
8811 bool fLockRead = false;
8812
8813 LogFlowFunc(("pDisk=%#p nImage=%u pszFilename=%#p cbFilename=%u\n",
8814 pDisk, nImage, pszFilename, cbFilename));
8815 do
8816 {
8817 /* sanity check */
8818 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
8819 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
8820
8821 /* Check arguments. */
8822 AssertMsgBreakStmt(VALID_PTR(pszFilename) && *pszFilename,
8823 ("pszFilename=%#p \"%s\"\n", pszFilename, pszFilename),
8824 rc = VERR_INVALID_PARAMETER);
8825 AssertMsgBreakStmt(cbFilename,
8826 ("cbFilename=%u\n", cbFilename),
8827 rc = VERR_INVALID_PARAMETER);
8828
8829 rc2 = vdThreadStartRead(pDisk);
8830 AssertRC(rc2);
8831 fLockRead = true;
8832
8833 PVDIMAGE pImage = vdGetImageByNumber(pDisk, nImage);
8834 AssertPtrBreakStmt(pImage, rc = VERR_VD_IMAGE_NOT_FOUND);
8835
8836 size_t cb = strlen(pImage->pszFilename);
8837 if (cb <= cbFilename)
8838 {
8839 strcpy(pszFilename, pImage->pszFilename);
8840 rc = VINF_SUCCESS;
8841 }
8842 else
8843 {
8844 strncpy(pszFilename, pImage->pszFilename, cbFilename - 1);
8845 pszFilename[cbFilename - 1] = '\0';
8846 rc = VERR_BUFFER_OVERFLOW;
8847 }
8848 } while (0);
8849
8850 if (RT_UNLIKELY(fLockRead))
8851 {
8852 rc2 = vdThreadFinishRead(pDisk);
8853 AssertRC(rc2);
8854 }
8855
8856 LogFlowFunc(("returns %Rrc, pszFilename=\"%s\"\n", rc, pszFilename));
8857 return rc;
8858}
8859
8860/**
8861 * Get the comment line of image in HDD container.
8862 *
8863 * @returns VBox status code.
8864 * @returns VERR_VD_IMAGE_NOT_FOUND if image with specified number was not opened.
8865 * @returns VERR_BUFFER_OVERFLOW if pszComment buffer too small to hold comment text.
8866 * @param pDisk Pointer to HDD container.
8867 * @param nImage Image number, counts from 0. 0 is always base image of container.
8868 * @param pszComment Where to store the comment string of image. NULL is ok.
8869 * @param cbComment The size of pszComment buffer. 0 is ok.
8870 */
8871VBOXDDU_DECL(int) VDGetComment(PVBOXHDD pDisk, unsigned nImage,
8872 char *pszComment, unsigned cbComment)
8873{
8874 int rc;
8875 int rc2;
8876 bool fLockRead = false;
8877
8878 LogFlowFunc(("pDisk=%#p nImage=%u pszComment=%#p cbComment=%u\n",
8879 pDisk, nImage, pszComment, cbComment));
8880 do
8881 {
8882 /* sanity check */
8883 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
8884 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
8885
8886 /* Check arguments. */
8887 AssertMsgBreakStmt(VALID_PTR(pszComment),
8888 ("pszComment=%#p \"%s\"\n", pszComment, pszComment),
8889 rc = VERR_INVALID_PARAMETER);
8890 AssertMsgBreakStmt(cbComment,
8891 ("cbComment=%u\n", cbComment),
8892 rc = VERR_INVALID_PARAMETER);
8893
8894 rc2 = vdThreadStartRead(pDisk);
8895 AssertRC(rc2);
8896 fLockRead = true;
8897
8898 PVDIMAGE pImage = vdGetImageByNumber(pDisk, nImage);
8899 AssertPtrBreakStmt(pImage, rc = VERR_VD_IMAGE_NOT_FOUND);
8900
8901 rc = pImage->Backend->pfnGetComment(pImage->pBackendData, pszComment,
8902 cbComment);
8903 } while (0);
8904
8905 if (RT_UNLIKELY(fLockRead))
8906 {
8907 rc2 = vdThreadFinishRead(pDisk);
8908 AssertRC(rc2);
8909 }
8910
8911 LogFlowFunc(("returns %Rrc, pszComment=\"%s\"\n", rc, pszComment));
8912 return rc;
8913}
8914
8915/**
8916 * Changes the comment line of image in HDD container.
8917 *
8918 * @returns VBox status code.
8919 * @returns VERR_VD_IMAGE_NOT_FOUND if image with specified number was not opened.
8920 * @param pDisk Pointer to HDD container.
8921 * @param nImage Image number, counts from 0. 0 is always base image of container.
8922 * @param pszComment New comment string (UTF-8). NULL is allowed to reset the comment.
8923 */
8924VBOXDDU_DECL(int) VDSetComment(PVBOXHDD pDisk, unsigned nImage,
8925 const char *pszComment)
8926{
8927 int rc;
8928 int rc2;
8929 bool fLockWrite = false;
8930
8931 LogFlowFunc(("pDisk=%#p nImage=%u pszComment=%#p \"%s\"\n",
8932 pDisk, nImage, pszComment, pszComment));
8933 do
8934 {
8935 /* sanity check */
8936 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
8937 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
8938
8939 /* Check arguments. */
8940 AssertMsgBreakStmt(VALID_PTR(pszComment) || pszComment == NULL,
8941 ("pszComment=%#p \"%s\"\n", pszComment, pszComment),
8942 rc = VERR_INVALID_PARAMETER);
8943
8944 rc2 = vdThreadStartWrite(pDisk);
8945 AssertRC(rc2);
8946 fLockWrite = true;
8947
8948 PVDIMAGE pImage = vdGetImageByNumber(pDisk, nImage);
8949 AssertPtrBreakStmt(pImage, rc = VERR_VD_IMAGE_NOT_FOUND);
8950
8951 rc = pImage->Backend->pfnSetComment(pImage->pBackendData, pszComment);
8952 } while (0);
8953
8954 if (RT_UNLIKELY(fLockWrite))
8955 {
8956 rc2 = vdThreadFinishWrite(pDisk);
8957 AssertRC(rc2);
8958 }
8959
8960 LogFlowFunc(("returns %Rrc\n", rc));
8961 return rc;
8962}
8963
8964
8965/**
8966 * Get UUID of image in HDD container.
8967 *
8968 * @returns VBox status code.
8969 * @returns VERR_VD_IMAGE_NOT_FOUND if image with specified number was not opened.
8970 * @param pDisk Pointer to HDD container.
8971 * @param nImage Image number, counts from 0. 0 is always base image of container.
8972 * @param pUuid Where to store the image creation UUID.
8973 */
8974VBOXDDU_DECL(int) VDGetUuid(PVBOXHDD pDisk, unsigned nImage, PRTUUID pUuid)
8975{
8976 int rc;
8977 int rc2;
8978 bool fLockRead = false;
8979
8980 LogFlowFunc(("pDisk=%#p nImage=%u pUuid=%#p\n", pDisk, nImage, pUuid));
8981 do
8982 {
8983 /* sanity check */
8984 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
8985 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
8986
8987 /* Check arguments. */
8988 AssertMsgBreakStmt(VALID_PTR(pUuid),
8989 ("pUuid=%#p\n", pUuid),
8990 rc = VERR_INVALID_PARAMETER);
8991
8992 rc2 = vdThreadStartRead(pDisk);
8993 AssertRC(rc2);
8994 fLockRead = true;
8995
8996 PVDIMAGE pImage = vdGetImageByNumber(pDisk, nImage);
8997 AssertPtrBreakStmt(pImage, rc = VERR_VD_IMAGE_NOT_FOUND);
8998
8999 rc = pImage->Backend->pfnGetUuid(pImage->pBackendData, pUuid);
9000 } while (0);
9001
9002 if (RT_UNLIKELY(fLockRead))
9003 {
9004 rc2 = vdThreadFinishRead(pDisk);
9005 AssertRC(rc2);
9006 }
9007
9008 LogFlowFunc(("returns %Rrc, Uuid={%RTuuid}\n", rc, pUuid));
9009 return rc;
9010}
9011
9012/**
9013 * Set the image's UUID. Should not be used by normal applications.
9014 *
9015 * @returns VBox status code.
9016 * @returns VERR_VD_IMAGE_NOT_FOUND if image with specified number was not opened.
9017 * @param pDisk Pointer to HDD container.
9018 * @param nImage Image number, counts from 0. 0 is always base image of container.
9019 * @param pUuid New UUID of the image. If NULL, a new UUID is created.
9020 */
9021VBOXDDU_DECL(int) VDSetUuid(PVBOXHDD pDisk, unsigned nImage, PCRTUUID pUuid)
9022{
9023 int rc;
9024 int rc2;
9025 bool fLockWrite = false;
9026
9027 LogFlowFunc(("pDisk=%#p nImage=%u pUuid=%#p {%RTuuid}\n",
9028 pDisk, nImage, pUuid, pUuid));
9029 do
9030 {
9031 /* sanity check */
9032 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
9033 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
9034
9035 AssertMsgBreakStmt(VALID_PTR(pUuid) || pUuid == NULL,
9036 ("pUuid=%#p\n", pUuid),
9037 rc = VERR_INVALID_PARAMETER);
9038
9039 rc2 = vdThreadStartWrite(pDisk);
9040 AssertRC(rc2);
9041 fLockWrite = true;
9042
9043 PVDIMAGE pImage = vdGetImageByNumber(pDisk, nImage);
9044 AssertPtrBreakStmt(pImage, rc = VERR_VD_IMAGE_NOT_FOUND);
9045
9046 RTUUID Uuid;
9047 if (!pUuid)
9048 {
9049 RTUuidCreate(&Uuid);
9050 pUuid = &Uuid;
9051 }
9052 rc = pImage->Backend->pfnSetUuid(pImage->pBackendData, pUuid);
9053 } while (0);
9054
9055 if (RT_UNLIKELY(fLockWrite))
9056 {
9057 rc2 = vdThreadFinishWrite(pDisk);
9058 AssertRC(rc2);
9059 }
9060
9061 LogFlowFunc(("returns %Rrc\n", rc));
9062 return rc;
9063}
9064
9065/**
9066 * Get last modification UUID of image in HDD container.
9067 *
9068 * @returns VBox status code.
9069 * @returns VERR_VD_IMAGE_NOT_FOUND if image with specified number was not opened.
9070 * @param pDisk Pointer to HDD container.
9071 * @param nImage Image number, counts from 0. 0 is always base image of container.
9072 * @param pUuid Where to store the image modification UUID.
9073 */
9074VBOXDDU_DECL(int) VDGetModificationUuid(PVBOXHDD pDisk, unsigned nImage, PRTUUID pUuid)
9075{
9076 int rc = VINF_SUCCESS;
9077 int rc2;
9078 bool fLockRead = false;
9079
9080 LogFlowFunc(("pDisk=%#p nImage=%u pUuid=%#p\n", pDisk, nImage, pUuid));
9081 do
9082 {
9083 /* sanity check */
9084 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
9085 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
9086
9087 /* Check arguments. */
9088 AssertMsgBreakStmt(VALID_PTR(pUuid),
9089 ("pUuid=%#p\n", pUuid),
9090 rc = VERR_INVALID_PARAMETER);
9091
9092 rc2 = vdThreadStartRead(pDisk);
9093 AssertRC(rc2);
9094 fLockRead = true;
9095
9096 PVDIMAGE pImage = vdGetImageByNumber(pDisk, nImage);
9097 AssertPtrBreakStmt(pImage, rc = VERR_VD_IMAGE_NOT_FOUND);
9098
9099 rc = pImage->Backend->pfnGetModificationUuid(pImage->pBackendData,
9100 pUuid);
9101 } while (0);
9102
9103 if (RT_UNLIKELY(fLockRead))
9104 {
9105 rc2 = vdThreadFinishRead(pDisk);
9106 AssertRC(rc2);
9107 }
9108
9109 LogFlowFunc(("returns %Rrc, Uuid={%RTuuid}\n", rc, pUuid));
9110 return rc;
9111}
9112
9113/**
9114 * Set the image's last modification UUID. Should not be used by normal applications.
9115 *
9116 * @returns VBox status code.
9117 * @returns VERR_VD_IMAGE_NOT_FOUND if image with specified number was not opened.
9118 * @param pDisk Pointer to HDD container.
9119 * @param nImage Image number, counts from 0. 0 is always base image of container.
9120 * @param pUuid New modification UUID of the image. If NULL, a new UUID is created.
9121 */
9122VBOXDDU_DECL(int) VDSetModificationUuid(PVBOXHDD pDisk, unsigned nImage, PCRTUUID pUuid)
9123{
9124 int rc;
9125 int rc2;
9126 bool fLockWrite = false;
9127
9128 LogFlowFunc(("pDisk=%#p nImage=%u pUuid=%#p {%RTuuid}\n",
9129 pDisk, nImage, pUuid, pUuid));
9130 do
9131 {
9132 /* sanity check */
9133 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
9134 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
9135
9136 /* Check arguments. */
9137 AssertMsgBreakStmt(VALID_PTR(pUuid) || pUuid == NULL,
9138 ("pUuid=%#p\n", pUuid),
9139 rc = VERR_INVALID_PARAMETER);
9140
9141 rc2 = vdThreadStartWrite(pDisk);
9142 AssertRC(rc2);
9143 fLockWrite = true;
9144
9145 PVDIMAGE pImage = vdGetImageByNumber(pDisk, nImage);
9146 AssertPtrBreakStmt(pImage, rc = VERR_VD_IMAGE_NOT_FOUND);
9147
9148 RTUUID Uuid;
9149 if (!pUuid)
9150 {
9151 RTUuidCreate(&Uuid);
9152 pUuid = &Uuid;
9153 }
9154 rc = pImage->Backend->pfnSetModificationUuid(pImage->pBackendData,
9155 pUuid);
9156 } while (0);
9157
9158 if (RT_UNLIKELY(fLockWrite))
9159 {
9160 rc2 = vdThreadFinishWrite(pDisk);
9161 AssertRC(rc2);
9162 }
9163
9164 LogFlowFunc(("returns %Rrc\n", rc));
9165 return rc;
9166}
9167
9168/**
9169 * Get parent UUID of image in HDD container.
9170 *
9171 * @returns VBox status code.
9172 * @returns VERR_VD_IMAGE_NOT_FOUND if image with specified number was not opened.
9173 * @param pDisk Pointer to HDD container.
9174 * @param nImage Image number, counts from 0. 0 is always base image of container.
9175 * @param pUuid Where to store the parent image UUID.
9176 */
9177VBOXDDU_DECL(int) VDGetParentUuid(PVBOXHDD pDisk, unsigned nImage,
9178 PRTUUID pUuid)
9179{
9180 int rc = VINF_SUCCESS;
9181 int rc2;
9182 bool fLockRead = false;
9183
9184 LogFlowFunc(("pDisk=%#p nImage=%u pUuid=%#p\n", pDisk, nImage, pUuid));
9185 do
9186 {
9187 /* sanity check */
9188 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
9189 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
9190
9191 /* Check arguments. */
9192 AssertMsgBreakStmt(VALID_PTR(pUuid),
9193 ("pUuid=%#p\n", pUuid),
9194 rc = VERR_INVALID_PARAMETER);
9195
9196 rc2 = vdThreadStartRead(pDisk);
9197 AssertRC(rc2);
9198 fLockRead = true;
9199
9200 PVDIMAGE pImage = vdGetImageByNumber(pDisk, nImage);
9201 AssertPtrBreakStmt(pImage, rc = VERR_VD_IMAGE_NOT_FOUND);
9202
9203 rc = pImage->Backend->pfnGetParentUuid(pImage->pBackendData, pUuid);
9204 } while (0);
9205
9206 if (RT_UNLIKELY(fLockRead))
9207 {
9208 rc2 = vdThreadFinishRead(pDisk);
9209 AssertRC(rc2);
9210 }
9211
9212 LogFlowFunc(("returns %Rrc, Uuid={%RTuuid}\n", rc, pUuid));
9213 return rc;
9214}
9215
9216/**
9217 * Set the image's parent UUID. Should not be used by normal applications.
9218 *
9219 * @returns VBox status code.
9220 * @param pDisk Pointer to HDD container.
9221 * @param nImage Image number, counts from 0. 0 is always base image of container.
9222 * @param pUuid New parent UUID of the image. If NULL, a new UUID is created.
9223 */
9224VBOXDDU_DECL(int) VDSetParentUuid(PVBOXHDD pDisk, unsigned nImage,
9225 PCRTUUID pUuid)
9226{
9227 int rc;
9228 int rc2;
9229 bool fLockWrite = false;
9230
9231 LogFlowFunc(("pDisk=%#p nImage=%u pUuid=%#p {%RTuuid}\n",
9232 pDisk, nImage, pUuid, pUuid));
9233 do
9234 {
9235 /* sanity check */
9236 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
9237 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
9238
9239 /* Check arguments. */
9240 AssertMsgBreakStmt(VALID_PTR(pUuid) || pUuid == NULL,
9241 ("pUuid=%#p\n", pUuid),
9242 rc = VERR_INVALID_PARAMETER);
9243
9244 rc2 = vdThreadStartWrite(pDisk);
9245 AssertRC(rc2);
9246 fLockWrite = true;
9247
9248 PVDIMAGE pImage = vdGetImageByNumber(pDisk, nImage);
9249 AssertPtrBreakStmt(pImage, rc = VERR_VD_IMAGE_NOT_FOUND);
9250
9251 RTUUID Uuid;
9252 if (!pUuid)
9253 {
9254 RTUuidCreate(&Uuid);
9255 pUuid = &Uuid;
9256 }
9257 rc = pImage->Backend->pfnSetParentUuid(pImage->pBackendData, pUuid);
9258 } while (0);
9259
9260 if (RT_UNLIKELY(fLockWrite))
9261 {
9262 rc2 = vdThreadFinishWrite(pDisk);
9263 AssertRC(rc2);
9264 }
9265
9266 LogFlowFunc(("returns %Rrc\n", rc));
9267 return rc;
9268}
9269
9270
9271/**
9272 * Debug helper - dumps all opened images in HDD container into the log file.
9273 *
9274 * @param pDisk Pointer to HDD container.
9275 */
9276VBOXDDU_DECL(void) VDDumpImages(PVBOXHDD pDisk)
9277{
9278 int rc2;
9279 bool fLockRead = false;
9280
9281 do
9282 {
9283 /* sanity check */
9284 AssertPtrBreak(pDisk);
9285 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
9286
9287 if (!pDisk->pInterfaceError || !VALID_PTR(pDisk->pInterfaceError->pfnMessage))
9288 pDisk->pInterfaceError->pfnMessage = vdLogMessage;
9289
9290 rc2 = vdThreadStartRead(pDisk);
9291 AssertRC(rc2);
9292 fLockRead = true;
9293
9294 vdMessageWrapper(pDisk, "--- Dumping VD Disk, Images=%u\n", pDisk->cImages);
9295 for (PVDIMAGE pImage = pDisk->pBase; pImage; pImage = pImage->pNext)
9296 {
9297 vdMessageWrapper(pDisk, "Dumping VD image \"%s\" (Backend=%s)\n",
9298 pImage->pszFilename, pImage->Backend->pszBackendName);
9299 pImage->Backend->pfnDump(pImage->pBackendData);
9300 }
9301 } while (0);
9302
9303 if (RT_UNLIKELY(fLockRead))
9304 {
9305 rc2 = vdThreadFinishRead(pDisk);
9306 AssertRC(rc2);
9307 }
9308}
9309
9310
9311VBOXDDU_DECL(int) VDDiscardRanges(PVBOXHDD pDisk, PCRTRANGE paRanges, unsigned cRanges)
9312{
9313 int rc;
9314 int rc2;
9315 bool fLockWrite = false;
9316
9317 LogFlowFunc(("pDisk=%#p paRanges=%#p cRanges=%u\n",
9318 pDisk, paRanges, cRanges));
9319 do
9320 {
9321 /* sanity check */
9322 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
9323 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
9324
9325 /* Check arguments. */
9326 AssertMsgBreakStmt(cRanges,
9327 ("cRanges=%u\n", cRanges),
9328 rc = VERR_INVALID_PARAMETER);
9329 AssertMsgBreakStmt(VALID_PTR(paRanges),
9330 ("paRanges=%#p\n", paRanges),
9331 rc = VERR_INVALID_PARAMETER);
9332
9333 rc2 = vdThreadStartWrite(pDisk);
9334 AssertRC(rc2);
9335 fLockWrite = true;
9336
9337 AssertPtrBreakStmt(pDisk->pLast, rc = VERR_VD_NOT_OPENED);
9338
9339 AssertMsgBreakStmt(pDisk->pLast->uOpenFlags & VD_OPEN_FLAGS_DISCARD,
9340 ("Discarding not supported\n"),
9341 rc = VERR_NOT_SUPPORTED);
9342
9343 vdSetModifiedFlag(pDisk);
9344 rc = vdDiscardHelper(pDisk, paRanges, cRanges);
9345 } while (0);
9346
9347 if (RT_UNLIKELY(fLockWrite))
9348 {
9349 rc2 = vdThreadFinishWrite(pDisk);
9350 AssertRC(rc2);
9351 }
9352
9353 LogFlowFunc(("returns %Rrc\n", rc));
9354 return rc;
9355}
9356
9357
9358VBOXDDU_DECL(int) VDAsyncRead(PVBOXHDD pDisk, uint64_t uOffset, size_t cbRead,
9359 PCRTSGBUF pcSgBuf,
9360 PFNVDASYNCTRANSFERCOMPLETE pfnComplete,
9361 void *pvUser1, void *pvUser2)
9362{
9363 int rc = VERR_VD_BLOCK_FREE;
9364 int rc2;
9365 bool fLockRead = false;
9366 PVDIOCTX pIoCtx = NULL;
9367
9368 LogFlowFunc(("pDisk=%#p uOffset=%llu pcSgBuf=%#p cbRead=%zu pvUser1=%#p pvUser2=%#p\n",
9369 pDisk, uOffset, pcSgBuf, cbRead, pvUser1, pvUser2));
9370
9371 do
9372 {
9373 /* sanity check */
9374 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
9375 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
9376
9377 /* Check arguments. */
9378 AssertMsgBreakStmt(cbRead,
9379 ("cbRead=%zu\n", cbRead),
9380 rc = VERR_INVALID_PARAMETER);
9381 AssertMsgBreakStmt(VALID_PTR(pcSgBuf),
9382 ("pcSgBuf=%#p\n", pcSgBuf),
9383 rc = VERR_INVALID_PARAMETER);
9384
9385 rc2 = vdThreadStartRead(pDisk);
9386 AssertRC(rc2);
9387 fLockRead = true;
9388
9389 AssertMsgBreakStmt(uOffset + cbRead <= pDisk->cbSize,
9390 ("uOffset=%llu cbRead=%zu pDisk->cbSize=%llu\n",
9391 uOffset, cbRead, pDisk->cbSize),
9392 rc = VERR_INVALID_PARAMETER);
9393 AssertPtrBreakStmt(pDisk->pLast, rc = VERR_VD_NOT_OPENED);
9394
9395 pIoCtx = vdIoCtxRootAlloc(pDisk, VDIOCTXTXDIR_READ, uOffset,
9396 cbRead, pDisk->pLast, pcSgBuf,
9397 pfnComplete, pvUser1, pvUser2,
9398 NULL, vdReadHelperAsync);
9399 if (!pIoCtx)
9400 {
9401 rc = VERR_NO_MEMORY;
9402 break;
9403 }
9404
9405#if 0
9406 rc = vdIoCtxProcessTryLockDefer(pIoCtx);
9407#else
9408 rc = vdIoCtxProcess(pIoCtx);
9409#endif
9410 if (rc == VINF_VD_ASYNC_IO_FINISHED)
9411 {
9412 if (ASMAtomicCmpXchgBool(&pIoCtx->fComplete, true, false))
9413 vdIoCtxFree(pDisk, pIoCtx);
9414 else
9415 rc = VERR_VD_ASYNC_IO_IN_PROGRESS; /* Let the other handler complete the request. */
9416 }
9417 else if (rc != VERR_VD_ASYNC_IO_IN_PROGRESS) /* Another error */
9418 vdIoCtxFree(pDisk, pIoCtx);
9419
9420 } while (0);
9421
9422 if (RT_UNLIKELY(fLockRead) && ( rc == VINF_VD_ASYNC_IO_FINISHED
9423 || rc != VERR_VD_ASYNC_IO_IN_PROGRESS))
9424 {
9425 rc2 = vdThreadFinishRead(pDisk);
9426 AssertRC(rc2);
9427 }
9428
9429 LogFlowFunc(("returns %Rrc\n", rc));
9430 return rc;
9431}
9432
9433
9434VBOXDDU_DECL(int) VDAsyncWrite(PVBOXHDD pDisk, uint64_t uOffset, size_t cbWrite,
9435 PCRTSGBUF pcSgBuf,
9436 PFNVDASYNCTRANSFERCOMPLETE pfnComplete,
9437 void *pvUser1, void *pvUser2)
9438{
9439 int rc;
9440 int rc2;
9441 bool fLockWrite = false;
9442 PVDIOCTX pIoCtx = NULL;
9443
9444 LogFlowFunc(("pDisk=%#p uOffset=%llu cSgBuf=%#p cbWrite=%zu pvUser1=%#p pvUser2=%#p\n",
9445 pDisk, uOffset, pcSgBuf, cbWrite, pvUser1, pvUser2));
9446 do
9447 {
9448 /* sanity check */
9449 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
9450 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
9451
9452 /* Check arguments. */
9453 AssertMsgBreakStmt(cbWrite,
9454 ("cbWrite=%zu\n", cbWrite),
9455 rc = VERR_INVALID_PARAMETER);
9456 AssertMsgBreakStmt(VALID_PTR(pcSgBuf),
9457 ("pcSgBuf=%#p\n", pcSgBuf),
9458 rc = VERR_INVALID_PARAMETER);
9459
9460 rc2 = vdThreadStartWrite(pDisk);
9461 AssertRC(rc2);
9462 fLockWrite = true;
9463
9464 AssertMsgBreakStmt(uOffset + cbWrite <= pDisk->cbSize,
9465 ("uOffset=%llu cbWrite=%zu pDisk->cbSize=%llu\n",
9466 uOffset, cbWrite, pDisk->cbSize),
9467 rc = VERR_INVALID_PARAMETER);
9468 AssertPtrBreakStmt(pDisk->pLast, rc = VERR_VD_NOT_OPENED);
9469
9470 pIoCtx = vdIoCtxRootAlloc(pDisk, VDIOCTXTXDIR_WRITE, uOffset,
9471 cbWrite, pDisk->pLast, pcSgBuf,
9472 pfnComplete, pvUser1, pvUser2,
9473 NULL, vdWriteHelperAsync);
9474 if (!pIoCtx)
9475 {
9476 rc = VERR_NO_MEMORY;
9477 break;
9478 }
9479
9480#if 0
9481 rc = vdIoCtxProcessTryLockDefer(pIoCtx);
9482#else
9483 rc = vdIoCtxProcess(pIoCtx);
9484#endif
9485 if (rc == VINF_VD_ASYNC_IO_FINISHED)
9486 {
9487 if (ASMAtomicCmpXchgBool(&pIoCtx->fComplete, true, false))
9488 vdIoCtxFree(pDisk, pIoCtx);
9489 else
9490 rc = VERR_VD_ASYNC_IO_IN_PROGRESS; /* Let the other handler complete the request. */
9491 }
9492 else if (rc != VERR_VD_ASYNC_IO_IN_PROGRESS) /* Another error */
9493 vdIoCtxFree(pDisk, pIoCtx);
9494 } while (0);
9495
9496 if (RT_UNLIKELY(fLockWrite) && ( rc == VINF_VD_ASYNC_IO_FINISHED
9497 || rc != VERR_VD_ASYNC_IO_IN_PROGRESS))
9498 {
9499 rc2 = vdThreadFinishWrite(pDisk);
9500 AssertRC(rc2);
9501 }
9502
9503 LogFlowFunc(("returns %Rrc\n", rc));
9504 return rc;
9505}
9506
9507
9508VBOXDDU_DECL(int) VDAsyncFlush(PVBOXHDD pDisk, PFNVDASYNCTRANSFERCOMPLETE pfnComplete,
9509 void *pvUser1, void *pvUser2)
9510{
9511 int rc;
9512 int rc2;
9513 bool fLockWrite = false;
9514 PVDIOCTX pIoCtx = NULL;
9515
9516 LogFlowFunc(("pDisk=%#p\n", pDisk));
9517
9518 do
9519 {
9520 /* sanity check */
9521 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
9522 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
9523
9524 rc2 = vdThreadStartWrite(pDisk);
9525 AssertRC(rc2);
9526 fLockWrite = true;
9527
9528 AssertPtrBreakStmt(pDisk->pLast, rc = VERR_VD_NOT_OPENED);
9529
9530 pIoCtx = vdIoCtxRootAlloc(pDisk, VDIOCTXTXDIR_FLUSH, 0,
9531 0, pDisk->pLast, NULL,
9532 pfnComplete, pvUser1, pvUser2,
9533 NULL, vdFlushHelperAsync);
9534 if (!pIoCtx)
9535 {
9536 rc = VERR_NO_MEMORY;
9537 break;
9538 }
9539
9540#if 0
9541 rc = vdIoCtxProcessTryLockDefer(pIoCtx);
9542#else
9543 rc = vdIoCtxProcess(pIoCtx);
9544#endif
9545 if (rc == VINF_VD_ASYNC_IO_FINISHED)
9546 {
9547 if (ASMAtomicCmpXchgBool(&pIoCtx->fComplete, true, false))
9548 vdIoCtxFree(pDisk, pIoCtx);
9549 else
9550 rc = VERR_VD_ASYNC_IO_IN_PROGRESS; /* Let the other handler complete the request. */
9551 }
9552 else if (rc != VERR_VD_ASYNC_IO_IN_PROGRESS) /* Another error */
9553 vdIoCtxFree(pDisk, pIoCtx);
9554 } while (0);
9555
9556 if (RT_UNLIKELY(fLockWrite) && ( rc == VINF_VD_ASYNC_IO_FINISHED
9557 || rc != VERR_VD_ASYNC_IO_IN_PROGRESS))
9558 {
9559 rc2 = vdThreadFinishWrite(pDisk);
9560 AssertRC(rc2);
9561 }
9562
9563 LogFlowFunc(("returns %Rrc\n", rc));
9564 return rc;
9565}
9566
9567VBOXDDU_DECL(int) VDAsyncDiscardRanges(PVBOXHDD pDisk, PCRTRANGE paRanges, unsigned cRanges,
9568 PFNVDASYNCTRANSFERCOMPLETE pfnComplete,
9569 void *pvUser1, void *pvUser2)
9570{
9571 int rc;
9572 int rc2;
9573 bool fLockWrite = false;
9574 PVDIOCTX pIoCtx = NULL;
9575
9576 LogFlowFunc(("pDisk=%#p\n", pDisk));
9577
9578 do
9579 {
9580 /* sanity check */
9581 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
9582 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
9583
9584 rc2 = vdThreadStartWrite(pDisk);
9585 AssertRC(rc2);
9586 fLockWrite = true;
9587
9588 AssertPtrBreakStmt(pDisk->pLast, rc = VERR_VD_NOT_OPENED);
9589
9590 pIoCtx = vdIoCtxDiscardAlloc(pDisk, paRanges, cRanges,
9591 pfnComplete, pvUser1, pvUser2, NULL,
9592 vdDiscardHelperAsync);
9593 if (!pIoCtx)
9594 {
9595 rc = VERR_NO_MEMORY;
9596 break;
9597 }
9598
9599#if 0
9600 rc = vdIoCtxProcessTryLockDefer(pIoCtx);
9601#else
9602 rc = vdIoCtxProcess(pIoCtx);
9603#endif
9604 if (rc == VINF_VD_ASYNC_IO_FINISHED)
9605 {
9606 if (ASMAtomicCmpXchgBool(&pIoCtx->fComplete, true, false))
9607 vdIoCtxFree(pDisk, pIoCtx);
9608 else
9609 rc = VERR_VD_ASYNC_IO_IN_PROGRESS; /* Let the other handler complete the request. */
9610 }
9611 else if (rc != VERR_VD_ASYNC_IO_IN_PROGRESS) /* Another error */
9612 vdIoCtxFree(pDisk, pIoCtx);
9613 } while (0);
9614
9615 if (RT_UNLIKELY(fLockWrite) && ( rc == VINF_VD_ASYNC_IO_FINISHED
9616 || rc != VERR_VD_ASYNC_IO_IN_PROGRESS))
9617 {
9618 rc2 = vdThreadFinishWrite(pDisk);
9619 AssertRC(rc2);
9620 }
9621
9622 LogFlowFunc(("returns %Rrc\n", rc));
9623 return rc;
9624}
9625
9626VBOXDDU_DECL(int) VDRepair(PVDINTERFACE pVDIfsDisk, PVDINTERFACE pVDIfsImage,
9627 const char *pszFilename, const char *pszBackend,
9628 uint32_t fFlags)
9629{
9630 int rc = VERR_NOT_SUPPORTED;
9631 PCVBOXHDDBACKEND pBackend = NULL;
9632 VDINTERFACEIOINT VDIfIoInt;
9633 VDINTERFACEIO VDIfIoFallback;
9634 PVDINTERFACEIO pInterfaceIo;
9635
9636 LogFlowFunc(("pszFilename=\"%s\"\n", pszFilename));
9637 /* Check arguments. */
9638 AssertMsgReturn(VALID_PTR(pszFilename) && *pszFilename,
9639 ("pszFilename=%#p \"%s\"\n", pszFilename, pszFilename),
9640 VERR_INVALID_PARAMETER);
9641 AssertMsgReturn(VALID_PTR(pszBackend),
9642 ("pszBackend=%#p\n", pszBackend),
9643 VERR_INVALID_PARAMETER);
9644 AssertMsgReturn((fFlags & ~VD_REPAIR_FLAGS_MASK) == 0,
9645 ("fFlags=%#x\n", fFlags),
9646 VERR_INVALID_PARAMETER);
9647
9648 pInterfaceIo = VDIfIoGet(pVDIfsImage);
9649 if (!pInterfaceIo)
9650 {
9651 /*
9652 * Caller doesn't provide an I/O interface, create our own using the
9653 * native file API.
9654 */
9655 vdIfIoFallbackCallbacksSetup(&VDIfIoFallback);
9656 pInterfaceIo = &VDIfIoFallback;
9657 }
9658
9659 /* Set up the internal I/O interface. */
9660 AssertReturn(!VDIfIoIntGet(pVDIfsImage), VERR_INVALID_PARAMETER);
9661 VDIfIoInt.pfnOpen = vdIOIntOpenLimited;
9662 VDIfIoInt.pfnClose = vdIOIntCloseLimited;
9663 VDIfIoInt.pfnDelete = vdIOIntDeleteLimited;
9664 VDIfIoInt.pfnMove = vdIOIntMoveLimited;
9665 VDIfIoInt.pfnGetFreeSpace = vdIOIntGetFreeSpaceLimited;
9666 VDIfIoInt.pfnGetModificationTime = vdIOIntGetModificationTimeLimited;
9667 VDIfIoInt.pfnGetSize = vdIOIntGetSizeLimited;
9668 VDIfIoInt.pfnSetSize = vdIOIntSetSizeLimited;
9669 VDIfIoInt.pfnReadSync = vdIOIntReadSyncLimited;
9670 VDIfIoInt.pfnWriteSync = vdIOIntWriteSyncLimited;
9671 VDIfIoInt.pfnFlushSync = vdIOIntFlushSyncLimited;
9672 VDIfIoInt.pfnReadUserAsync = NULL;
9673 VDIfIoInt.pfnWriteUserAsync = NULL;
9674 VDIfIoInt.pfnReadMetaAsync = NULL;
9675 VDIfIoInt.pfnWriteMetaAsync = NULL;
9676 VDIfIoInt.pfnFlushAsync = NULL;
9677 rc = VDInterfaceAdd(&VDIfIoInt.Core, "VD_IOINT", VDINTERFACETYPE_IOINT,
9678 pInterfaceIo, sizeof(VDINTERFACEIOINT), &pVDIfsImage);
9679 AssertRC(rc);
9680
9681 rc = vdFindBackend(pszBackend, &pBackend);
9682 if (RT_SUCCESS(rc))
9683 {
9684 if (pBackend->pfnRepair)
9685 rc = pBackend->pfnRepair(pszFilename, pVDIfsDisk, pVDIfsImage, fFlags);
9686 else
9687 rc = VERR_VD_IMAGE_REPAIR_NOT_SUPPORTED;
9688 }
9689
9690 LogFlowFunc(("returns %Rrc\n", rc));
9691 return rc;
9692}
9693
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