VirtualBox

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

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

Storage: Another shot at the I/O unification after fixing a bug

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

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette