VirtualBox

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

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

VD: Update size field after a successful resize operation

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 344.1 KB
Line 
1/* $Id: VD.cpp 44226 2013-01-02 12:05:47Z 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 uOpenFlags &= ~VD_OPEN_FLAGS_READONLY;
6656 rc = pImageTo->Backend->pfnSetOpenFlags(pImageTo->pBackendData,
6657 uOpenFlags);
6658 if (RT_FAILURE(rc))
6659 break;
6660 }
6661
6662 /* Get size of destination image. */
6663 uint64_t cbSize = pImageTo->Backend->pfnGetSize(pImageTo->pBackendData);
6664 rc2 = vdThreadFinishWrite(pDisk);
6665 AssertRC(rc2);
6666 fLockWrite = false;
6667
6668 /* Allocate tmp buffer. */
6669 pvBuf = RTMemTmpAlloc(VD_MERGE_BUFFER_SIZE);
6670 if (!pvBuf)
6671 {
6672 rc = VERR_NO_MEMORY;
6673 break;
6674 }
6675
6676 /* Merging is done directly on the images itself. This potentially
6677 * causes trouble if the disk is full in the middle of operation. */
6678 if (nImageFrom < nImageTo)
6679 {
6680 /* Merge parent state into child. This means writing all not
6681 * allocated blocks in the destination image which are allocated in
6682 * the images to be merged. */
6683 uint64_t uOffset = 0;
6684 uint64_t cbRemaining = cbSize;
6685 do
6686 {
6687 size_t cbThisRead = RT_MIN(VD_MERGE_BUFFER_SIZE, cbRemaining);
6688
6689 /* Need to hold the write lock during a read-write operation. */
6690 rc2 = vdThreadStartWrite(pDisk);
6691 AssertRC(rc2);
6692 fLockWrite = true;
6693
6694 rc = pImageTo->Backend->pfnRead(pImageTo->pBackendData,
6695 uOffset, pvBuf, cbThisRead,
6696 &cbThisRead);
6697 if (rc == VERR_VD_BLOCK_FREE)
6698 {
6699 /* Search for image with allocated block. Do not attempt to
6700 * read more than the previous reads marked as valid.
6701 * Otherwise this would return stale data when different
6702 * block sizes are used for the images. */
6703 for (PVDIMAGE pCurrImage = pImageTo->pPrev;
6704 pCurrImage != NULL && pCurrImage != pImageFrom->pPrev && rc == VERR_VD_BLOCK_FREE;
6705 pCurrImage = pCurrImage->pPrev)
6706 {
6707 rc = pCurrImage->Backend->pfnRead(pCurrImage->pBackendData,
6708 uOffset, pvBuf,
6709 cbThisRead,
6710 &cbThisRead);
6711 }
6712
6713 if (rc != VERR_VD_BLOCK_FREE)
6714 {
6715 if (RT_FAILURE(rc))
6716 break;
6717 /* Updating the cache is required because this might be a live merge. */
6718 rc = vdWriteHelperEx(pDisk, pImageTo, pImageFrom->pPrev,
6719 uOffset, pvBuf, cbThisRead,
6720 true /* fUpdateCache */, 0);
6721 if (RT_FAILURE(rc))
6722 break;
6723 }
6724 else
6725 rc = VINF_SUCCESS;
6726 }
6727 else if (RT_FAILURE(rc))
6728 break;
6729
6730 rc2 = vdThreadFinishWrite(pDisk);
6731 AssertRC(rc2);
6732 fLockWrite = false;
6733
6734 uOffset += cbThisRead;
6735 cbRemaining -= cbThisRead;
6736
6737 if (pIfProgress && pIfProgress->pfnProgress)
6738 {
6739 /** @todo r=klaus: this can update the progress to the same
6740 * percentage over and over again if the image format makes
6741 * relatively small increments. */
6742 rc = pIfProgress->pfnProgress(pIfProgress->Core.pvUser,
6743 uOffset * 99 / cbSize);
6744 if (RT_FAILURE(rc))
6745 break;
6746 }
6747 } while (uOffset < cbSize);
6748 }
6749 else
6750 {
6751 /*
6752 * We may need to update the parent uuid of the child coming after
6753 * the last image to be merged. We have to reopen it read/write.
6754 *
6755 * This is done before we do the actual merge to prevent an
6756 * inconsistent chain if the mode change fails for some reason.
6757 */
6758 if (pImageFrom->pNext)
6759 {
6760 PVDIMAGE pImageChild = pImageFrom->pNext;
6761
6762 /* Take the write lock. */
6763 rc2 = vdThreadStartWrite(pDisk);
6764 AssertRC(rc2);
6765 fLockWrite = true;
6766
6767 /* We need to open the image in read/write mode. */
6768 uOpenFlags = pImageChild->Backend->pfnGetOpenFlags(pImageChild->pBackendData);
6769
6770 if (uOpenFlags & VD_OPEN_FLAGS_READONLY)
6771 {
6772 uOpenFlags &= ~VD_OPEN_FLAGS_READONLY;
6773 rc = pImageChild->Backend->pfnSetOpenFlags(pImageChild->pBackendData,
6774 uOpenFlags);
6775 if (RT_FAILURE(rc))
6776 break;
6777 }
6778
6779 rc2 = vdThreadFinishWrite(pDisk);
6780 AssertRC(rc2);
6781 fLockWrite = false;
6782 }
6783
6784 /* If the merge is from the last image we have to relay all writes
6785 * to the merge destination as well, so that concurrent writes
6786 * (in case of a live merge) are handled correctly. */
6787 if (!pImageFrom->pNext)
6788 {
6789 /* Take the write lock. */
6790 rc2 = vdThreadStartWrite(pDisk);
6791 AssertRC(rc2);
6792 fLockWrite = true;
6793
6794 pDisk->pImageRelay = pImageTo;
6795
6796 rc2 = vdThreadFinishWrite(pDisk);
6797 AssertRC(rc2);
6798 fLockWrite = false;
6799 }
6800
6801 /* Merge child state into parent. This means writing all blocks
6802 * which are allocated in the image up to the source image to the
6803 * destination image. */
6804 uint64_t uOffset = 0;
6805 uint64_t cbRemaining = cbSize;
6806 do
6807 {
6808 size_t cbThisRead = RT_MIN(VD_MERGE_BUFFER_SIZE, cbRemaining);
6809 rc = VERR_VD_BLOCK_FREE;
6810
6811 /* Need to hold the write lock during a read-write operation. */
6812 rc2 = vdThreadStartWrite(pDisk);
6813 AssertRC(rc2);
6814 fLockWrite = true;
6815
6816 /* Search for image with allocated block. Do not attempt to
6817 * read more than the previous reads marked as valid. Otherwise
6818 * this would return stale data when different block sizes are
6819 * used for the images. */
6820 for (PVDIMAGE pCurrImage = pImageFrom;
6821 pCurrImage != NULL && pCurrImage != pImageTo && rc == VERR_VD_BLOCK_FREE;
6822 pCurrImage = pCurrImage->pPrev)
6823 {
6824 rc = pCurrImage->Backend->pfnRead(pCurrImage->pBackendData,
6825 uOffset, pvBuf,
6826 cbThisRead, &cbThisRead);
6827 }
6828
6829 if (rc != VERR_VD_BLOCK_FREE)
6830 {
6831 if (RT_FAILURE(rc))
6832 break;
6833 rc = vdWriteHelper(pDisk, pImageTo, uOffset, pvBuf,
6834 cbThisRead, true /* fUpdateCache */);
6835 if (RT_FAILURE(rc))
6836 break;
6837 }
6838 else
6839 rc = VINF_SUCCESS;
6840
6841 rc2 = vdThreadFinishWrite(pDisk);
6842 AssertRC(rc2);
6843 fLockWrite = false;
6844
6845 uOffset += cbThisRead;
6846 cbRemaining -= cbThisRead;
6847
6848 if (pIfProgress && pIfProgress->pfnProgress)
6849 {
6850 /** @todo r=klaus: this can update the progress to the same
6851 * percentage over and over again if the image format makes
6852 * relatively small increments. */
6853 rc = pIfProgress->pfnProgress(pIfProgress->Core.pvUser,
6854 uOffset * 99 / cbSize);
6855 if (RT_FAILURE(rc))
6856 break;
6857 }
6858 } while (uOffset < cbSize);
6859
6860 /* In case we set up a "write proxy" image above we must clear
6861 * this again now to prevent stray writes. Failure or not. */
6862 if (!pImageFrom->pNext)
6863 {
6864 /* Take the write lock. */
6865 rc2 = vdThreadStartWrite(pDisk);
6866 AssertRC(rc2);
6867 fLockWrite = true;
6868
6869 pDisk->pImageRelay = NULL;
6870
6871 rc2 = vdThreadFinishWrite(pDisk);
6872 AssertRC(rc2);
6873 fLockWrite = false;
6874 }
6875 }
6876
6877 /*
6878 * Leave in case of an error to avoid corrupted data in the image chain
6879 * (includes cancelling the operation by the user).
6880 */
6881 if (RT_FAILURE(rc))
6882 break;
6883
6884 /* Need to hold the write lock while finishing the merge. */
6885 rc2 = vdThreadStartWrite(pDisk);
6886 AssertRC(rc2);
6887 fLockWrite = true;
6888
6889 /* Update parent UUID so that image chain is consistent.
6890 * The two attempts work around the problem that some backends
6891 * (e.g. iSCSI) do not support UUIDs, so we exploit the fact that
6892 * so far there can only be one such image in the chain. */
6893 /** @todo needs a better long-term solution, passing the UUID
6894 * knowledge from the caller or some such */
6895 RTUUID Uuid;
6896 PVDIMAGE pImageChild = NULL;
6897 if (nImageFrom < nImageTo)
6898 {
6899 if (pImageFrom->pPrev)
6900 {
6901 /* plan A: ask the parent itself for its UUID */
6902 rc = pImageFrom->pPrev->Backend->pfnGetUuid(pImageFrom->pPrev->pBackendData,
6903 &Uuid);
6904 if (RT_FAILURE(rc))
6905 {
6906 /* plan B: ask the child of the parent for parent UUID */
6907 rc = pImageFrom->Backend->pfnGetParentUuid(pImageFrom->pBackendData,
6908 &Uuid);
6909 }
6910 AssertRC(rc);
6911 }
6912 else
6913 RTUuidClear(&Uuid);
6914 rc = pImageTo->Backend->pfnSetParentUuid(pImageTo->pBackendData,
6915 &Uuid);
6916 AssertRC(rc);
6917 }
6918 else
6919 {
6920 /* Update the parent uuid of the child of the last merged image. */
6921 if (pImageFrom->pNext)
6922 {
6923 /* plan A: ask the parent itself for its UUID */
6924 rc = pImageTo->Backend->pfnGetUuid(pImageTo->pBackendData,
6925 &Uuid);
6926 if (RT_FAILURE(rc))
6927 {
6928 /* plan B: ask the child of the parent for parent UUID */
6929 rc = pImageTo->pNext->Backend->pfnGetParentUuid(pImageTo->pNext->pBackendData,
6930 &Uuid);
6931 }
6932 AssertRC(rc);
6933
6934 rc = pImageFrom->Backend->pfnSetParentUuid(pImageFrom->pNext->pBackendData,
6935 &Uuid);
6936 AssertRC(rc);
6937
6938 pImageChild = pImageFrom->pNext;
6939 }
6940 }
6941
6942 /* Delete the no longer needed images. */
6943 PVDIMAGE pImg = pImageFrom, pTmp;
6944 while (pImg != pImageTo)
6945 {
6946 if (nImageFrom < nImageTo)
6947 pTmp = pImg->pNext;
6948 else
6949 pTmp = pImg->pPrev;
6950 vdRemoveImageFromList(pDisk, pImg);
6951 pImg->Backend->pfnClose(pImg->pBackendData, true);
6952 RTMemFree(pImg->pszFilename);
6953 RTMemFree(pImg);
6954 pImg = pTmp;
6955 }
6956
6957 /* Make sure destination image is back to read only if necessary. */
6958 if (pImageTo != pDisk->pLast)
6959 {
6960 uOpenFlags = pImageTo->Backend->pfnGetOpenFlags(pImageTo->pBackendData);
6961 uOpenFlags |= VD_OPEN_FLAGS_READONLY;
6962 rc = pImageTo->Backend->pfnSetOpenFlags(pImageTo->pBackendData,
6963 uOpenFlags);
6964 if (RT_FAILURE(rc))
6965 break;
6966 }
6967
6968 /*
6969 * Make sure the child is readonly
6970 * for the child -> parent merge direction
6971 * if necessary.
6972 */
6973 if ( nImageFrom > nImageTo
6974 && pImageChild
6975 && pImageChild != pDisk->pLast)
6976 {
6977 uOpenFlags = pImageChild->Backend->pfnGetOpenFlags(pImageChild->pBackendData);
6978 uOpenFlags |= VD_OPEN_FLAGS_READONLY;
6979 rc = pImageChild->Backend->pfnSetOpenFlags(pImageChild->pBackendData,
6980 uOpenFlags);
6981 if (RT_FAILURE(rc))
6982 break;
6983 }
6984 } while (0);
6985
6986 if (RT_UNLIKELY(fLockWrite))
6987 {
6988 rc2 = vdThreadFinishWrite(pDisk);
6989 AssertRC(rc2);
6990 }
6991 else if (RT_UNLIKELY(fLockRead))
6992 {
6993 rc2 = vdThreadFinishRead(pDisk);
6994 AssertRC(rc2);
6995 }
6996
6997 if (pvBuf)
6998 RTMemTmpFree(pvBuf);
6999
7000 if (RT_SUCCESS(rc) && pIfProgress && pIfProgress->pfnProgress)
7001 pIfProgress->pfnProgress(pIfProgress->Core.pvUser, 100);
7002
7003 LogFlowFunc(("returns %Rrc\n", rc));
7004 return rc;
7005}
7006
7007/**
7008 * Copies an image from one HDD container to another - extended version.
7009 * The copy is opened in the target HDD container.
7010 * It is possible to convert between different image formats, because the
7011 * backend for the destination may be different from the source.
7012 * If both the source and destination reference the same HDD container,
7013 * then the image is moved (by copying/deleting or renaming) to the new location.
7014 * The source container is unchanged if the move operation fails, otherwise
7015 * the image at the new location is opened in the same way as the old one was.
7016 *
7017 * @note The read/write accesses across disks are not synchronized, just the
7018 * accesses to each disk. Once there is a use case which requires a defined
7019 * read/write behavior in this situation this needs to be extended.
7020 *
7021 * @return VBox status code.
7022 * @return VERR_VD_IMAGE_NOT_FOUND if image with specified number was not opened.
7023 * @param pDiskFrom Pointer to source HDD container.
7024 * @param nImage Image number, counts from 0. 0 is always base image of container.
7025 * @param pDiskTo Pointer to destination HDD container.
7026 * @param pszBackend Name of the image file backend to use (may be NULL to use the same as the source, case insensitive).
7027 * @param pszFilename New name of the image (may be NULL to specify that the
7028 * copy destination is the destination container, or
7029 * if pDiskFrom == pDiskTo, i.e. when moving).
7030 * @param fMoveByRename If true, attempt to perform a move by renaming (if successful the new size is ignored).
7031 * @param cbSize New image size (0 means leave unchanged).
7032 * @param nImageSameFrom todo
7033 * @param nImageSameTo todo
7034 * @param uImageFlags Flags specifying special destination image features.
7035 * @param pDstUuid New UUID of the destination image. If NULL, a new UUID is created.
7036 * This parameter is used if and only if a true copy is created.
7037 * In all rename/move cases or copy to existing image cases the modification UUIDs are copied over.
7038 * @param uOpenFlags Image file open mode, see VD_OPEN_FLAGS_* constants.
7039 * Only used if the destination image is created.
7040 * @param pVDIfsOperation Pointer to the per-operation VD interface list.
7041 * @param pDstVDIfsImage Pointer to the per-image VD interface list, for the
7042 * destination image.
7043 * @param pDstVDIfsOperation Pointer to the per-operation VD interface list,
7044 * for the destination operation.
7045 */
7046VBOXDDU_DECL(int) VDCopyEx(PVBOXHDD pDiskFrom, unsigned nImage, PVBOXHDD pDiskTo,
7047 const char *pszBackend, const char *pszFilename,
7048 bool fMoveByRename, uint64_t cbSize,
7049 unsigned nImageFromSame, unsigned nImageToSame,
7050 unsigned uImageFlags, PCRTUUID pDstUuid,
7051 unsigned uOpenFlags, PVDINTERFACE pVDIfsOperation,
7052 PVDINTERFACE pDstVDIfsImage,
7053 PVDINTERFACE pDstVDIfsOperation)
7054{
7055 int rc = VINF_SUCCESS;
7056 int rc2;
7057 bool fLockReadFrom = false, fLockWriteFrom = false, fLockWriteTo = false;
7058 PVDIMAGE pImageTo = NULL;
7059
7060 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",
7061 pDiskFrom, nImage, pDiskTo, pszBackend, pszFilename, fMoveByRename, cbSize, nImageFromSame, nImageToSame, uImageFlags, pDstUuid, uOpenFlags, pVDIfsOperation, pDstVDIfsImage, pDstVDIfsOperation));
7062
7063 PVDINTERFACEPROGRESS pIfProgress = VDIfProgressGet(pVDIfsOperation);
7064 PVDINTERFACEPROGRESS pDstIfProgress = VDIfProgressGet(pDstVDIfsOperation);
7065
7066 do {
7067 /* Check arguments. */
7068 AssertMsgBreakStmt(VALID_PTR(pDiskFrom), ("pDiskFrom=%#p\n", pDiskFrom),
7069 rc = VERR_INVALID_PARAMETER);
7070 AssertMsg(pDiskFrom->u32Signature == VBOXHDDDISK_SIGNATURE,
7071 ("u32Signature=%08x\n", pDiskFrom->u32Signature));
7072
7073 rc2 = vdThreadStartRead(pDiskFrom);
7074 AssertRC(rc2);
7075 fLockReadFrom = true;
7076 PVDIMAGE pImageFrom = vdGetImageByNumber(pDiskFrom, nImage);
7077 AssertPtrBreakStmt(pImageFrom, rc = VERR_VD_IMAGE_NOT_FOUND);
7078 AssertMsgBreakStmt(VALID_PTR(pDiskTo), ("pDiskTo=%#p\n", pDiskTo),
7079 rc = VERR_INVALID_PARAMETER);
7080 AssertMsg(pDiskTo->u32Signature == VBOXHDDDISK_SIGNATURE,
7081 ("u32Signature=%08x\n", pDiskTo->u32Signature));
7082 AssertMsgBreakStmt( (nImageFromSame < nImage || nImageFromSame == VD_IMAGE_CONTENT_UNKNOWN)
7083 && (nImageToSame < pDiskTo->cImages || nImageToSame == VD_IMAGE_CONTENT_UNKNOWN)
7084 && ( (nImageFromSame == VD_IMAGE_CONTENT_UNKNOWN && nImageToSame == VD_IMAGE_CONTENT_UNKNOWN)
7085 || (nImageFromSame != VD_IMAGE_CONTENT_UNKNOWN && nImageToSame != VD_IMAGE_CONTENT_UNKNOWN)),
7086 ("nImageFromSame=%u nImageToSame=%u\n", nImageFromSame, nImageToSame),
7087 rc = VERR_INVALID_PARAMETER);
7088
7089 /* Move the image. */
7090 if (pDiskFrom == pDiskTo)
7091 {
7092 /* Rename only works when backends are the same, are file based
7093 * and the rename method is implemented. */
7094 if ( fMoveByRename
7095 && !RTStrICmp(pszBackend, pImageFrom->Backend->pszBackendName)
7096 && pImageFrom->Backend->uBackendCaps & VD_CAP_FILE
7097 && pImageFrom->Backend->pfnRename)
7098 {
7099 rc2 = vdThreadFinishRead(pDiskFrom);
7100 AssertRC(rc2);
7101 fLockReadFrom = false;
7102
7103 rc2 = vdThreadStartWrite(pDiskFrom);
7104 AssertRC(rc2);
7105 fLockWriteFrom = true;
7106 rc = pImageFrom->Backend->pfnRename(pImageFrom->pBackendData, pszFilename ? pszFilename : pImageFrom->pszFilename);
7107 break;
7108 }
7109
7110 /** @todo Moving (including shrinking/growing) of the image is
7111 * requested, but the rename attempt failed or it wasn't possible.
7112 * Must now copy image to temp location. */
7113 AssertReleaseMsgFailed(("VDCopy: moving by copy/delete not implemented\n"));
7114 }
7115
7116 /* pszFilename is allowed to be NULL, as this indicates copy to the existing image. */
7117 AssertMsgBreakStmt(pszFilename == NULL || (VALID_PTR(pszFilename) && *pszFilename),
7118 ("pszFilename=%#p \"%s\"\n", pszFilename, pszFilename),
7119 rc = VERR_INVALID_PARAMETER);
7120
7121 uint64_t cbSizeFrom;
7122 cbSizeFrom = pImageFrom->Backend->pfnGetSize(pImageFrom->pBackendData);
7123 if (cbSizeFrom == 0)
7124 {
7125 rc = VERR_VD_VALUE_NOT_FOUND;
7126 break;
7127 }
7128
7129 VDGEOMETRY PCHSGeometryFrom = {0, 0, 0};
7130 VDGEOMETRY LCHSGeometryFrom = {0, 0, 0};
7131 pImageFrom->Backend->pfnGetPCHSGeometry(pImageFrom->pBackendData, &PCHSGeometryFrom);
7132 pImageFrom->Backend->pfnGetLCHSGeometry(pImageFrom->pBackendData, &LCHSGeometryFrom);
7133
7134 RTUUID ImageUuid, ImageModificationUuid;
7135 if (pDiskFrom != pDiskTo)
7136 {
7137 if (pDstUuid)
7138 ImageUuid = *pDstUuid;
7139 else
7140 RTUuidCreate(&ImageUuid);
7141 }
7142 else
7143 {
7144 rc = pImageFrom->Backend->pfnGetUuid(pImageFrom->pBackendData, &ImageUuid);
7145 if (RT_FAILURE(rc))
7146 RTUuidCreate(&ImageUuid);
7147 }
7148 rc = pImageFrom->Backend->pfnGetModificationUuid(pImageFrom->pBackendData, &ImageModificationUuid);
7149 if (RT_FAILURE(rc))
7150 RTUuidClear(&ImageModificationUuid);
7151
7152 char szComment[1024];
7153 rc = pImageFrom->Backend->pfnGetComment(pImageFrom->pBackendData, szComment, sizeof(szComment));
7154 if (RT_FAILURE(rc))
7155 szComment[0] = '\0';
7156 else
7157 szComment[sizeof(szComment) - 1] = '\0';
7158
7159 rc2 = vdThreadFinishRead(pDiskFrom);
7160 AssertRC(rc2);
7161 fLockReadFrom = false;
7162
7163 rc2 = vdThreadStartRead(pDiskTo);
7164 AssertRC(rc2);
7165 unsigned cImagesTo = pDiskTo->cImages;
7166 rc2 = vdThreadFinishRead(pDiskTo);
7167 AssertRC(rc2);
7168
7169 if (pszFilename)
7170 {
7171 if (cbSize == 0)
7172 cbSize = cbSizeFrom;
7173
7174 /* Create destination image with the properties of source image. */
7175 /** @todo replace the VDCreateDiff/VDCreateBase calls by direct
7176 * calls to the backend. Unifies the code and reduces the API
7177 * dependencies. Would also make the synchronization explicit. */
7178 if (cImagesTo > 0)
7179 {
7180 rc = VDCreateDiff(pDiskTo, pszBackend, pszFilename,
7181 uImageFlags, szComment, &ImageUuid,
7182 NULL /* pParentUuid */,
7183 uOpenFlags & ~VD_OPEN_FLAGS_READONLY,
7184 pDstVDIfsImage, NULL);
7185
7186 rc2 = vdThreadStartWrite(pDiskTo);
7187 AssertRC(rc2);
7188 fLockWriteTo = true;
7189 } else {
7190 /** @todo hack to force creation of a fixed image for
7191 * the RAW backend, which can't handle anything else. */
7192 if (!RTStrICmp(pszBackend, "RAW"))
7193 uImageFlags |= VD_IMAGE_FLAGS_FIXED;
7194
7195 vdFixupPCHSGeometry(&PCHSGeometryFrom, cbSize);
7196 vdFixupLCHSGeometry(&LCHSGeometryFrom, cbSize);
7197
7198 rc = VDCreateBase(pDiskTo, pszBackend, pszFilename, cbSize,
7199 uImageFlags, szComment,
7200 &PCHSGeometryFrom, &LCHSGeometryFrom,
7201 NULL, uOpenFlags & ~VD_OPEN_FLAGS_READONLY,
7202 pDstVDIfsImage, NULL);
7203
7204 rc2 = vdThreadStartWrite(pDiskTo);
7205 AssertRC(rc2);
7206 fLockWriteTo = true;
7207
7208 if (RT_SUCCESS(rc) && !RTUuidIsNull(&ImageUuid))
7209 pDiskTo->pLast->Backend->pfnSetUuid(pDiskTo->pLast->pBackendData, &ImageUuid);
7210 }
7211 if (RT_FAILURE(rc))
7212 break;
7213
7214 pImageTo = pDiskTo->pLast;
7215 AssertPtrBreakStmt(pImageTo, rc = VERR_VD_IMAGE_NOT_FOUND);
7216
7217 cbSize = RT_MIN(cbSize, cbSizeFrom);
7218 }
7219 else
7220 {
7221 pImageTo = pDiskTo->pLast;
7222 AssertPtrBreakStmt(pImageTo, rc = VERR_VD_IMAGE_NOT_FOUND);
7223
7224 uint64_t cbSizeTo;
7225 cbSizeTo = pImageTo->Backend->pfnGetSize(pImageTo->pBackendData);
7226 if (cbSizeTo == 0)
7227 {
7228 rc = VERR_VD_VALUE_NOT_FOUND;
7229 break;
7230 }
7231
7232 if (cbSize == 0)
7233 cbSize = RT_MIN(cbSizeFrom, cbSizeTo);
7234
7235 vdFixupPCHSGeometry(&PCHSGeometryFrom, cbSize);
7236 vdFixupLCHSGeometry(&LCHSGeometryFrom, cbSize);
7237
7238 /* Update the geometry in the destination image. */
7239 pImageTo->Backend->pfnSetPCHSGeometry(pImageTo->pBackendData, &PCHSGeometryFrom);
7240 pImageTo->Backend->pfnSetLCHSGeometry(pImageTo->pBackendData, &LCHSGeometryFrom);
7241 }
7242
7243 rc2 = vdThreadFinishWrite(pDiskTo);
7244 AssertRC(rc2);
7245 fLockWriteTo = false;
7246
7247 /* Whether we can take the optimized copy path (false) or not.
7248 * Don't optimize if the image existed or if it is a child image. */
7249 bool fSuppressRedundantIo = ( !(pszFilename == NULL || cImagesTo > 0)
7250 || (nImageToSame != VD_IMAGE_CONTENT_UNKNOWN));
7251 unsigned cImagesFromReadBack, cImagesToReadBack;
7252
7253 if (nImageFromSame == VD_IMAGE_CONTENT_UNKNOWN)
7254 cImagesFromReadBack = 0;
7255 else
7256 {
7257 if (nImage == VD_LAST_IMAGE)
7258 cImagesFromReadBack = pDiskFrom->cImages - nImageFromSame - 1;
7259 else
7260 cImagesFromReadBack = nImage - nImageFromSame;
7261 }
7262
7263 if (nImageToSame == VD_IMAGE_CONTENT_UNKNOWN)
7264 cImagesToReadBack = 0;
7265 else
7266 cImagesToReadBack = pDiskTo->cImages - nImageToSame - 1;
7267
7268 /* Copy the data. */
7269 rc = vdCopyHelper(pDiskFrom, pImageFrom, pDiskTo, cbSize,
7270 cImagesFromReadBack, cImagesToReadBack,
7271 fSuppressRedundantIo, pIfProgress, pDstIfProgress);
7272
7273 if (RT_SUCCESS(rc))
7274 {
7275 rc2 = vdThreadStartWrite(pDiskTo);
7276 AssertRC(rc2);
7277 fLockWriteTo = true;
7278
7279 /* Only set modification UUID if it is non-null, since the source
7280 * backend might not provide a valid modification UUID. */
7281 if (!RTUuidIsNull(&ImageModificationUuid))
7282 pImageTo->Backend->pfnSetModificationUuid(pImageTo->pBackendData, &ImageModificationUuid);
7283
7284 /* Set the requested open flags if they differ from the value
7285 * required for creating the image and copying the contents. */
7286 if ( pImageTo && pszFilename
7287 && uOpenFlags != (uOpenFlags & ~VD_OPEN_FLAGS_READONLY))
7288 rc = pImageTo->Backend->pfnSetOpenFlags(pImageTo->pBackendData,
7289 uOpenFlags);
7290 }
7291 } while (0);
7292
7293 if (RT_FAILURE(rc) && pImageTo && pszFilename)
7294 {
7295 /* Take the write lock only if it is not taken. Not worth making the
7296 * above code even more complicated. */
7297 if (RT_UNLIKELY(!fLockWriteTo))
7298 {
7299 rc2 = vdThreadStartWrite(pDiskTo);
7300 AssertRC(rc2);
7301 fLockWriteTo = true;
7302 }
7303 /* Error detected, but new image created. Remove image from list. */
7304 vdRemoveImageFromList(pDiskTo, pImageTo);
7305
7306 /* Close and delete image. */
7307 rc2 = pImageTo->Backend->pfnClose(pImageTo->pBackendData, true);
7308 AssertRC(rc2);
7309 pImageTo->pBackendData = NULL;
7310
7311 /* Free remaining resources. */
7312 if (pImageTo->pszFilename)
7313 RTStrFree(pImageTo->pszFilename);
7314
7315 RTMemFree(pImageTo);
7316 }
7317
7318 if (RT_UNLIKELY(fLockWriteTo))
7319 {
7320 rc2 = vdThreadFinishWrite(pDiskTo);
7321 AssertRC(rc2);
7322 }
7323 if (RT_UNLIKELY(fLockWriteFrom))
7324 {
7325 rc2 = vdThreadFinishWrite(pDiskFrom);
7326 AssertRC(rc2);
7327 }
7328 else if (RT_UNLIKELY(fLockReadFrom))
7329 {
7330 rc2 = vdThreadFinishRead(pDiskFrom);
7331 AssertRC(rc2);
7332 }
7333
7334 if (RT_SUCCESS(rc))
7335 {
7336 if (pIfProgress && pIfProgress->pfnProgress)
7337 pIfProgress->pfnProgress(pIfProgress->Core.pvUser, 100);
7338 if (pDstIfProgress && pDstIfProgress->pfnProgress)
7339 pDstIfProgress->pfnProgress(pDstIfProgress->Core.pvUser, 100);
7340 }
7341
7342 LogFlowFunc(("returns %Rrc\n", rc));
7343 return rc;
7344}
7345
7346/**
7347 * Copies an image from one HDD container to another.
7348 * The copy is opened in the target HDD container.
7349 * It is possible to convert between different image formats, because the
7350 * backend for the destination may be different from the source.
7351 * If both the source and destination reference the same HDD container,
7352 * then the image is moved (by copying/deleting or renaming) to the new location.
7353 * The source container is unchanged if the move operation fails, otherwise
7354 * the image at the new location is opened in the same way as the old one was.
7355 *
7356 * @returns VBox status code.
7357 * @returns VERR_VD_IMAGE_NOT_FOUND if image with specified number was not opened.
7358 * @param pDiskFrom Pointer to source HDD container.
7359 * @param nImage Image number, counts from 0. 0 is always base image of container.
7360 * @param pDiskTo Pointer to destination HDD container.
7361 * @param pszBackend Name of the image file backend to use.
7362 * @param pszFilename New name of the image (may be NULL if pDiskFrom == pDiskTo).
7363 * @param fMoveByRename If true, attempt to perform a move by renaming (if successful the new size is ignored).
7364 * @param cbSize New image size (0 means leave unchanged).
7365 * @param uImageFlags Flags specifying special destination image features.
7366 * @param pDstUuid New UUID of the destination image. If NULL, a new UUID is created.
7367 * This parameter is used if and only if a true copy is created.
7368 * In all rename/move cases the UUIDs are copied over.
7369 * @param uOpenFlags Image file open mode, see VD_OPEN_FLAGS_* constants.
7370 * Only used if the destination image is created.
7371 * @param pVDIfsOperation Pointer to the per-operation VD interface list.
7372 * @param pDstVDIfsImage Pointer to the per-image VD interface list, for the
7373 * destination image.
7374 * @param pDstVDIfsOperation Pointer to the per-image VD interface list,
7375 * for the destination image.
7376 */
7377VBOXDDU_DECL(int) VDCopy(PVBOXHDD pDiskFrom, unsigned nImage, PVBOXHDD pDiskTo,
7378 const char *pszBackend, const char *pszFilename,
7379 bool fMoveByRename, uint64_t cbSize,
7380 unsigned uImageFlags, PCRTUUID pDstUuid,
7381 unsigned uOpenFlags, PVDINTERFACE pVDIfsOperation,
7382 PVDINTERFACE pDstVDIfsImage,
7383 PVDINTERFACE pDstVDIfsOperation)
7384{
7385 return VDCopyEx(pDiskFrom, nImage, pDiskTo, pszBackend, pszFilename, fMoveByRename,
7386 cbSize, VD_IMAGE_CONTENT_UNKNOWN, VD_IMAGE_CONTENT_UNKNOWN,
7387 uImageFlags, pDstUuid, uOpenFlags, pVDIfsOperation,
7388 pDstVDIfsImage, pDstVDIfsOperation);
7389}
7390
7391/**
7392 * Optimizes the storage consumption of an image. Typically the unused blocks
7393 * have to be wiped with zeroes to achieve a substantial reduced storage use.
7394 * Another optimization done is reordering the image blocks, which can provide
7395 * a significant performance boost, as reads and writes tend to use less random
7396 * file offsets.
7397 *
7398 * @return VBox status code.
7399 * @return VERR_VD_IMAGE_NOT_FOUND if image with specified number was not opened.
7400 * @return VERR_VD_IMAGE_READ_ONLY if image is not writable.
7401 * @return VERR_NOT_SUPPORTED if this kind of image can be compacted, but
7402 * the code for this isn't implemented yet.
7403 * @param pDisk Pointer to HDD container.
7404 * @param nImage Image number, counts from 0. 0 is always base image of container.
7405 * @param pVDIfsOperation Pointer to the per-operation VD interface list.
7406 */
7407VBOXDDU_DECL(int) VDCompact(PVBOXHDD pDisk, unsigned nImage,
7408 PVDINTERFACE pVDIfsOperation)
7409{
7410 int rc = VINF_SUCCESS;
7411 int rc2;
7412 bool fLockRead = false, fLockWrite = false;
7413 void *pvBuf = NULL;
7414 void *pvTmp = NULL;
7415
7416 LogFlowFunc(("pDisk=%#p nImage=%u pVDIfsOperation=%#p\n",
7417 pDisk, nImage, pVDIfsOperation));
7418
7419 PVDINTERFACEPROGRESS pIfProgress = VDIfProgressGet(pVDIfsOperation);
7420
7421 do {
7422 /* Check arguments. */
7423 AssertMsgBreakStmt(VALID_PTR(pDisk), ("pDisk=%#p\n", pDisk),
7424 rc = VERR_INVALID_PARAMETER);
7425 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE,
7426 ("u32Signature=%08x\n", pDisk->u32Signature));
7427
7428 rc2 = vdThreadStartRead(pDisk);
7429 AssertRC(rc2);
7430 fLockRead = true;
7431
7432 PVDIMAGE pImage = vdGetImageByNumber(pDisk, nImage);
7433 AssertPtrBreakStmt(pImage, rc = VERR_VD_IMAGE_NOT_FOUND);
7434
7435 /* If there is no compact callback for not file based backends then
7436 * the backend doesn't need compaction. No need to make much fuss about
7437 * this. For file based ones signal this as not yet supported. */
7438 if (!pImage->Backend->pfnCompact)
7439 {
7440 if (pImage->Backend->uBackendCaps & VD_CAP_FILE)
7441 rc = VERR_NOT_SUPPORTED;
7442 else
7443 rc = VINF_SUCCESS;
7444 break;
7445 }
7446
7447 /* Insert interface for reading parent state into per-operation list,
7448 * if there is a parent image. */
7449 VDINTERFACEPARENTSTATE VDIfParent;
7450 VDPARENTSTATEDESC ParentUser;
7451 if (pImage->pPrev)
7452 {
7453 VDIfParent.pfnParentRead = vdParentRead;
7454 ParentUser.pDisk = pDisk;
7455 ParentUser.pImage = pImage->pPrev;
7456 rc = VDInterfaceAdd(&VDIfParent.Core, "VDCompact_ParentState", VDINTERFACETYPE_PARENTSTATE,
7457 &ParentUser, sizeof(VDINTERFACEPARENTSTATE), &pVDIfsOperation);
7458 AssertRC(rc);
7459 }
7460
7461 rc2 = vdThreadFinishRead(pDisk);
7462 AssertRC(rc2);
7463 fLockRead = false;
7464
7465 rc2 = vdThreadStartWrite(pDisk);
7466 AssertRC(rc2);
7467 fLockWrite = true;
7468
7469 rc = pImage->Backend->pfnCompact(pImage->pBackendData,
7470 0, 99,
7471 pDisk->pVDIfsDisk,
7472 pImage->pVDIfsImage,
7473 pVDIfsOperation);
7474 } while (0);
7475
7476 if (RT_UNLIKELY(fLockWrite))
7477 {
7478 rc2 = vdThreadFinishWrite(pDisk);
7479 AssertRC(rc2);
7480 }
7481 else if (RT_UNLIKELY(fLockRead))
7482 {
7483 rc2 = vdThreadFinishRead(pDisk);
7484 AssertRC(rc2);
7485 }
7486
7487 if (pvBuf)
7488 RTMemTmpFree(pvBuf);
7489 if (pvTmp)
7490 RTMemTmpFree(pvTmp);
7491
7492 if (RT_SUCCESS(rc))
7493 {
7494 if (pIfProgress && pIfProgress->pfnProgress)
7495 pIfProgress->pfnProgress(pIfProgress->Core.pvUser, 100);
7496 }
7497
7498 LogFlowFunc(("returns %Rrc\n", rc));
7499 return rc;
7500}
7501
7502/**
7503 * Resizes the given disk image to the given size.
7504 *
7505 * @return VBox status
7506 * @return VERR_VD_IMAGE_READ_ONLY if image is not writable.
7507 * @return VERR_NOT_SUPPORTED if this kind of image can be compacted, but
7508 *
7509 * @param pDisk Pointer to the HDD container.
7510 * @param cbSize New size of the image.
7511 * @param pPCHSGeometry Pointer to the new physical disk geometry <= (16383,16,63). Not NULL.
7512 * @param pLCHSGeometry Pointer to the new logical disk geometry <= (x,255,63). Not NULL.
7513 * @param pVDIfsOperation Pointer to the per-operation VD interface list.
7514 */
7515VBOXDDU_DECL(int) VDResize(PVBOXHDD pDisk, uint64_t cbSize,
7516 PCVDGEOMETRY pPCHSGeometry,
7517 PCVDGEOMETRY pLCHSGeometry,
7518 PVDINTERFACE pVDIfsOperation)
7519{
7520 /** @todo r=klaus resizing was designed to be part of VDCopy, so having a separate function is not desirable. */
7521 int rc = VINF_SUCCESS;
7522 int rc2;
7523 bool fLockRead = false, fLockWrite = false;
7524
7525 LogFlowFunc(("pDisk=%#p cbSize=%llu pVDIfsOperation=%#p\n",
7526 pDisk, cbSize, pVDIfsOperation));
7527
7528 PVDINTERFACEPROGRESS pIfProgress = VDIfProgressGet(pVDIfsOperation);
7529
7530 do {
7531 /* Check arguments. */
7532 AssertMsgBreakStmt(VALID_PTR(pDisk), ("pDisk=%#p\n", pDisk),
7533 rc = VERR_INVALID_PARAMETER);
7534 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE,
7535 ("u32Signature=%08x\n", pDisk->u32Signature));
7536
7537 rc2 = vdThreadStartRead(pDisk);
7538 AssertRC(rc2);
7539 fLockRead = true;
7540
7541 /* Not supported if the disk has child images attached. */
7542 AssertMsgBreakStmt(pDisk->cImages == 1, ("cImages=%u\n", pDisk->cImages),
7543 rc = VERR_NOT_SUPPORTED);
7544
7545 PVDIMAGE pImage = pDisk->pBase;
7546
7547 /* If there is no compact callback for not file based backends then
7548 * the backend doesn't need compaction. No need to make much fuss about
7549 * this. For file based ones signal this as not yet supported. */
7550 if (!pImage->Backend->pfnResize)
7551 {
7552 if (pImage->Backend->uBackendCaps & VD_CAP_FILE)
7553 rc = VERR_NOT_SUPPORTED;
7554 else
7555 rc = VINF_SUCCESS;
7556 break;
7557 }
7558
7559 rc2 = vdThreadFinishRead(pDisk);
7560 AssertRC(rc2);
7561 fLockRead = false;
7562
7563 rc2 = vdThreadStartWrite(pDisk);
7564 AssertRC(rc2);
7565 fLockWrite = true;
7566
7567 VDGEOMETRY PCHSGeometryOld;
7568 VDGEOMETRY LCHSGeometryOld;
7569 PCVDGEOMETRY pPCHSGeometryNew;
7570 PCVDGEOMETRY pLCHSGeometryNew;
7571
7572 if (pPCHSGeometry->cCylinders == 0)
7573 {
7574 /* Auto-detect marker, calculate new value ourself. */
7575 rc = pImage->Backend->pfnGetPCHSGeometry(pImage->pBackendData, &PCHSGeometryOld);
7576 if (RT_SUCCESS(rc) && (PCHSGeometryOld.cCylinders != 0))
7577 PCHSGeometryOld.cCylinders = RT_MIN(cbSize / 512 / PCHSGeometryOld.cHeads / PCHSGeometryOld.cSectors, 16383);
7578 else if (rc == VERR_VD_GEOMETRY_NOT_SET)
7579 rc = VINF_SUCCESS;
7580
7581 pPCHSGeometryNew = &PCHSGeometryOld;
7582 }
7583 else
7584 pPCHSGeometryNew = pPCHSGeometry;
7585
7586 if (pLCHSGeometry->cCylinders == 0)
7587 {
7588 /* Auto-detect marker, calculate new value ourself. */
7589 rc = pImage->Backend->pfnGetLCHSGeometry(pImage->pBackendData, &LCHSGeometryOld);
7590 if (RT_SUCCESS(rc) && (LCHSGeometryOld.cCylinders != 0))
7591 LCHSGeometryOld.cCylinders = cbSize / 512 / LCHSGeometryOld.cHeads / LCHSGeometryOld.cSectors;
7592 else if (rc == VERR_VD_GEOMETRY_NOT_SET)
7593 rc = VINF_SUCCESS;
7594
7595 pLCHSGeometryNew = &LCHSGeometryOld;
7596 }
7597 else
7598 pLCHSGeometryNew = pLCHSGeometry;
7599
7600 if (RT_SUCCESS(rc))
7601 rc = pImage->Backend->pfnResize(pImage->pBackendData,
7602 cbSize,
7603 pPCHSGeometryNew,
7604 pLCHSGeometryNew,
7605 0, 99,
7606 pDisk->pVDIfsDisk,
7607 pImage->pVDIfsImage,
7608 pVDIfsOperation);
7609 } while (0);
7610
7611 if (RT_UNLIKELY(fLockWrite))
7612 {
7613 rc2 = vdThreadFinishWrite(pDisk);
7614 AssertRC(rc2);
7615 }
7616 else if (RT_UNLIKELY(fLockRead))
7617 {
7618 rc2 = vdThreadFinishRead(pDisk);
7619 AssertRC(rc2);
7620 }
7621
7622 if (RT_SUCCESS(rc))
7623 {
7624 if (pIfProgress && pIfProgress->pfnProgress)
7625 pIfProgress->pfnProgress(pIfProgress->Core.pvUser, 100);
7626
7627 pDisk->cbSize = cbSize;
7628 }
7629
7630 LogFlowFunc(("returns %Rrc\n", rc));
7631 return rc;
7632}
7633
7634/**
7635 * Closes the last opened image file in HDD container.
7636 * If previous image file was opened in read-only mode (the normal case) and
7637 * the last opened image is in read-write mode then the previous image will be
7638 * reopened in read/write mode.
7639 *
7640 * @returns VBox status code.
7641 * @returns VERR_VD_NOT_OPENED if no image is opened in HDD container.
7642 * @param pDisk Pointer to HDD container.
7643 * @param fDelete If true, delete the image from the host disk.
7644 */
7645VBOXDDU_DECL(int) VDClose(PVBOXHDD pDisk, bool fDelete)
7646{
7647 int rc = VINF_SUCCESS;
7648 int rc2;
7649 bool fLockWrite = false;
7650
7651 LogFlowFunc(("pDisk=%#p fDelete=%d\n", pDisk, fDelete));
7652 do
7653 {
7654 /* sanity check */
7655 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
7656 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
7657
7658 /* Not worth splitting this up into a read lock phase and write
7659 * lock phase, as closing an image is a relatively fast operation
7660 * dominated by the part which needs the write lock. */
7661 rc2 = vdThreadStartWrite(pDisk);
7662 AssertRC(rc2);
7663 fLockWrite = true;
7664
7665 PVDIMAGE pImage = pDisk->pLast;
7666 if (!pImage)
7667 {
7668 rc = VERR_VD_NOT_OPENED;
7669 break;
7670 }
7671
7672 /* Destroy the current discard state first which might still have pending blocks. */
7673 rc = vdDiscardStateDestroy(pDisk);
7674 if (RT_FAILURE(rc))
7675 break;
7676
7677 unsigned uOpenFlags = pImage->Backend->pfnGetOpenFlags(pImage->pBackendData);
7678 /* Remove image from list of opened images. */
7679 vdRemoveImageFromList(pDisk, pImage);
7680 /* Close (and optionally delete) image. */
7681 rc = pImage->Backend->pfnClose(pImage->pBackendData, fDelete);
7682 /* Free remaining resources related to the image. */
7683 RTStrFree(pImage->pszFilename);
7684 RTMemFree(pImage);
7685
7686 pImage = pDisk->pLast;
7687 if (!pImage)
7688 break;
7689
7690 /* If disk was previously in read/write mode, make sure it will stay
7691 * like this (if possible) after closing this image. Set the open flags
7692 * accordingly. */
7693 if (!(uOpenFlags & VD_OPEN_FLAGS_READONLY))
7694 {
7695 uOpenFlags = pImage->Backend->pfnGetOpenFlags(pImage->pBackendData);
7696 uOpenFlags &= ~ VD_OPEN_FLAGS_READONLY;
7697 rc = pImage->Backend->pfnSetOpenFlags(pImage->pBackendData, uOpenFlags);
7698 }
7699
7700 /* Cache disk information. */
7701 pDisk->cbSize = pImage->Backend->pfnGetSize(pImage->pBackendData);
7702
7703 /* Cache PCHS geometry. */
7704 rc2 = pImage->Backend->pfnGetPCHSGeometry(pImage->pBackendData,
7705 &pDisk->PCHSGeometry);
7706 if (RT_FAILURE(rc2))
7707 {
7708 pDisk->PCHSGeometry.cCylinders = 0;
7709 pDisk->PCHSGeometry.cHeads = 0;
7710 pDisk->PCHSGeometry.cSectors = 0;
7711 }
7712 else
7713 {
7714 /* Make sure the PCHS geometry is properly clipped. */
7715 pDisk->PCHSGeometry.cCylinders = RT_MIN(pDisk->PCHSGeometry.cCylinders, 16383);
7716 pDisk->PCHSGeometry.cHeads = RT_MIN(pDisk->PCHSGeometry.cHeads, 16);
7717 pDisk->PCHSGeometry.cSectors = RT_MIN(pDisk->PCHSGeometry.cSectors, 63);
7718 }
7719
7720 /* Cache LCHS geometry. */
7721 rc2 = pImage->Backend->pfnGetLCHSGeometry(pImage->pBackendData,
7722 &pDisk->LCHSGeometry);
7723 if (RT_FAILURE(rc2))
7724 {
7725 pDisk->LCHSGeometry.cCylinders = 0;
7726 pDisk->LCHSGeometry.cHeads = 0;
7727 pDisk->LCHSGeometry.cSectors = 0;
7728 }
7729 else
7730 {
7731 /* Make sure the LCHS geometry is properly clipped. */
7732 pDisk->LCHSGeometry.cHeads = RT_MIN(pDisk->LCHSGeometry.cHeads, 255);
7733 pDisk->LCHSGeometry.cSectors = RT_MIN(pDisk->LCHSGeometry.cSectors, 63);
7734 }
7735 } while (0);
7736
7737 if (RT_UNLIKELY(fLockWrite))
7738 {
7739 rc2 = vdThreadFinishWrite(pDisk);
7740 AssertRC(rc2);
7741 }
7742
7743 LogFlowFunc(("returns %Rrc\n", rc));
7744 return rc;
7745}
7746
7747/**
7748 * Closes the currently opened cache image file in HDD container.
7749 *
7750 * @return VBox status code.
7751 * @return VERR_VD_NOT_OPENED if no cache is opened in HDD container.
7752 * @param pDisk Pointer to HDD container.
7753 * @param fDelete If true, delete the image from the host disk.
7754 */
7755VBOXDDU_DECL(int) VDCacheClose(PVBOXHDD pDisk, bool fDelete)
7756{
7757 int rc = VINF_SUCCESS;
7758 int rc2;
7759 bool fLockWrite = false;
7760 PVDCACHE pCache = NULL;
7761
7762 LogFlowFunc(("pDisk=%#p fDelete=%d\n", pDisk, fDelete));
7763
7764 do
7765 {
7766 /* sanity check */
7767 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
7768 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
7769
7770 rc2 = vdThreadStartWrite(pDisk);
7771 AssertRC(rc2);
7772 fLockWrite = true;
7773
7774 AssertPtrBreakStmt(pDisk->pCache, rc = VERR_VD_CACHE_NOT_FOUND);
7775
7776 pCache = pDisk->pCache;
7777 pDisk->pCache = NULL;
7778
7779 pCache->Backend->pfnClose(pCache->pBackendData, fDelete);
7780 if (pCache->pszFilename)
7781 RTStrFree(pCache->pszFilename);
7782 RTMemFree(pCache);
7783 } while (0);
7784
7785 if (RT_LIKELY(fLockWrite))
7786 {
7787 rc2 = vdThreadFinishWrite(pDisk);
7788 AssertRC(rc2);
7789 }
7790
7791 LogFlowFunc(("returns %Rrc\n", rc));
7792 return rc;
7793}
7794
7795/**
7796 * Closes all opened image files in HDD container.
7797 *
7798 * @returns VBox status code.
7799 * @param pDisk Pointer to HDD container.
7800 */
7801VBOXDDU_DECL(int) VDCloseAll(PVBOXHDD pDisk)
7802{
7803 int rc = VINF_SUCCESS;
7804 int rc2;
7805 bool fLockWrite = false;
7806
7807 LogFlowFunc(("pDisk=%#p\n", pDisk));
7808 do
7809 {
7810 /* sanity check */
7811 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
7812 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
7813
7814 /* Lock the entire operation. */
7815 rc2 = vdThreadStartWrite(pDisk);
7816 AssertRC(rc2);
7817 fLockWrite = true;
7818
7819 PVDCACHE pCache = pDisk->pCache;
7820 if (pCache)
7821 {
7822 rc2 = pCache->Backend->pfnClose(pCache->pBackendData, false);
7823 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
7824 rc = rc2;
7825
7826 if (pCache->pszFilename)
7827 RTStrFree(pCache->pszFilename);
7828 RTMemFree(pCache);
7829 }
7830
7831 PVDIMAGE pImage = pDisk->pLast;
7832 while (VALID_PTR(pImage))
7833 {
7834 PVDIMAGE pPrev = pImage->pPrev;
7835 /* Remove image from list of opened images. */
7836 vdRemoveImageFromList(pDisk, pImage);
7837 /* Close image. */
7838 rc2 = pImage->Backend->pfnClose(pImage->pBackendData, false);
7839 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
7840 rc = rc2;
7841 /* Free remaining resources related to the image. */
7842 RTStrFree(pImage->pszFilename);
7843 RTMemFree(pImage);
7844 pImage = pPrev;
7845 }
7846 Assert(!VALID_PTR(pDisk->pLast));
7847 } while (0);
7848
7849 if (RT_UNLIKELY(fLockWrite))
7850 {
7851 rc2 = vdThreadFinishWrite(pDisk);
7852 AssertRC(rc2);
7853 }
7854
7855 LogFlowFunc(("returns %Rrc\n", rc));
7856 return rc;
7857}
7858
7859/**
7860 * Read data from virtual HDD.
7861 *
7862 * @returns VBox status code.
7863 * @returns VERR_VD_NOT_OPENED if no image is opened in HDD container.
7864 * @param pDisk Pointer to HDD container.
7865 * @param uOffset Offset of first reading byte from start of disk.
7866 * @param pvBuf Pointer to buffer for reading data.
7867 * @param cbRead Number of bytes to read.
7868 */
7869VBOXDDU_DECL(int) VDRead(PVBOXHDD pDisk, uint64_t uOffset, void *pvBuf,
7870 size_t cbRead)
7871{
7872 int rc = VINF_SUCCESS;
7873 int rc2;
7874 bool fLockRead = false;
7875
7876 LogFlowFunc(("pDisk=%#p uOffset=%llu pvBuf=%p cbRead=%zu\n",
7877 pDisk, uOffset, pvBuf, cbRead));
7878 do
7879 {
7880 /* sanity check */
7881 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
7882 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
7883
7884 /* Check arguments. */
7885 AssertMsgBreakStmt(VALID_PTR(pvBuf),
7886 ("pvBuf=%#p\n", pvBuf),
7887 rc = VERR_INVALID_PARAMETER);
7888 AssertMsgBreakStmt(cbRead,
7889 ("cbRead=%zu\n", cbRead),
7890 rc = VERR_INVALID_PARAMETER);
7891
7892 rc2 = vdThreadStartRead(pDisk);
7893 AssertRC(rc2);
7894 fLockRead = true;
7895
7896 AssertMsgBreakStmt(uOffset + cbRead <= pDisk->cbSize,
7897 ("uOffset=%llu cbRead=%zu pDisk->cbSize=%llu\n",
7898 uOffset, cbRead, pDisk->cbSize),
7899 rc = VERR_INVALID_PARAMETER);
7900
7901 PVDIMAGE pImage = pDisk->pLast;
7902 AssertPtrBreakStmt(pImage, rc = VERR_VD_NOT_OPENED);
7903
7904 rc = vdReadHelper(pDisk, pImage, uOffset, pvBuf, cbRead,
7905 true /* fUpdateCache */);
7906 } while (0);
7907
7908 if (RT_UNLIKELY(fLockRead))
7909 {
7910 rc2 = vdThreadFinishRead(pDisk);
7911 AssertRC(rc2);
7912 }
7913
7914 LogFlowFunc(("returns %Rrc\n", rc));
7915 return rc;
7916}
7917
7918/**
7919 * Write data to virtual HDD.
7920 *
7921 * @returns VBox status code.
7922 * @returns VERR_VD_NOT_OPENED if no image is opened in HDD container.
7923 * @param pDisk Pointer to HDD container.
7924 * @param uOffset Offset of the first byte being
7925 * written from start of disk.
7926 * @param pvBuf Pointer to buffer for writing data.
7927 * @param cbWrite Number of bytes to write.
7928 */
7929VBOXDDU_DECL(int) VDWrite(PVBOXHDD pDisk, uint64_t uOffset, const void *pvBuf,
7930 size_t cbWrite)
7931{
7932 int rc = VINF_SUCCESS;
7933 int rc2;
7934 bool fLockWrite = false;
7935
7936 LogFlowFunc(("pDisk=%#p uOffset=%llu pvBuf=%p cbWrite=%zu\n",
7937 pDisk, uOffset, pvBuf, cbWrite));
7938 do
7939 {
7940 /* sanity check */
7941 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
7942 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
7943
7944 /* Check arguments. */
7945 AssertMsgBreakStmt(VALID_PTR(pvBuf),
7946 ("pvBuf=%#p\n", pvBuf),
7947 rc = VERR_INVALID_PARAMETER);
7948 AssertMsgBreakStmt(cbWrite,
7949 ("cbWrite=%zu\n", cbWrite),
7950 rc = VERR_INVALID_PARAMETER);
7951
7952 rc2 = vdThreadStartWrite(pDisk);
7953 AssertRC(rc2);
7954 fLockWrite = true;
7955
7956 AssertMsgBreakStmt(uOffset + cbWrite <= pDisk->cbSize,
7957 ("uOffset=%llu cbWrite=%zu pDisk->cbSize=%llu\n",
7958 uOffset, cbWrite, pDisk->cbSize),
7959 rc = VERR_INVALID_PARAMETER);
7960
7961 PVDIMAGE pImage = pDisk->pLast;
7962 AssertPtrBreakStmt(pImage, rc = VERR_VD_NOT_OPENED);
7963
7964 vdSetModifiedFlag(pDisk);
7965 rc = vdWriteHelper(pDisk, pImage, uOffset, pvBuf, cbWrite,
7966 true /* fUpdateCache */);
7967 if (RT_FAILURE(rc))
7968 break;
7969
7970 /* If there is a merge (in the direction towards a parent) running
7971 * concurrently then we have to also "relay" the write to this parent,
7972 * as the merge position might be already past the position where
7973 * this write is going. The "context" of the write can come from the
7974 * natural chain, since merging either already did or will take care
7975 * of the "other" content which is might be needed to fill the block
7976 * to a full allocation size. The cache doesn't need to be touched
7977 * as this write is covered by the previous one. */
7978 if (RT_UNLIKELY(pDisk->pImageRelay))
7979 rc = vdWriteHelper(pDisk, pDisk->pImageRelay, uOffset,
7980 pvBuf, cbWrite, false /* fUpdateCache */);
7981 } while (0);
7982
7983 if (RT_UNLIKELY(fLockWrite))
7984 {
7985 rc2 = vdThreadFinishWrite(pDisk);
7986 AssertRC(rc2);
7987 }
7988
7989 LogFlowFunc(("returns %Rrc\n", rc));
7990 return rc;
7991}
7992
7993/**
7994 * Make sure the on disk representation of a virtual HDD is up to date.
7995 *
7996 * @returns VBox status code.
7997 * @returns VERR_VD_NOT_OPENED if no image is opened in HDD container.
7998 * @param pDisk Pointer to HDD container.
7999 */
8000VBOXDDU_DECL(int) VDFlush(PVBOXHDD pDisk)
8001{
8002 int rc = VINF_SUCCESS;
8003 int rc2;
8004 bool fLockWrite = false;
8005
8006 LogFlowFunc(("pDisk=%#p\n", pDisk));
8007 do
8008 {
8009 /* sanity check */
8010 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
8011 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
8012
8013 rc2 = vdThreadStartWrite(pDisk);
8014 AssertRC(rc2);
8015 fLockWrite = true;
8016
8017 PVDIMAGE pImage = pDisk->pLast;
8018 AssertPtrBreakStmt(pImage, rc = VERR_VD_NOT_OPENED);
8019
8020 vdResetModifiedFlag(pDisk);
8021 rc = pImage->Backend->pfnFlush(pImage->pBackendData);
8022
8023 if ( RT_SUCCESS(rc)
8024 && pDisk->pCache)
8025 rc = pDisk->pCache->Backend->pfnFlush(pDisk->pCache->pBackendData);
8026 } while (0);
8027
8028 if (RT_UNLIKELY(fLockWrite))
8029 {
8030 rc2 = vdThreadFinishWrite(pDisk);
8031 AssertRC(rc2);
8032 }
8033
8034 LogFlowFunc(("returns %Rrc\n", rc));
8035 return rc;
8036}
8037
8038/**
8039 * Get number of opened images in HDD container.
8040 *
8041 * @returns Number of opened images for HDD container. 0 if no images have been opened.
8042 * @param pDisk Pointer to HDD container.
8043 */
8044VBOXDDU_DECL(unsigned) VDGetCount(PVBOXHDD pDisk)
8045{
8046 unsigned cImages;
8047 int rc2;
8048 bool fLockRead = false;
8049
8050 LogFlowFunc(("pDisk=%#p\n", pDisk));
8051 do
8052 {
8053 /* sanity check */
8054 AssertPtrBreakStmt(pDisk, cImages = 0);
8055 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
8056
8057 rc2 = vdThreadStartRead(pDisk);
8058 AssertRC(rc2);
8059 fLockRead = true;
8060
8061 cImages = pDisk->cImages;
8062 } while (0);
8063
8064 if (RT_UNLIKELY(fLockRead))
8065 {
8066 rc2 = vdThreadFinishRead(pDisk);
8067 AssertRC(rc2);
8068 }
8069
8070 LogFlowFunc(("returns %u\n", cImages));
8071 return cImages;
8072}
8073
8074/**
8075 * Get read/write mode of HDD container.
8076 *
8077 * @returns Virtual disk ReadOnly status.
8078 * @returns true if no image is opened in HDD container.
8079 * @param pDisk Pointer to HDD container.
8080 */
8081VBOXDDU_DECL(bool) VDIsReadOnly(PVBOXHDD pDisk)
8082{
8083 bool fReadOnly;
8084 int rc2;
8085 bool fLockRead = false;
8086
8087 LogFlowFunc(("pDisk=%#p\n", pDisk));
8088 do
8089 {
8090 /* sanity check */
8091 AssertPtrBreakStmt(pDisk, fReadOnly = false);
8092 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
8093
8094 rc2 = vdThreadStartRead(pDisk);
8095 AssertRC(rc2);
8096 fLockRead = true;
8097
8098 PVDIMAGE pImage = pDisk->pLast;
8099 AssertPtrBreakStmt(pImage, fReadOnly = true);
8100
8101 unsigned uOpenFlags;
8102 uOpenFlags = pDisk->pLast->Backend->pfnGetOpenFlags(pDisk->pLast->pBackendData);
8103 fReadOnly = !!(uOpenFlags & VD_OPEN_FLAGS_READONLY);
8104 } while (0);
8105
8106 if (RT_UNLIKELY(fLockRead))
8107 {
8108 rc2 = vdThreadFinishRead(pDisk);
8109 AssertRC(rc2);
8110 }
8111
8112 LogFlowFunc(("returns %d\n", fReadOnly));
8113 return fReadOnly;
8114}
8115
8116/**
8117 * Get total capacity of an image in HDD container.
8118 *
8119 * @returns Virtual disk size in bytes.
8120 * @returns 0 if no image with specified number was not opened.
8121 * @param pDisk Pointer to HDD container.
8122 * @param nImage Image number, counts from 0. 0 is always base image of container.
8123 */
8124VBOXDDU_DECL(uint64_t) VDGetSize(PVBOXHDD pDisk, unsigned nImage)
8125{
8126 uint64_t cbSize;
8127 int rc2;
8128 bool fLockRead = false;
8129
8130 LogFlowFunc(("pDisk=%#p nImage=%u\n", pDisk, nImage));
8131 do
8132 {
8133 /* sanity check */
8134 AssertPtrBreakStmt(pDisk, cbSize = 0);
8135 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
8136
8137 rc2 = vdThreadStartRead(pDisk);
8138 AssertRC(rc2);
8139 fLockRead = true;
8140
8141 PVDIMAGE pImage = vdGetImageByNumber(pDisk, nImage);
8142 AssertPtrBreakStmt(pImage, cbSize = 0);
8143 cbSize = pImage->Backend->pfnGetSize(pImage->pBackendData);
8144 } while (0);
8145
8146 if (RT_UNLIKELY(fLockRead))
8147 {
8148 rc2 = vdThreadFinishRead(pDisk);
8149 AssertRC(rc2);
8150 }
8151
8152 LogFlowFunc(("returns %llu\n", cbSize));
8153 return cbSize;
8154}
8155
8156/**
8157 * Get total file size of an image in HDD container.
8158 *
8159 * @returns Virtual disk size in bytes.
8160 * @returns 0 if no image is opened in HDD container.
8161 * @param pDisk Pointer to HDD container.
8162 * @param nImage Image number, counts from 0. 0 is always base image of container.
8163 */
8164VBOXDDU_DECL(uint64_t) VDGetFileSize(PVBOXHDD pDisk, unsigned nImage)
8165{
8166 uint64_t cbSize;
8167 int rc2;
8168 bool fLockRead = false;
8169
8170 LogFlowFunc(("pDisk=%#p nImage=%u\n", pDisk, nImage));
8171 do
8172 {
8173 /* sanity check */
8174 AssertPtrBreakStmt(pDisk, cbSize = 0);
8175 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
8176
8177 rc2 = vdThreadStartRead(pDisk);
8178 AssertRC(rc2);
8179 fLockRead = true;
8180
8181 PVDIMAGE pImage = vdGetImageByNumber(pDisk, nImage);
8182 AssertPtrBreakStmt(pImage, cbSize = 0);
8183 cbSize = pImage->Backend->pfnGetFileSize(pImage->pBackendData);
8184 } while (0);
8185
8186 if (RT_UNLIKELY(fLockRead))
8187 {
8188 rc2 = vdThreadFinishRead(pDisk);
8189 AssertRC(rc2);
8190 }
8191
8192 LogFlowFunc(("returns %llu\n", cbSize));
8193 return cbSize;
8194}
8195
8196/**
8197 * Get virtual disk PCHS geometry stored in HDD container.
8198 *
8199 * @returns VBox status code.
8200 * @returns VERR_VD_IMAGE_NOT_FOUND if image with specified number was not opened.
8201 * @returns VERR_VD_GEOMETRY_NOT_SET if no geometry present in the HDD container.
8202 * @param pDisk Pointer to HDD container.
8203 * @param nImage Image number, counts from 0. 0 is always base image of container.
8204 * @param pPCHSGeometry Where to store PCHS geometry. Not NULL.
8205 */
8206VBOXDDU_DECL(int) VDGetPCHSGeometry(PVBOXHDD pDisk, unsigned nImage,
8207 PVDGEOMETRY pPCHSGeometry)
8208{
8209 int rc = VINF_SUCCESS;
8210 int rc2;
8211 bool fLockRead = false;
8212
8213 LogFlowFunc(("pDisk=%#p nImage=%u pPCHSGeometry=%#p\n",
8214 pDisk, nImage, pPCHSGeometry));
8215 do
8216 {
8217 /* sanity check */
8218 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
8219 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
8220
8221 /* Check arguments. */
8222 AssertMsgBreakStmt(VALID_PTR(pPCHSGeometry),
8223 ("pPCHSGeometry=%#p\n", pPCHSGeometry),
8224 rc = VERR_INVALID_PARAMETER);
8225
8226 rc2 = vdThreadStartRead(pDisk);
8227 AssertRC(rc2);
8228 fLockRead = true;
8229
8230 PVDIMAGE pImage = vdGetImageByNumber(pDisk, nImage);
8231 AssertPtrBreakStmt(pImage, rc = VERR_VD_IMAGE_NOT_FOUND);
8232
8233 if (pImage == pDisk->pLast)
8234 {
8235 /* Use cached information if possible. */
8236 if (pDisk->PCHSGeometry.cCylinders != 0)
8237 *pPCHSGeometry = pDisk->PCHSGeometry;
8238 else
8239 rc = VERR_VD_GEOMETRY_NOT_SET;
8240 }
8241 else
8242 rc = pImage->Backend->pfnGetPCHSGeometry(pImage->pBackendData,
8243 pPCHSGeometry);
8244 } while (0);
8245
8246 if (RT_UNLIKELY(fLockRead))
8247 {
8248 rc2 = vdThreadFinishRead(pDisk);
8249 AssertRC(rc2);
8250 }
8251
8252 LogFlowFunc(("%Rrc (PCHS=%u/%u/%u)\n", rc,
8253 pDisk->PCHSGeometry.cCylinders, pDisk->PCHSGeometry.cHeads,
8254 pDisk->PCHSGeometry.cSectors));
8255 return rc;
8256}
8257
8258/**
8259 * Store virtual disk PCHS geometry in HDD container.
8260 *
8261 * Note that in case of unrecoverable error all images in HDD container will be closed.
8262 *
8263 * @returns VBox status code.
8264 * @returns VERR_VD_IMAGE_NOT_FOUND if image with specified number was not opened.
8265 * @returns VERR_VD_GEOMETRY_NOT_SET if no geometry present in the HDD container.
8266 * @param pDisk Pointer to HDD container.
8267 * @param nImage Image number, counts from 0. 0 is always base image of container.
8268 * @param pPCHSGeometry Where to load PCHS geometry from. Not NULL.
8269 */
8270VBOXDDU_DECL(int) VDSetPCHSGeometry(PVBOXHDD pDisk, unsigned nImage,
8271 PCVDGEOMETRY pPCHSGeometry)
8272{
8273 int rc = VINF_SUCCESS;
8274 int rc2;
8275 bool fLockWrite = false;
8276
8277 LogFlowFunc(("pDisk=%#p nImage=%u pPCHSGeometry=%#p PCHS=%u/%u/%u\n",
8278 pDisk, nImage, pPCHSGeometry, pPCHSGeometry->cCylinders,
8279 pPCHSGeometry->cHeads, pPCHSGeometry->cSectors));
8280 do
8281 {
8282 /* sanity check */
8283 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
8284 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
8285
8286 /* Check arguments. */
8287 AssertMsgBreakStmt( VALID_PTR(pPCHSGeometry)
8288 && pPCHSGeometry->cHeads <= 16
8289 && pPCHSGeometry->cSectors <= 63,
8290 ("pPCHSGeometry=%#p PCHS=%u/%u/%u\n", pPCHSGeometry,
8291 pPCHSGeometry->cCylinders, pPCHSGeometry->cHeads,
8292 pPCHSGeometry->cSectors),
8293 rc = VERR_INVALID_PARAMETER);
8294
8295 rc2 = vdThreadStartWrite(pDisk);
8296 AssertRC(rc2);
8297 fLockWrite = true;
8298
8299 PVDIMAGE pImage = vdGetImageByNumber(pDisk, nImage);
8300 AssertPtrBreakStmt(pImage, rc = VERR_VD_IMAGE_NOT_FOUND);
8301
8302 if (pImage == pDisk->pLast)
8303 {
8304 if ( pPCHSGeometry->cCylinders != pDisk->PCHSGeometry.cCylinders
8305 || pPCHSGeometry->cHeads != pDisk->PCHSGeometry.cHeads
8306 || pPCHSGeometry->cSectors != pDisk->PCHSGeometry.cSectors)
8307 {
8308 /* Only update geometry if it is changed. Avoids similar checks
8309 * in every backend. Most of the time the new geometry is set
8310 * to the previous values, so no need to go through the hassle
8311 * of updating an image which could be opened in read-only mode
8312 * right now. */
8313 rc = pImage->Backend->pfnSetPCHSGeometry(pImage->pBackendData,
8314 pPCHSGeometry);
8315
8316 /* Cache new geometry values in any case. */
8317 rc2 = pImage->Backend->pfnGetPCHSGeometry(pImage->pBackendData,
8318 &pDisk->PCHSGeometry);
8319 if (RT_FAILURE(rc2))
8320 {
8321 pDisk->PCHSGeometry.cCylinders = 0;
8322 pDisk->PCHSGeometry.cHeads = 0;
8323 pDisk->PCHSGeometry.cSectors = 0;
8324 }
8325 else
8326 {
8327 /* Make sure the CHS geometry is properly clipped. */
8328 pDisk->PCHSGeometry.cHeads = RT_MIN(pDisk->PCHSGeometry.cHeads, 255);
8329 pDisk->PCHSGeometry.cSectors = RT_MIN(pDisk->PCHSGeometry.cSectors, 63);
8330 }
8331 }
8332 }
8333 else
8334 {
8335 VDGEOMETRY PCHS;
8336 rc = pImage->Backend->pfnGetPCHSGeometry(pImage->pBackendData,
8337 &PCHS);
8338 if ( RT_FAILURE(rc)
8339 || pPCHSGeometry->cCylinders != PCHS.cCylinders
8340 || pPCHSGeometry->cHeads != PCHS.cHeads
8341 || pPCHSGeometry->cSectors != PCHS.cSectors)
8342 {
8343 /* Only update geometry if it is changed. Avoids similar checks
8344 * in every backend. Most of the time the new geometry is set
8345 * to the previous values, so no need to go through the hassle
8346 * of updating an image which could be opened in read-only mode
8347 * right now. */
8348 rc = pImage->Backend->pfnSetPCHSGeometry(pImage->pBackendData,
8349 pPCHSGeometry);
8350 }
8351 }
8352 } while (0);
8353
8354 if (RT_UNLIKELY(fLockWrite))
8355 {
8356 rc2 = vdThreadFinishWrite(pDisk);
8357 AssertRC(rc2);
8358 }
8359
8360 LogFlowFunc(("returns %Rrc\n", rc));
8361 return rc;
8362}
8363
8364/**
8365 * Get virtual disk LCHS geometry stored in HDD container.
8366 *
8367 * @returns VBox status code.
8368 * @returns VERR_VD_IMAGE_NOT_FOUND if image with specified number was not opened.
8369 * @returns VERR_VD_GEOMETRY_NOT_SET if no geometry present in the HDD container.
8370 * @param pDisk Pointer to HDD container.
8371 * @param nImage Image number, counts from 0. 0 is always base image of container.
8372 * @param pLCHSGeometry Where to store LCHS geometry. Not NULL.
8373 */
8374VBOXDDU_DECL(int) VDGetLCHSGeometry(PVBOXHDD pDisk, unsigned nImage,
8375 PVDGEOMETRY pLCHSGeometry)
8376{
8377 int rc = VINF_SUCCESS;
8378 int rc2;
8379 bool fLockRead = false;
8380
8381 LogFlowFunc(("pDisk=%#p nImage=%u pLCHSGeometry=%#p\n",
8382 pDisk, nImage, pLCHSGeometry));
8383 do
8384 {
8385 /* sanity check */
8386 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
8387 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
8388
8389 /* Check arguments. */
8390 AssertMsgBreakStmt(VALID_PTR(pLCHSGeometry),
8391 ("pLCHSGeometry=%#p\n", pLCHSGeometry),
8392 rc = VERR_INVALID_PARAMETER);
8393
8394 rc2 = vdThreadStartRead(pDisk);
8395 AssertRC(rc2);
8396 fLockRead = true;
8397
8398 PVDIMAGE pImage = vdGetImageByNumber(pDisk, nImage);
8399 AssertPtrBreakStmt(pImage, rc = VERR_VD_IMAGE_NOT_FOUND);
8400
8401 if (pImage == pDisk->pLast)
8402 {
8403 /* Use cached information if possible. */
8404 if (pDisk->LCHSGeometry.cCylinders != 0)
8405 *pLCHSGeometry = pDisk->LCHSGeometry;
8406 else
8407 rc = VERR_VD_GEOMETRY_NOT_SET;
8408 }
8409 else
8410 rc = pImage->Backend->pfnGetLCHSGeometry(pImage->pBackendData,
8411 pLCHSGeometry);
8412 } while (0);
8413
8414 if (RT_UNLIKELY(fLockRead))
8415 {
8416 rc2 = vdThreadFinishRead(pDisk);
8417 AssertRC(rc2);
8418 }
8419
8420 LogFlowFunc((": %Rrc (LCHS=%u/%u/%u)\n", rc,
8421 pDisk->LCHSGeometry.cCylinders, pDisk->LCHSGeometry.cHeads,
8422 pDisk->LCHSGeometry.cSectors));
8423 return rc;
8424}
8425
8426/**
8427 * Store virtual disk LCHS geometry in HDD container.
8428 *
8429 * Note that in case of unrecoverable error all images in HDD container will be closed.
8430 *
8431 * @returns VBox status code.
8432 * @returns VERR_VD_IMAGE_NOT_FOUND if image with specified number was not opened.
8433 * @returns VERR_VD_GEOMETRY_NOT_SET if no geometry present in the HDD container.
8434 * @param pDisk Pointer to HDD container.
8435 * @param nImage Image number, counts from 0. 0 is always base image of container.
8436 * @param pLCHSGeometry Where to load LCHS geometry from. Not NULL.
8437 */
8438VBOXDDU_DECL(int) VDSetLCHSGeometry(PVBOXHDD pDisk, unsigned nImage,
8439 PCVDGEOMETRY pLCHSGeometry)
8440{
8441 int rc = VINF_SUCCESS;
8442 int rc2;
8443 bool fLockWrite = false;
8444
8445 LogFlowFunc(("pDisk=%#p nImage=%u pLCHSGeometry=%#p LCHS=%u/%u/%u\n",
8446 pDisk, nImage, pLCHSGeometry, pLCHSGeometry->cCylinders,
8447 pLCHSGeometry->cHeads, pLCHSGeometry->cSectors));
8448 do
8449 {
8450 /* sanity check */
8451 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
8452 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
8453
8454 /* Check arguments. */
8455 AssertMsgBreakStmt( VALID_PTR(pLCHSGeometry)
8456 && pLCHSGeometry->cHeads <= 255
8457 && pLCHSGeometry->cSectors <= 63,
8458 ("pLCHSGeometry=%#p LCHS=%u/%u/%u\n", pLCHSGeometry,
8459 pLCHSGeometry->cCylinders, pLCHSGeometry->cHeads,
8460 pLCHSGeometry->cSectors),
8461 rc = VERR_INVALID_PARAMETER);
8462
8463 rc2 = vdThreadStartWrite(pDisk);
8464 AssertRC(rc2);
8465 fLockWrite = true;
8466
8467 PVDIMAGE pImage = vdGetImageByNumber(pDisk, nImage);
8468 AssertPtrBreakStmt(pImage, rc = VERR_VD_IMAGE_NOT_FOUND);
8469
8470 if (pImage == pDisk->pLast)
8471 {
8472 if ( pLCHSGeometry->cCylinders != pDisk->LCHSGeometry.cCylinders
8473 || pLCHSGeometry->cHeads != pDisk->LCHSGeometry.cHeads
8474 || pLCHSGeometry->cSectors != pDisk->LCHSGeometry.cSectors)
8475 {
8476 /* Only update geometry if it is changed. Avoids similar checks
8477 * in every backend. Most of the time the new geometry is set
8478 * to the previous values, so no need to go through the hassle
8479 * of updating an image which could be opened in read-only mode
8480 * right now. */
8481 rc = pImage->Backend->pfnSetLCHSGeometry(pImage->pBackendData,
8482 pLCHSGeometry);
8483
8484 /* Cache new geometry values in any case. */
8485 rc2 = pImage->Backend->pfnGetLCHSGeometry(pImage->pBackendData,
8486 &pDisk->LCHSGeometry);
8487 if (RT_FAILURE(rc2))
8488 {
8489 pDisk->LCHSGeometry.cCylinders = 0;
8490 pDisk->LCHSGeometry.cHeads = 0;
8491 pDisk->LCHSGeometry.cSectors = 0;
8492 }
8493 else
8494 {
8495 /* Make sure the CHS geometry is properly clipped. */
8496 pDisk->LCHSGeometry.cHeads = RT_MIN(pDisk->LCHSGeometry.cHeads, 255);
8497 pDisk->LCHSGeometry.cSectors = RT_MIN(pDisk->LCHSGeometry.cSectors, 63);
8498 }
8499 }
8500 }
8501 else
8502 {
8503 VDGEOMETRY LCHS;
8504 rc = pImage->Backend->pfnGetLCHSGeometry(pImage->pBackendData,
8505 &LCHS);
8506 if ( RT_FAILURE(rc)
8507 || pLCHSGeometry->cCylinders != LCHS.cCylinders
8508 || pLCHSGeometry->cHeads != LCHS.cHeads
8509 || pLCHSGeometry->cSectors != LCHS.cSectors)
8510 {
8511 /* Only update geometry if it is changed. Avoids similar checks
8512 * in every backend. Most of the time the new geometry is set
8513 * to the previous values, so no need to go through the hassle
8514 * of updating an image which could be opened in read-only mode
8515 * right now. */
8516 rc = pImage->Backend->pfnSetLCHSGeometry(pImage->pBackendData,
8517 pLCHSGeometry);
8518 }
8519 }
8520 } while (0);
8521
8522 if (RT_UNLIKELY(fLockWrite))
8523 {
8524 rc2 = vdThreadFinishWrite(pDisk);
8525 AssertRC(rc2);
8526 }
8527
8528 LogFlowFunc(("returns %Rrc\n", rc));
8529 return rc;
8530}
8531
8532/**
8533 * Get version of image in HDD container.
8534 *
8535 * @returns VBox status code.
8536 * @returns VERR_VD_IMAGE_NOT_FOUND if image with specified number was not opened.
8537 * @param pDisk Pointer to HDD container.
8538 * @param nImage Image number, counts from 0. 0 is always base image of container.
8539 * @param puVersion Where to store the image version.
8540 */
8541VBOXDDU_DECL(int) VDGetVersion(PVBOXHDD pDisk, unsigned nImage,
8542 unsigned *puVersion)
8543{
8544 int rc = VINF_SUCCESS;
8545 int rc2;
8546 bool fLockRead = false;
8547
8548 LogFlowFunc(("pDisk=%#p nImage=%u puVersion=%#p\n",
8549 pDisk, nImage, puVersion));
8550 do
8551 {
8552 /* sanity check */
8553 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
8554 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
8555
8556 /* Check arguments. */
8557 AssertMsgBreakStmt(VALID_PTR(puVersion),
8558 ("puVersion=%#p\n", puVersion),
8559 rc = VERR_INVALID_PARAMETER);
8560
8561 rc2 = vdThreadStartRead(pDisk);
8562 AssertRC(rc2);
8563 fLockRead = true;
8564
8565 PVDIMAGE pImage = vdGetImageByNumber(pDisk, nImage);
8566 AssertPtrBreakStmt(pImage, rc = VERR_VD_IMAGE_NOT_FOUND);
8567
8568 *puVersion = pImage->Backend->pfnGetVersion(pImage->pBackendData);
8569 } while (0);
8570
8571 if (RT_UNLIKELY(fLockRead))
8572 {
8573 rc2 = vdThreadFinishRead(pDisk);
8574 AssertRC(rc2);
8575 }
8576
8577 LogFlowFunc(("returns %Rrc uVersion=%#x\n", rc, *puVersion));
8578 return rc;
8579}
8580
8581/**
8582 * List the capabilities of image backend in HDD container.
8583 *
8584 * @returns VBox status code.
8585 * @returns VERR_VD_IMAGE_NOT_FOUND if image with specified number was not opened.
8586 * @param pDisk Pointer to the HDD container.
8587 * @param nImage Image number, counts from 0. 0 is always base image of container.
8588 * @param pbackendInfo Where to store the backend information.
8589 */
8590VBOXDDU_DECL(int) VDBackendInfoSingle(PVBOXHDD pDisk, unsigned nImage,
8591 PVDBACKENDINFO pBackendInfo)
8592{
8593 int rc = VINF_SUCCESS;
8594 int rc2;
8595 bool fLockRead = false;
8596
8597 LogFlowFunc(("pDisk=%#p nImage=%u pBackendInfo=%#p\n",
8598 pDisk, nImage, pBackendInfo));
8599 do
8600 {
8601 /* sanity check */
8602 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
8603 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
8604
8605 /* Check arguments. */
8606 AssertMsgBreakStmt(VALID_PTR(pBackendInfo),
8607 ("pBackendInfo=%#p\n", pBackendInfo),
8608 rc = VERR_INVALID_PARAMETER);
8609
8610 rc2 = vdThreadStartRead(pDisk);
8611 AssertRC(rc2);
8612 fLockRead = true;
8613
8614 PVDIMAGE pImage = vdGetImageByNumber(pDisk, nImage);
8615 AssertPtrBreakStmt(pImage, rc = VERR_VD_IMAGE_NOT_FOUND);
8616
8617 pBackendInfo->pszBackend = pImage->Backend->pszBackendName;
8618 pBackendInfo->uBackendCaps = pImage->Backend->uBackendCaps;
8619 pBackendInfo->paFileExtensions = pImage->Backend->paFileExtensions;
8620 pBackendInfo->paConfigInfo = pImage->Backend->paConfigInfo;
8621 } while (0);
8622
8623 if (RT_UNLIKELY(fLockRead))
8624 {
8625 rc2 = vdThreadFinishRead(pDisk);
8626 AssertRC(rc2);
8627 }
8628
8629 LogFlowFunc(("returns %Rrc\n", rc));
8630 return rc;
8631}
8632
8633/**
8634 * Get flags of image in HDD container.
8635 *
8636 * @returns VBox status code.
8637 * @returns VERR_VD_IMAGE_NOT_FOUND if image with specified number was not opened.
8638 * @param pDisk Pointer to HDD container.
8639 * @param nImage Image number, counts from 0. 0 is always base image of container.
8640 * @param puImageFlags Where to store the image flags.
8641 */
8642VBOXDDU_DECL(int) VDGetImageFlags(PVBOXHDD pDisk, unsigned nImage,
8643 unsigned *puImageFlags)
8644{
8645 int rc = VINF_SUCCESS;
8646 int rc2;
8647 bool fLockRead = false;
8648
8649 LogFlowFunc(("pDisk=%#p nImage=%u puImageFlags=%#p\n",
8650 pDisk, nImage, puImageFlags));
8651 do
8652 {
8653 /* sanity check */
8654 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
8655 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
8656
8657 /* Check arguments. */
8658 AssertMsgBreakStmt(VALID_PTR(puImageFlags),
8659 ("puImageFlags=%#p\n", puImageFlags),
8660 rc = VERR_INVALID_PARAMETER);
8661
8662 rc2 = vdThreadStartRead(pDisk);
8663 AssertRC(rc2);
8664 fLockRead = true;
8665
8666 PVDIMAGE pImage = vdGetImageByNumber(pDisk, nImage);
8667 AssertPtrBreakStmt(pImage, rc = VERR_VD_IMAGE_NOT_FOUND);
8668
8669 *puImageFlags = pImage->uImageFlags;
8670 } while (0);
8671
8672 if (RT_UNLIKELY(fLockRead))
8673 {
8674 rc2 = vdThreadFinishRead(pDisk);
8675 AssertRC(rc2);
8676 }
8677
8678 LogFlowFunc(("returns %Rrc uImageFlags=%#x\n", rc, *puImageFlags));
8679 return rc;
8680}
8681
8682/**
8683 * Get open flags of image in HDD container.
8684 *
8685 * @returns VBox status code.
8686 * @returns VERR_VD_IMAGE_NOT_FOUND if image with specified number was not opened.
8687 * @param pDisk Pointer to HDD container.
8688 * @param nImage Image number, counts from 0. 0 is always base image of container.
8689 * @param puOpenFlags Where to store the image open flags.
8690 */
8691VBOXDDU_DECL(int) VDGetOpenFlags(PVBOXHDD pDisk, unsigned nImage,
8692 unsigned *puOpenFlags)
8693{
8694 int rc = VINF_SUCCESS;
8695 int rc2;
8696 bool fLockRead = false;
8697
8698 LogFlowFunc(("pDisk=%#p nImage=%u puOpenFlags=%#p\n",
8699 pDisk, nImage, puOpenFlags));
8700 do
8701 {
8702 /* sanity check */
8703 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
8704 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
8705
8706 /* Check arguments. */
8707 AssertMsgBreakStmt(VALID_PTR(puOpenFlags),
8708 ("puOpenFlags=%#p\n", puOpenFlags),
8709 rc = VERR_INVALID_PARAMETER);
8710
8711 rc2 = vdThreadStartRead(pDisk);
8712 AssertRC(rc2);
8713 fLockRead = true;
8714
8715 PVDIMAGE pImage = vdGetImageByNumber(pDisk, nImage);
8716 AssertPtrBreakStmt(pImage, rc = VERR_VD_IMAGE_NOT_FOUND);
8717
8718 *puOpenFlags = pImage->Backend->pfnGetOpenFlags(pImage->pBackendData);
8719 } while (0);
8720
8721 if (RT_UNLIKELY(fLockRead))
8722 {
8723 rc2 = vdThreadFinishRead(pDisk);
8724 AssertRC(rc2);
8725 }
8726
8727 LogFlowFunc(("returns %Rrc uOpenFlags=%#x\n", rc, *puOpenFlags));
8728 return rc;
8729}
8730
8731/**
8732 * Set open flags of image in HDD container.
8733 * This operation may cause file locking changes and/or files being reopened.
8734 * Note that in case of unrecoverable error all images in HDD container will be closed.
8735 *
8736 * @returns VBox status code.
8737 * @returns VERR_VD_IMAGE_NOT_FOUND if image with specified number was not opened.
8738 * @param pDisk Pointer to HDD container.
8739 * @param nImage Image number, counts from 0. 0 is always base image of container.
8740 * @param uOpenFlags Image file open mode, see VD_OPEN_FLAGS_* constants.
8741 */
8742VBOXDDU_DECL(int) VDSetOpenFlags(PVBOXHDD pDisk, unsigned nImage,
8743 unsigned uOpenFlags)
8744{
8745 int rc;
8746 int rc2;
8747 bool fLockWrite = false;
8748
8749 LogFlowFunc(("pDisk=%#p uOpenFlags=%#u\n", pDisk, uOpenFlags));
8750 do
8751 {
8752 /* sanity check */
8753 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
8754 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
8755
8756 /* Check arguments. */
8757 AssertMsgBreakStmt((uOpenFlags & ~VD_OPEN_FLAGS_MASK) == 0,
8758 ("uOpenFlags=%#x\n", uOpenFlags),
8759 rc = VERR_INVALID_PARAMETER);
8760
8761 rc2 = vdThreadStartWrite(pDisk);
8762 AssertRC(rc2);
8763 fLockWrite = true;
8764
8765 /* Destroy any discard state because the image might be changed to readonly mode. */
8766 rc = vdDiscardStateDestroy(pDisk);
8767 if (RT_FAILURE(rc))
8768 break;
8769
8770 PVDIMAGE pImage = vdGetImageByNumber(pDisk, nImage);
8771 AssertPtrBreakStmt(pImage, rc = VERR_VD_IMAGE_NOT_FOUND);
8772
8773 rc = pImage->Backend->pfnSetOpenFlags(pImage->pBackendData,
8774 uOpenFlags & ~(VD_OPEN_FLAGS_HONOR_SAME | VD_OPEN_FLAGS_IGNORE_FLUSH | VD_OPEN_FLAGS_INFORM_ABOUT_ZERO_BLOCKS));
8775 if (RT_SUCCESS(rc))
8776 pImage->uOpenFlags = uOpenFlags & (VD_OPEN_FLAGS_HONOR_SAME | VD_OPEN_FLAGS_DISCARD | VD_OPEN_FLAGS_IGNORE_FLUSH | VD_OPEN_FLAGS_INFORM_ABOUT_ZERO_BLOCKS);
8777 } while (0);
8778
8779 if (RT_UNLIKELY(fLockWrite))
8780 {
8781 rc2 = vdThreadFinishWrite(pDisk);
8782 AssertRC(rc2);
8783 }
8784
8785 LogFlowFunc(("returns %Rrc\n", rc));
8786 return rc;
8787}
8788
8789/**
8790 * Get base filename of image in HDD container. Some image formats use
8791 * other filenames as well, so don't use this for anything but informational
8792 * purposes.
8793 *
8794 * @returns VBox status code.
8795 * @returns VERR_VD_IMAGE_NOT_FOUND if image with specified number was not opened.
8796 * @returns VERR_BUFFER_OVERFLOW if pszFilename buffer too small to hold filename.
8797 * @param pDisk Pointer to HDD container.
8798 * @param nImage Image number, counts from 0. 0 is always base image of container.
8799 * @param pszFilename Where to store the image file name.
8800 * @param cbFilename Size of buffer pszFilename points to.
8801 */
8802VBOXDDU_DECL(int) VDGetFilename(PVBOXHDD pDisk, unsigned nImage,
8803 char *pszFilename, unsigned cbFilename)
8804{
8805 int rc;
8806 int rc2;
8807 bool fLockRead = false;
8808
8809 LogFlowFunc(("pDisk=%#p nImage=%u pszFilename=%#p cbFilename=%u\n",
8810 pDisk, nImage, pszFilename, cbFilename));
8811 do
8812 {
8813 /* sanity check */
8814 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
8815 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
8816
8817 /* Check arguments. */
8818 AssertMsgBreakStmt(VALID_PTR(pszFilename) && *pszFilename,
8819 ("pszFilename=%#p \"%s\"\n", pszFilename, pszFilename),
8820 rc = VERR_INVALID_PARAMETER);
8821 AssertMsgBreakStmt(cbFilename,
8822 ("cbFilename=%u\n", cbFilename),
8823 rc = VERR_INVALID_PARAMETER);
8824
8825 rc2 = vdThreadStartRead(pDisk);
8826 AssertRC(rc2);
8827 fLockRead = true;
8828
8829 PVDIMAGE pImage = vdGetImageByNumber(pDisk, nImage);
8830 AssertPtrBreakStmt(pImage, rc = VERR_VD_IMAGE_NOT_FOUND);
8831
8832 size_t cb = strlen(pImage->pszFilename);
8833 if (cb <= cbFilename)
8834 {
8835 strcpy(pszFilename, pImage->pszFilename);
8836 rc = VINF_SUCCESS;
8837 }
8838 else
8839 {
8840 strncpy(pszFilename, pImage->pszFilename, cbFilename - 1);
8841 pszFilename[cbFilename - 1] = '\0';
8842 rc = VERR_BUFFER_OVERFLOW;
8843 }
8844 } while (0);
8845
8846 if (RT_UNLIKELY(fLockRead))
8847 {
8848 rc2 = vdThreadFinishRead(pDisk);
8849 AssertRC(rc2);
8850 }
8851
8852 LogFlowFunc(("returns %Rrc, pszFilename=\"%s\"\n", rc, pszFilename));
8853 return rc;
8854}
8855
8856/**
8857 * Get the comment line of image in HDD container.
8858 *
8859 * @returns VBox status code.
8860 * @returns VERR_VD_IMAGE_NOT_FOUND if image with specified number was not opened.
8861 * @returns VERR_BUFFER_OVERFLOW if pszComment buffer too small to hold comment text.
8862 * @param pDisk Pointer to HDD container.
8863 * @param nImage Image number, counts from 0. 0 is always base image of container.
8864 * @param pszComment Where to store the comment string of image. NULL is ok.
8865 * @param cbComment The size of pszComment buffer. 0 is ok.
8866 */
8867VBOXDDU_DECL(int) VDGetComment(PVBOXHDD pDisk, unsigned nImage,
8868 char *pszComment, unsigned cbComment)
8869{
8870 int rc;
8871 int rc2;
8872 bool fLockRead = false;
8873
8874 LogFlowFunc(("pDisk=%#p nImage=%u pszComment=%#p cbComment=%u\n",
8875 pDisk, nImage, pszComment, cbComment));
8876 do
8877 {
8878 /* sanity check */
8879 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
8880 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
8881
8882 /* Check arguments. */
8883 AssertMsgBreakStmt(VALID_PTR(pszComment),
8884 ("pszComment=%#p \"%s\"\n", pszComment, pszComment),
8885 rc = VERR_INVALID_PARAMETER);
8886 AssertMsgBreakStmt(cbComment,
8887 ("cbComment=%u\n", cbComment),
8888 rc = VERR_INVALID_PARAMETER);
8889
8890 rc2 = vdThreadStartRead(pDisk);
8891 AssertRC(rc2);
8892 fLockRead = true;
8893
8894 PVDIMAGE pImage = vdGetImageByNumber(pDisk, nImage);
8895 AssertPtrBreakStmt(pImage, rc = VERR_VD_IMAGE_NOT_FOUND);
8896
8897 rc = pImage->Backend->pfnGetComment(pImage->pBackendData, pszComment,
8898 cbComment);
8899 } while (0);
8900
8901 if (RT_UNLIKELY(fLockRead))
8902 {
8903 rc2 = vdThreadFinishRead(pDisk);
8904 AssertRC(rc2);
8905 }
8906
8907 LogFlowFunc(("returns %Rrc, pszComment=\"%s\"\n", rc, pszComment));
8908 return rc;
8909}
8910
8911/**
8912 * Changes the comment line of image in HDD container.
8913 *
8914 * @returns VBox status code.
8915 * @returns VERR_VD_IMAGE_NOT_FOUND if image with specified number was not opened.
8916 * @param pDisk Pointer to HDD container.
8917 * @param nImage Image number, counts from 0. 0 is always base image of container.
8918 * @param pszComment New comment string (UTF-8). NULL is allowed to reset the comment.
8919 */
8920VBOXDDU_DECL(int) VDSetComment(PVBOXHDD pDisk, unsigned nImage,
8921 const char *pszComment)
8922{
8923 int rc;
8924 int rc2;
8925 bool fLockWrite = false;
8926
8927 LogFlowFunc(("pDisk=%#p nImage=%u pszComment=%#p \"%s\"\n",
8928 pDisk, nImage, pszComment, pszComment));
8929 do
8930 {
8931 /* sanity check */
8932 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
8933 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
8934
8935 /* Check arguments. */
8936 AssertMsgBreakStmt(VALID_PTR(pszComment) || pszComment == NULL,
8937 ("pszComment=%#p \"%s\"\n", pszComment, pszComment),
8938 rc = VERR_INVALID_PARAMETER);
8939
8940 rc2 = vdThreadStartWrite(pDisk);
8941 AssertRC(rc2);
8942 fLockWrite = true;
8943
8944 PVDIMAGE pImage = vdGetImageByNumber(pDisk, nImage);
8945 AssertPtrBreakStmt(pImage, rc = VERR_VD_IMAGE_NOT_FOUND);
8946
8947 rc = pImage->Backend->pfnSetComment(pImage->pBackendData, pszComment);
8948 } while (0);
8949
8950 if (RT_UNLIKELY(fLockWrite))
8951 {
8952 rc2 = vdThreadFinishWrite(pDisk);
8953 AssertRC(rc2);
8954 }
8955
8956 LogFlowFunc(("returns %Rrc\n", rc));
8957 return rc;
8958}
8959
8960
8961/**
8962 * Get UUID of image in HDD container.
8963 *
8964 * @returns VBox status code.
8965 * @returns VERR_VD_IMAGE_NOT_FOUND if image with specified number was not opened.
8966 * @param pDisk Pointer to HDD container.
8967 * @param nImage Image number, counts from 0. 0 is always base image of container.
8968 * @param pUuid Where to store the image creation UUID.
8969 */
8970VBOXDDU_DECL(int) VDGetUuid(PVBOXHDD pDisk, unsigned nImage, PRTUUID pUuid)
8971{
8972 int rc;
8973 int rc2;
8974 bool fLockRead = false;
8975
8976 LogFlowFunc(("pDisk=%#p nImage=%u pUuid=%#p\n", pDisk, nImage, pUuid));
8977 do
8978 {
8979 /* sanity check */
8980 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
8981 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
8982
8983 /* Check arguments. */
8984 AssertMsgBreakStmt(VALID_PTR(pUuid),
8985 ("pUuid=%#p\n", pUuid),
8986 rc = VERR_INVALID_PARAMETER);
8987
8988 rc2 = vdThreadStartRead(pDisk);
8989 AssertRC(rc2);
8990 fLockRead = true;
8991
8992 PVDIMAGE pImage = vdGetImageByNumber(pDisk, nImage);
8993 AssertPtrBreakStmt(pImage, rc = VERR_VD_IMAGE_NOT_FOUND);
8994
8995 rc = pImage->Backend->pfnGetUuid(pImage->pBackendData, pUuid);
8996 } while (0);
8997
8998 if (RT_UNLIKELY(fLockRead))
8999 {
9000 rc2 = vdThreadFinishRead(pDisk);
9001 AssertRC(rc2);
9002 }
9003
9004 LogFlowFunc(("returns %Rrc, Uuid={%RTuuid}\n", rc, pUuid));
9005 return rc;
9006}
9007
9008/**
9009 * Set the image's UUID. Should not be used by normal applications.
9010 *
9011 * @returns VBox status code.
9012 * @returns VERR_VD_IMAGE_NOT_FOUND if image with specified number was not opened.
9013 * @param pDisk Pointer to HDD container.
9014 * @param nImage Image number, counts from 0. 0 is always base image of container.
9015 * @param pUuid New UUID of the image. If NULL, a new UUID is created.
9016 */
9017VBOXDDU_DECL(int) VDSetUuid(PVBOXHDD pDisk, unsigned nImage, PCRTUUID pUuid)
9018{
9019 int rc;
9020 int rc2;
9021 bool fLockWrite = false;
9022
9023 LogFlowFunc(("pDisk=%#p nImage=%u pUuid=%#p {%RTuuid}\n",
9024 pDisk, nImage, pUuid, pUuid));
9025 do
9026 {
9027 /* sanity check */
9028 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
9029 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
9030
9031 AssertMsgBreakStmt(VALID_PTR(pUuid) || pUuid == NULL,
9032 ("pUuid=%#p\n", pUuid),
9033 rc = VERR_INVALID_PARAMETER);
9034
9035 rc2 = vdThreadStartWrite(pDisk);
9036 AssertRC(rc2);
9037 fLockWrite = true;
9038
9039 PVDIMAGE pImage = vdGetImageByNumber(pDisk, nImage);
9040 AssertPtrBreakStmt(pImage, rc = VERR_VD_IMAGE_NOT_FOUND);
9041
9042 RTUUID Uuid;
9043 if (!pUuid)
9044 {
9045 RTUuidCreate(&Uuid);
9046 pUuid = &Uuid;
9047 }
9048 rc = pImage->Backend->pfnSetUuid(pImage->pBackendData, pUuid);
9049 } while (0);
9050
9051 if (RT_UNLIKELY(fLockWrite))
9052 {
9053 rc2 = vdThreadFinishWrite(pDisk);
9054 AssertRC(rc2);
9055 }
9056
9057 LogFlowFunc(("returns %Rrc\n", rc));
9058 return rc;
9059}
9060
9061/**
9062 * Get last modification UUID of image in HDD container.
9063 *
9064 * @returns VBox status code.
9065 * @returns VERR_VD_IMAGE_NOT_FOUND if image with specified number was not opened.
9066 * @param pDisk Pointer to HDD container.
9067 * @param nImage Image number, counts from 0. 0 is always base image of container.
9068 * @param pUuid Where to store the image modification UUID.
9069 */
9070VBOXDDU_DECL(int) VDGetModificationUuid(PVBOXHDD pDisk, unsigned nImage, PRTUUID pUuid)
9071{
9072 int rc = VINF_SUCCESS;
9073 int rc2;
9074 bool fLockRead = false;
9075
9076 LogFlowFunc(("pDisk=%#p nImage=%u pUuid=%#p\n", pDisk, nImage, pUuid));
9077 do
9078 {
9079 /* sanity check */
9080 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
9081 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
9082
9083 /* Check arguments. */
9084 AssertMsgBreakStmt(VALID_PTR(pUuid),
9085 ("pUuid=%#p\n", pUuid),
9086 rc = VERR_INVALID_PARAMETER);
9087
9088 rc2 = vdThreadStartRead(pDisk);
9089 AssertRC(rc2);
9090 fLockRead = true;
9091
9092 PVDIMAGE pImage = vdGetImageByNumber(pDisk, nImage);
9093 AssertPtrBreakStmt(pImage, rc = VERR_VD_IMAGE_NOT_FOUND);
9094
9095 rc = pImage->Backend->pfnGetModificationUuid(pImage->pBackendData,
9096 pUuid);
9097 } while (0);
9098
9099 if (RT_UNLIKELY(fLockRead))
9100 {
9101 rc2 = vdThreadFinishRead(pDisk);
9102 AssertRC(rc2);
9103 }
9104
9105 LogFlowFunc(("returns %Rrc, Uuid={%RTuuid}\n", rc, pUuid));
9106 return rc;
9107}
9108
9109/**
9110 * Set the image's last modification UUID. Should not be used by normal applications.
9111 *
9112 * @returns VBox status code.
9113 * @returns VERR_VD_IMAGE_NOT_FOUND if image with specified number was not opened.
9114 * @param pDisk Pointer to HDD container.
9115 * @param nImage Image number, counts from 0. 0 is always base image of container.
9116 * @param pUuid New modification UUID of the image. If NULL, a new UUID is created.
9117 */
9118VBOXDDU_DECL(int) VDSetModificationUuid(PVBOXHDD pDisk, unsigned nImage, PCRTUUID pUuid)
9119{
9120 int rc;
9121 int rc2;
9122 bool fLockWrite = false;
9123
9124 LogFlowFunc(("pDisk=%#p nImage=%u pUuid=%#p {%RTuuid}\n",
9125 pDisk, nImage, pUuid, pUuid));
9126 do
9127 {
9128 /* sanity check */
9129 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
9130 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
9131
9132 /* Check arguments. */
9133 AssertMsgBreakStmt(VALID_PTR(pUuid) || pUuid == NULL,
9134 ("pUuid=%#p\n", pUuid),
9135 rc = VERR_INVALID_PARAMETER);
9136
9137 rc2 = vdThreadStartWrite(pDisk);
9138 AssertRC(rc2);
9139 fLockWrite = true;
9140
9141 PVDIMAGE pImage = vdGetImageByNumber(pDisk, nImage);
9142 AssertPtrBreakStmt(pImage, rc = VERR_VD_IMAGE_NOT_FOUND);
9143
9144 RTUUID Uuid;
9145 if (!pUuid)
9146 {
9147 RTUuidCreate(&Uuid);
9148 pUuid = &Uuid;
9149 }
9150 rc = pImage->Backend->pfnSetModificationUuid(pImage->pBackendData,
9151 pUuid);
9152 } while (0);
9153
9154 if (RT_UNLIKELY(fLockWrite))
9155 {
9156 rc2 = vdThreadFinishWrite(pDisk);
9157 AssertRC(rc2);
9158 }
9159
9160 LogFlowFunc(("returns %Rrc\n", rc));
9161 return rc;
9162}
9163
9164/**
9165 * Get parent UUID of image in HDD container.
9166 *
9167 * @returns VBox status code.
9168 * @returns VERR_VD_IMAGE_NOT_FOUND if image with specified number was not opened.
9169 * @param pDisk Pointer to HDD container.
9170 * @param nImage Image number, counts from 0. 0 is always base image of container.
9171 * @param pUuid Where to store the parent image UUID.
9172 */
9173VBOXDDU_DECL(int) VDGetParentUuid(PVBOXHDD pDisk, unsigned nImage,
9174 PRTUUID pUuid)
9175{
9176 int rc = VINF_SUCCESS;
9177 int rc2;
9178 bool fLockRead = false;
9179
9180 LogFlowFunc(("pDisk=%#p nImage=%u pUuid=%#p\n", pDisk, nImage, pUuid));
9181 do
9182 {
9183 /* sanity check */
9184 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
9185 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
9186
9187 /* Check arguments. */
9188 AssertMsgBreakStmt(VALID_PTR(pUuid),
9189 ("pUuid=%#p\n", pUuid),
9190 rc = VERR_INVALID_PARAMETER);
9191
9192 rc2 = vdThreadStartRead(pDisk);
9193 AssertRC(rc2);
9194 fLockRead = true;
9195
9196 PVDIMAGE pImage = vdGetImageByNumber(pDisk, nImage);
9197 AssertPtrBreakStmt(pImage, rc = VERR_VD_IMAGE_NOT_FOUND);
9198
9199 rc = pImage->Backend->pfnGetParentUuid(pImage->pBackendData, pUuid);
9200 } while (0);
9201
9202 if (RT_UNLIKELY(fLockRead))
9203 {
9204 rc2 = vdThreadFinishRead(pDisk);
9205 AssertRC(rc2);
9206 }
9207
9208 LogFlowFunc(("returns %Rrc, Uuid={%RTuuid}\n", rc, pUuid));
9209 return rc;
9210}
9211
9212/**
9213 * Set the image's parent UUID. Should not be used by normal applications.
9214 *
9215 * @returns VBox status code.
9216 * @param pDisk Pointer to HDD container.
9217 * @param nImage Image number, counts from 0. 0 is always base image of container.
9218 * @param pUuid New parent UUID of the image. If NULL, a new UUID is created.
9219 */
9220VBOXDDU_DECL(int) VDSetParentUuid(PVBOXHDD pDisk, unsigned nImage,
9221 PCRTUUID pUuid)
9222{
9223 int rc;
9224 int rc2;
9225 bool fLockWrite = false;
9226
9227 LogFlowFunc(("pDisk=%#p nImage=%u pUuid=%#p {%RTuuid}\n",
9228 pDisk, nImage, pUuid, pUuid));
9229 do
9230 {
9231 /* sanity check */
9232 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
9233 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
9234
9235 /* Check arguments. */
9236 AssertMsgBreakStmt(VALID_PTR(pUuid) || pUuid == NULL,
9237 ("pUuid=%#p\n", pUuid),
9238 rc = VERR_INVALID_PARAMETER);
9239
9240 rc2 = vdThreadStartWrite(pDisk);
9241 AssertRC(rc2);
9242 fLockWrite = true;
9243
9244 PVDIMAGE pImage = vdGetImageByNumber(pDisk, nImage);
9245 AssertPtrBreakStmt(pImage, rc = VERR_VD_IMAGE_NOT_FOUND);
9246
9247 RTUUID Uuid;
9248 if (!pUuid)
9249 {
9250 RTUuidCreate(&Uuid);
9251 pUuid = &Uuid;
9252 }
9253 rc = pImage->Backend->pfnSetParentUuid(pImage->pBackendData, pUuid);
9254 } while (0);
9255
9256 if (RT_UNLIKELY(fLockWrite))
9257 {
9258 rc2 = vdThreadFinishWrite(pDisk);
9259 AssertRC(rc2);
9260 }
9261
9262 LogFlowFunc(("returns %Rrc\n", rc));
9263 return rc;
9264}
9265
9266
9267/**
9268 * Debug helper - dumps all opened images in HDD container into the log file.
9269 *
9270 * @param pDisk Pointer to HDD container.
9271 */
9272VBOXDDU_DECL(void) VDDumpImages(PVBOXHDD pDisk)
9273{
9274 int rc2;
9275 bool fLockRead = false;
9276
9277 do
9278 {
9279 /* sanity check */
9280 AssertPtrBreak(pDisk);
9281 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
9282
9283 if (!pDisk->pInterfaceError || !VALID_PTR(pDisk->pInterfaceError->pfnMessage))
9284 pDisk->pInterfaceError->pfnMessage = vdLogMessage;
9285
9286 rc2 = vdThreadStartRead(pDisk);
9287 AssertRC(rc2);
9288 fLockRead = true;
9289
9290 vdMessageWrapper(pDisk, "--- Dumping VD Disk, Images=%u\n", pDisk->cImages);
9291 for (PVDIMAGE pImage = pDisk->pBase; pImage; pImage = pImage->pNext)
9292 {
9293 vdMessageWrapper(pDisk, "Dumping VD image \"%s\" (Backend=%s)\n",
9294 pImage->pszFilename, pImage->Backend->pszBackendName);
9295 pImage->Backend->pfnDump(pImage->pBackendData);
9296 }
9297 } while (0);
9298
9299 if (RT_UNLIKELY(fLockRead))
9300 {
9301 rc2 = vdThreadFinishRead(pDisk);
9302 AssertRC(rc2);
9303 }
9304}
9305
9306
9307VBOXDDU_DECL(int) VDDiscardRanges(PVBOXHDD pDisk, PCRTRANGE paRanges, unsigned cRanges)
9308{
9309 int rc;
9310 int rc2;
9311 bool fLockWrite = false;
9312
9313 LogFlowFunc(("pDisk=%#p paRanges=%#p cRanges=%u\n",
9314 pDisk, paRanges, cRanges));
9315 do
9316 {
9317 /* sanity check */
9318 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
9319 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
9320
9321 /* Check arguments. */
9322 AssertMsgBreakStmt(cRanges,
9323 ("cRanges=%u\n", cRanges),
9324 rc = VERR_INVALID_PARAMETER);
9325 AssertMsgBreakStmt(VALID_PTR(paRanges),
9326 ("paRanges=%#p\n", paRanges),
9327 rc = VERR_INVALID_PARAMETER);
9328
9329 rc2 = vdThreadStartWrite(pDisk);
9330 AssertRC(rc2);
9331 fLockWrite = true;
9332
9333 AssertPtrBreakStmt(pDisk->pLast, rc = VERR_VD_NOT_OPENED);
9334
9335 AssertMsgBreakStmt(pDisk->pLast->uOpenFlags & VD_OPEN_FLAGS_DISCARD,
9336 ("Discarding not supported\n"),
9337 rc = VERR_NOT_SUPPORTED);
9338
9339 vdSetModifiedFlag(pDisk);
9340 rc = vdDiscardHelper(pDisk, paRanges, cRanges);
9341 } while (0);
9342
9343 if (RT_UNLIKELY(fLockWrite))
9344 {
9345 rc2 = vdThreadFinishWrite(pDisk);
9346 AssertRC(rc2);
9347 }
9348
9349 LogFlowFunc(("returns %Rrc\n", rc));
9350 return rc;
9351}
9352
9353
9354VBOXDDU_DECL(int) VDAsyncRead(PVBOXHDD pDisk, uint64_t uOffset, size_t cbRead,
9355 PCRTSGBUF pcSgBuf,
9356 PFNVDASYNCTRANSFERCOMPLETE pfnComplete,
9357 void *pvUser1, void *pvUser2)
9358{
9359 int rc = VERR_VD_BLOCK_FREE;
9360 int rc2;
9361 bool fLockRead = false;
9362 PVDIOCTX pIoCtx = NULL;
9363
9364 LogFlowFunc(("pDisk=%#p uOffset=%llu pcSgBuf=%#p cbRead=%zu pvUser1=%#p pvUser2=%#p\n",
9365 pDisk, uOffset, pcSgBuf, cbRead, pvUser1, pvUser2));
9366
9367 do
9368 {
9369 /* sanity check */
9370 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
9371 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
9372
9373 /* Check arguments. */
9374 AssertMsgBreakStmt(cbRead,
9375 ("cbRead=%zu\n", cbRead),
9376 rc = VERR_INVALID_PARAMETER);
9377 AssertMsgBreakStmt(VALID_PTR(pcSgBuf),
9378 ("pcSgBuf=%#p\n", pcSgBuf),
9379 rc = VERR_INVALID_PARAMETER);
9380
9381 rc2 = vdThreadStartRead(pDisk);
9382 AssertRC(rc2);
9383 fLockRead = true;
9384
9385 AssertMsgBreakStmt(uOffset + cbRead <= pDisk->cbSize,
9386 ("uOffset=%llu cbRead=%zu pDisk->cbSize=%llu\n",
9387 uOffset, cbRead, pDisk->cbSize),
9388 rc = VERR_INVALID_PARAMETER);
9389 AssertPtrBreakStmt(pDisk->pLast, rc = VERR_VD_NOT_OPENED);
9390
9391 pIoCtx = vdIoCtxRootAlloc(pDisk, VDIOCTXTXDIR_READ, uOffset,
9392 cbRead, pDisk->pLast, pcSgBuf,
9393 pfnComplete, pvUser1, pvUser2,
9394 NULL, vdReadHelperAsync);
9395 if (!pIoCtx)
9396 {
9397 rc = VERR_NO_MEMORY;
9398 break;
9399 }
9400
9401#if 0
9402 rc = vdIoCtxProcessTryLockDefer(pIoCtx);
9403#else
9404 rc = vdIoCtxProcess(pIoCtx);
9405#endif
9406 if (rc == VINF_VD_ASYNC_IO_FINISHED)
9407 {
9408 if (ASMAtomicCmpXchgBool(&pIoCtx->fComplete, true, false))
9409 vdIoCtxFree(pDisk, pIoCtx);
9410 else
9411 rc = VERR_VD_ASYNC_IO_IN_PROGRESS; /* Let the other handler complete the request. */
9412 }
9413 else if (rc != VERR_VD_ASYNC_IO_IN_PROGRESS) /* Another error */
9414 vdIoCtxFree(pDisk, pIoCtx);
9415
9416 } while (0);
9417
9418 if (RT_UNLIKELY(fLockRead) && ( rc == VINF_VD_ASYNC_IO_FINISHED
9419 || rc != VERR_VD_ASYNC_IO_IN_PROGRESS))
9420 {
9421 rc2 = vdThreadFinishRead(pDisk);
9422 AssertRC(rc2);
9423 }
9424
9425 LogFlowFunc(("returns %Rrc\n", rc));
9426 return rc;
9427}
9428
9429
9430VBOXDDU_DECL(int) VDAsyncWrite(PVBOXHDD pDisk, uint64_t uOffset, size_t cbWrite,
9431 PCRTSGBUF pcSgBuf,
9432 PFNVDASYNCTRANSFERCOMPLETE pfnComplete,
9433 void *pvUser1, void *pvUser2)
9434{
9435 int rc;
9436 int rc2;
9437 bool fLockWrite = false;
9438 PVDIOCTX pIoCtx = NULL;
9439
9440 LogFlowFunc(("pDisk=%#p uOffset=%llu cSgBuf=%#p cbWrite=%zu pvUser1=%#p pvUser2=%#p\n",
9441 pDisk, uOffset, pcSgBuf, cbWrite, pvUser1, pvUser2));
9442 do
9443 {
9444 /* sanity check */
9445 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
9446 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
9447
9448 /* Check arguments. */
9449 AssertMsgBreakStmt(cbWrite,
9450 ("cbWrite=%zu\n", cbWrite),
9451 rc = VERR_INVALID_PARAMETER);
9452 AssertMsgBreakStmt(VALID_PTR(pcSgBuf),
9453 ("pcSgBuf=%#p\n", pcSgBuf),
9454 rc = VERR_INVALID_PARAMETER);
9455
9456 rc2 = vdThreadStartWrite(pDisk);
9457 AssertRC(rc2);
9458 fLockWrite = true;
9459
9460 AssertMsgBreakStmt(uOffset + cbWrite <= pDisk->cbSize,
9461 ("uOffset=%llu cbWrite=%zu pDisk->cbSize=%llu\n",
9462 uOffset, cbWrite, pDisk->cbSize),
9463 rc = VERR_INVALID_PARAMETER);
9464 AssertPtrBreakStmt(pDisk->pLast, rc = VERR_VD_NOT_OPENED);
9465
9466 pIoCtx = vdIoCtxRootAlloc(pDisk, VDIOCTXTXDIR_WRITE, uOffset,
9467 cbWrite, pDisk->pLast, pcSgBuf,
9468 pfnComplete, pvUser1, pvUser2,
9469 NULL, vdWriteHelperAsync);
9470 if (!pIoCtx)
9471 {
9472 rc = VERR_NO_MEMORY;
9473 break;
9474 }
9475
9476#if 0
9477 rc = vdIoCtxProcessTryLockDefer(pIoCtx);
9478#else
9479 rc = vdIoCtxProcess(pIoCtx);
9480#endif
9481 if (rc == VINF_VD_ASYNC_IO_FINISHED)
9482 {
9483 if (ASMAtomicCmpXchgBool(&pIoCtx->fComplete, true, false))
9484 vdIoCtxFree(pDisk, pIoCtx);
9485 else
9486 rc = VERR_VD_ASYNC_IO_IN_PROGRESS; /* Let the other handler complete the request. */
9487 }
9488 else if (rc != VERR_VD_ASYNC_IO_IN_PROGRESS) /* Another error */
9489 vdIoCtxFree(pDisk, pIoCtx);
9490 } while (0);
9491
9492 if (RT_UNLIKELY(fLockWrite) && ( rc == VINF_VD_ASYNC_IO_FINISHED
9493 || rc != VERR_VD_ASYNC_IO_IN_PROGRESS))
9494 {
9495 rc2 = vdThreadFinishWrite(pDisk);
9496 AssertRC(rc2);
9497 }
9498
9499 LogFlowFunc(("returns %Rrc\n", rc));
9500 return rc;
9501}
9502
9503
9504VBOXDDU_DECL(int) VDAsyncFlush(PVBOXHDD pDisk, PFNVDASYNCTRANSFERCOMPLETE pfnComplete,
9505 void *pvUser1, void *pvUser2)
9506{
9507 int rc;
9508 int rc2;
9509 bool fLockWrite = false;
9510 PVDIOCTX pIoCtx = NULL;
9511
9512 LogFlowFunc(("pDisk=%#p\n", pDisk));
9513
9514 do
9515 {
9516 /* sanity check */
9517 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
9518 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
9519
9520 rc2 = vdThreadStartWrite(pDisk);
9521 AssertRC(rc2);
9522 fLockWrite = true;
9523
9524 AssertPtrBreakStmt(pDisk->pLast, rc = VERR_VD_NOT_OPENED);
9525
9526 pIoCtx = vdIoCtxRootAlloc(pDisk, VDIOCTXTXDIR_FLUSH, 0,
9527 0, pDisk->pLast, NULL,
9528 pfnComplete, pvUser1, pvUser2,
9529 NULL, vdFlushHelperAsync);
9530 if (!pIoCtx)
9531 {
9532 rc = VERR_NO_MEMORY;
9533 break;
9534 }
9535
9536#if 0
9537 rc = vdIoCtxProcessTryLockDefer(pIoCtx);
9538#else
9539 rc = vdIoCtxProcess(pIoCtx);
9540#endif
9541 if (rc == VINF_VD_ASYNC_IO_FINISHED)
9542 {
9543 if (ASMAtomicCmpXchgBool(&pIoCtx->fComplete, true, false))
9544 vdIoCtxFree(pDisk, pIoCtx);
9545 else
9546 rc = VERR_VD_ASYNC_IO_IN_PROGRESS; /* Let the other handler complete the request. */
9547 }
9548 else if (rc != VERR_VD_ASYNC_IO_IN_PROGRESS) /* Another error */
9549 vdIoCtxFree(pDisk, pIoCtx);
9550 } while (0);
9551
9552 if (RT_UNLIKELY(fLockWrite) && ( rc == VINF_VD_ASYNC_IO_FINISHED
9553 || rc != VERR_VD_ASYNC_IO_IN_PROGRESS))
9554 {
9555 rc2 = vdThreadFinishWrite(pDisk);
9556 AssertRC(rc2);
9557 }
9558
9559 LogFlowFunc(("returns %Rrc\n", rc));
9560 return rc;
9561}
9562
9563VBOXDDU_DECL(int) VDAsyncDiscardRanges(PVBOXHDD pDisk, PCRTRANGE paRanges, unsigned cRanges,
9564 PFNVDASYNCTRANSFERCOMPLETE pfnComplete,
9565 void *pvUser1, void *pvUser2)
9566{
9567 int rc;
9568 int rc2;
9569 bool fLockWrite = false;
9570 PVDIOCTX pIoCtx = NULL;
9571
9572 LogFlowFunc(("pDisk=%#p\n", pDisk));
9573
9574 do
9575 {
9576 /* sanity check */
9577 AssertPtrBreakStmt(pDisk, rc = VERR_INVALID_PARAMETER);
9578 AssertMsg(pDisk->u32Signature == VBOXHDDDISK_SIGNATURE, ("u32Signature=%08x\n", pDisk->u32Signature));
9579
9580 rc2 = vdThreadStartWrite(pDisk);
9581 AssertRC(rc2);
9582 fLockWrite = true;
9583
9584 AssertPtrBreakStmt(pDisk->pLast, rc = VERR_VD_NOT_OPENED);
9585
9586 pIoCtx = vdIoCtxDiscardAlloc(pDisk, paRanges, cRanges,
9587 pfnComplete, pvUser1, pvUser2, NULL,
9588 vdDiscardHelperAsync);
9589 if (!pIoCtx)
9590 {
9591 rc = VERR_NO_MEMORY;
9592 break;
9593 }
9594
9595#if 0
9596 rc = vdIoCtxProcessTryLockDefer(pIoCtx);
9597#else
9598 rc = vdIoCtxProcess(pIoCtx);
9599#endif
9600 if (rc == VINF_VD_ASYNC_IO_FINISHED)
9601 {
9602 if (ASMAtomicCmpXchgBool(&pIoCtx->fComplete, true, false))
9603 vdIoCtxFree(pDisk, pIoCtx);
9604 else
9605 rc = VERR_VD_ASYNC_IO_IN_PROGRESS; /* Let the other handler complete the request. */
9606 }
9607 else if (rc != VERR_VD_ASYNC_IO_IN_PROGRESS) /* Another error */
9608 vdIoCtxFree(pDisk, pIoCtx);
9609 } while (0);
9610
9611 if (RT_UNLIKELY(fLockWrite) && ( rc == VINF_VD_ASYNC_IO_FINISHED
9612 || rc != VERR_VD_ASYNC_IO_IN_PROGRESS))
9613 {
9614 rc2 = vdThreadFinishWrite(pDisk);
9615 AssertRC(rc2);
9616 }
9617
9618 LogFlowFunc(("returns %Rrc\n", rc));
9619 return rc;
9620}
9621
9622VBOXDDU_DECL(int) VDRepair(PVDINTERFACE pVDIfsDisk, PVDINTERFACE pVDIfsImage,
9623 const char *pszFilename, const char *pszBackend,
9624 uint32_t fFlags)
9625{
9626 int rc = VERR_NOT_SUPPORTED;
9627 PCVBOXHDDBACKEND pBackend = NULL;
9628 VDINTERFACEIOINT VDIfIoInt;
9629 VDINTERFACEIO VDIfIoFallback;
9630 PVDINTERFACEIO pInterfaceIo;
9631
9632 LogFlowFunc(("pszFilename=\"%s\"\n", pszFilename));
9633 /* Check arguments. */
9634 AssertMsgReturn(VALID_PTR(pszFilename) && *pszFilename,
9635 ("pszFilename=%#p \"%s\"\n", pszFilename, pszFilename),
9636 VERR_INVALID_PARAMETER);
9637 AssertMsgReturn(VALID_PTR(pszBackend),
9638 ("pszBackend=%#p\n", pszBackend),
9639 VERR_INVALID_PARAMETER);
9640 AssertMsgReturn((fFlags & ~VD_REPAIR_FLAGS_MASK) == 0,
9641 ("fFlags=%#x\n", fFlags),
9642 VERR_INVALID_PARAMETER);
9643
9644 pInterfaceIo = VDIfIoGet(pVDIfsImage);
9645 if (!pInterfaceIo)
9646 {
9647 /*
9648 * Caller doesn't provide an I/O interface, create our own using the
9649 * native file API.
9650 */
9651 vdIfIoFallbackCallbacksSetup(&VDIfIoFallback);
9652 pInterfaceIo = &VDIfIoFallback;
9653 }
9654
9655 /* Set up the internal I/O interface. */
9656 AssertReturn(!VDIfIoIntGet(pVDIfsImage), VERR_INVALID_PARAMETER);
9657 VDIfIoInt.pfnOpen = vdIOIntOpenLimited;
9658 VDIfIoInt.pfnClose = vdIOIntCloseLimited;
9659 VDIfIoInt.pfnDelete = vdIOIntDeleteLimited;
9660 VDIfIoInt.pfnMove = vdIOIntMoveLimited;
9661 VDIfIoInt.pfnGetFreeSpace = vdIOIntGetFreeSpaceLimited;
9662 VDIfIoInt.pfnGetModificationTime = vdIOIntGetModificationTimeLimited;
9663 VDIfIoInt.pfnGetSize = vdIOIntGetSizeLimited;
9664 VDIfIoInt.pfnSetSize = vdIOIntSetSizeLimited;
9665 VDIfIoInt.pfnReadSync = vdIOIntReadSyncLimited;
9666 VDIfIoInt.pfnWriteSync = vdIOIntWriteSyncLimited;
9667 VDIfIoInt.pfnFlushSync = vdIOIntFlushSyncLimited;
9668 VDIfIoInt.pfnReadUserAsync = NULL;
9669 VDIfIoInt.pfnWriteUserAsync = NULL;
9670 VDIfIoInt.pfnReadMetaAsync = NULL;
9671 VDIfIoInt.pfnWriteMetaAsync = NULL;
9672 VDIfIoInt.pfnFlushAsync = NULL;
9673 rc = VDInterfaceAdd(&VDIfIoInt.Core, "VD_IOINT", VDINTERFACETYPE_IOINT,
9674 pInterfaceIo, sizeof(VDINTERFACEIOINT), &pVDIfsImage);
9675 AssertRC(rc);
9676
9677 rc = vdFindBackend(pszBackend, &pBackend);
9678 if (RT_SUCCESS(rc))
9679 {
9680 if (pBackend->pfnRepair)
9681 rc = pBackend->pfnRepair(pszFilename, pVDIfsDisk, pVDIfsImage, fFlags);
9682 else
9683 rc = VERR_VD_IMAGE_REPAIR_NOT_SUPPORTED;
9684 }
9685
9686 LogFlowFunc(("returns %Rrc\n", rc));
9687 return rc;
9688}
9689
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