VirtualBox

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

Last change on this file since 36278 was 36278, checked in by vboxsync, 14 years ago

VD: Fix leak if queuing a I/O request failed

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