VirtualBox

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

Last change on this file since 40257 was 39928, checked in by vboxsync, 13 years ago

VD: Disable optimization temporary until the crash is fixed

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