VirtualBox

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

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

Storage: Disable dynamic loading of backends on non x86 architectures

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