VirtualBox

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

Last change on this file since 63890 was 63830, checked in by vboxsync, 8 years ago

Storage/VD: Cleanup, get rid of goto ...

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