VirtualBox

source: vbox/trunk/src/VBox/Storage/QED.cpp@ 98103

Last change on this file since 98103 was 98103, checked in by vboxsync, 21 months ago

Copyright year updates by scm.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 87.1 KB
Line 
1/* $Id: QED.cpp 98103 2023-01-17 14:15:46Z vboxsync $ */
2/** @file
3 * QED - QED Disk image.
4 */
5
6/*
7 * Copyright (C) 2011-2023 Oracle and/or its affiliates.
8 *
9 * This file is part of VirtualBox base platform packages, as
10 * available from https://www.virtualbox.org.
11 *
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation, in version 3 of the
15 * License.
16 *
17 * This program is distributed in the hope that it will be useful, but
18 * WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, see <https://www.gnu.org/licenses>.
24 *
25 * SPDX-License-Identifier: GPL-3.0-only
26 */
27
28
29/*********************************************************************************************************************************
30* Header Files *
31*********************************************************************************************************************************/
32#define LOG_GROUP LOG_GROUP_VD_QED
33#include <VBox/vd-plugin.h>
34#include <VBox/err.h>
35
36#include <VBox/log.h>
37#include <iprt/asm.h>
38#include <iprt/assert.h>
39#include <iprt/string.h>
40#include <iprt/alloc.h>
41#include <iprt/path.h>
42#include <iprt/list.h>
43
44#include "VDBackends.h"
45#include "VDBackendsInline.h"
46
47/**
48 * The QED backend implements support for the qemu enhanced disk format (short QED)
49 * The specification for the format is available under http://wiki.qemu.org/Features/QED/Specification
50 *
51 * Missing things to implement:
52 * - compaction
53 * - resizing which requires block relocation (very rare case)
54 */
55
56
57/*********************************************************************************************************************************
58* Structures in a QED image, little endian *
59*********************************************************************************************************************************/
60
61#pragma pack(1)
62typedef struct QedHeader
63{
64 /** Magic value. */
65 uint32_t u32Magic;
66 /** Cluster size in bytes. */
67 uint32_t u32ClusterSize;
68 /** Size of L1 and L2 tables in clusters. */
69 uint32_t u32TableSize;
70 /** size of this header structure in clusters. */
71 uint32_t u32HeaderSize;
72 /** Features used for the image. */
73 uint64_t u64FeatureFlags;
74 /** Compatibility features used for the image. */
75 uint64_t u64CompatFeatureFlags;
76 /** Self resetting feature bits. */
77 uint64_t u64AutoresetFeatureFlags;
78 /** Offset of the L1 table in bytes. */
79 uint64_t u64OffL1Table;
80 /** Logical image size as seen by the guest. */
81 uint64_t u64Size;
82 /** Offset of the backing filename in bytes. */
83 uint32_t u32OffBackingFilename;
84 /** Size of the backing filename. */
85 uint32_t u32BackingFilenameSize;
86} QedHeader;
87#pragma pack()
88/** Pointer to a on disk QED header. */
89typedef QedHeader *PQedHeader;
90
91/** QED magic value. */
92#define QED_MAGIC UINT32_C(0x00444551) /* QED\0 */
93/** Cluster size minimum. */
94#define QED_CLUSTER_SIZE_MIN RT_BIT(12)
95/** Cluster size maximum. */
96#define QED_CLUSTER_SIZE_MAX RT_BIT(26)
97/** L1 and L2 Table size minimum. */
98#define QED_TABLE_SIZE_MIN 1
99/** L1 and L2 Table size maximum. */
100#define QED_TABLE_SIZE_MAX 16
101
102/** QED default cluster size when creating an image. */
103#define QED_CLUSTER_SIZE_DEFAULT (64 * _1K)
104/** The default table size in clusters. */
105#define QED_TABLE_SIZE_DEFAULT 4
106
107/** Feature flags.
108 * @{
109 */
110/** Image uses a backing file to provide data for unallocated clusters. */
111#define QED_FEATURE_BACKING_FILE RT_BIT_64(0)
112/** Image needs checking before use. */
113#define QED_FEATURE_NEED_CHECK RT_BIT_64(1)
114/** Don't probe for format of the backing file, treat as raw image. */
115#define QED_FEATURE_BACKING_FILE_NO_PROBE RT_BIT_64(2)
116/** Mask of valid features. */
117#define QED_FEATURE_MASK (QED_FEATURE_BACKING_FILE | QED_FEATURE_NEED_CHECK | QED_FEATURE_BACKING_FILE_NO_PROBE)
118/** @} */
119
120/** Compatibility feature flags.
121 * @{
122 */
123/** Mask of valid compatibility features. */
124#define QED_COMPAT_FEATURE_MASK (0)
125/** @} */
126
127/** Autoreset feature flags.
128 * @{
129 */
130/** Mask of valid autoreset features. */
131#define QED_AUTORESET_FEATURE_MASK (0)
132/** @} */
133
134
135/*********************************************************************************************************************************
136* Constants And Macros, Structures and Typedefs *
137*********************************************************************************************************************************/
138
139/**
140 * QED L2 cache entry.
141 */
142typedef struct QEDL2CACHEENTRY
143{
144 /** List node for the search list. */
145 RTLISTNODE NodeSearch;
146 /** List node for the LRU list. */
147 RTLISTNODE NodeLru;
148 /** Reference counter. */
149 uint32_t cRefs;
150 /** The offset of the L2 table, used as search key. */
151 uint64_t offL2Tbl;
152 /** Pointer to the cached L2 table. */
153 uint64_t *paL2Tbl;
154} QEDL2CACHEENTRY, *PQEDL2CACHEENTRY;
155
156/** Maximum amount of memory the cache is allowed to use. */
157#define QED_L2_CACHE_MEMORY_MAX (2*_1M)
158
159/**
160 * QED image data structure.
161 */
162typedef struct QEDIMAGE
163{
164 /** Image name. */
165 const char *pszFilename;
166 /** Storage handle. */
167 PVDIOSTORAGE pStorage;
168
169 /** Pointer to the per-disk VD interface list. */
170 PVDINTERFACE pVDIfsDisk;
171 /** Pointer to the per-image VD interface list. */
172 PVDINTERFACE pVDIfsImage;
173 /** Error interface. */
174 PVDINTERFACEERROR pIfError;
175 /** I/O interface. */
176 PVDINTERFACEIOINT pIfIo;
177
178 /** Open flags passed by VBoxHD layer. */
179 unsigned uOpenFlags;
180 /** Image flags defined during creation or determined during open. */
181 unsigned uImageFlags;
182 /** Total size of the image. */
183 uint64_t cbSize;
184 /** Physical geometry of this image. */
185 VDGEOMETRY PCHSGeometry;
186 /** Logical geometry of this image. */
187 VDGEOMETRY LCHSGeometry;
188
189 /** Filename of the backing file if any. */
190 char *pszBackingFilename;
191 /** Offset of the filename in the image. */
192 uint32_t offBackingFilename;
193 /** Size of the backing filename excluding \0. */
194 uint32_t cbBackingFilename;
195
196 /** Size of the image, multiple of clusters. */
197 uint64_t cbImage;
198 /** Cluster size in bytes. */
199 uint32_t cbCluster;
200 /** Number of entries in the L1 and L2 table. */
201 uint32_t cTableEntries;
202 /** Size of an L1 or L2 table rounded to the next cluster size. */
203 uint32_t cbTable;
204 /** Pointer to the L1 table. */
205 uint64_t *paL1Table;
206 /** Offset of the L1 table. */
207 uint64_t offL1Table;
208
209 /** Offset mask for a cluster. */
210 uint64_t fOffsetMask;
211 /** L1 table mask to get the L1 index. */
212 uint64_t fL1Mask;
213 /** Number of bits to shift to get the L1 index. */
214 uint32_t cL1Shift;
215 /** L2 table mask to get the L2 index. */
216 uint64_t fL2Mask;
217 /** Number of bits to shift to get the L2 index. */
218 uint32_t cL2Shift;
219
220 /** Pointer to the L2 table we are currently allocating
221 * (can be only one at a time). */
222 PQEDL2CACHEENTRY pL2TblAlloc;
223
224 /** Memory occupied by the L2 table cache. */
225 size_t cbL2Cache;
226 /** The sorted L2 entry list used for searching. */
227 RTLISTNODE ListSearch;
228 /** The LRU L2 entry list used for eviction. */
229 RTLISTNODE ListLru;
230 /** The static region list. */
231 VDREGIONLIST RegionList;
232} QEDIMAGE, *PQEDIMAGE;
233
234/**
235 * State of the async cluster allocation.
236 */
237typedef enum QEDCLUSTERASYNCALLOCSTATE
238{
239 /** Invalid. */
240 QEDCLUSTERASYNCALLOCSTATE_INVALID = 0,
241 /** L2 table allocation. */
242 QEDCLUSTERASYNCALLOCSTATE_L2_ALLOC,
243 /** Link L2 table into L1. */
244 QEDCLUSTERASYNCALLOCSTATE_L2_LINK,
245 /** Allocate user data cluster. */
246 QEDCLUSTERASYNCALLOCSTATE_USER_ALLOC,
247 /** Link user data cluster. */
248 QEDCLUSTERASYNCALLOCSTATE_USER_LINK,
249 /** 32bit blowup. */
250 QEDCLUSTERASYNCALLOCSTATE_32BIT_HACK = 0x7fffffff
251} QEDCLUSTERASYNCALLOCSTATE, *PQEDCLUSTERASYNCALLOCSTATE;
252
253/**
254 * Data needed to track async cluster allocation.
255 */
256typedef struct QEDCLUSTERASYNCALLOC
257{
258 /** The state of the cluster allocation. */
259 QEDCLUSTERASYNCALLOCSTATE enmAllocState;
260 /** Old image size to rollback in case of an error. */
261 uint64_t cbImageOld;
262 /** L1 index to link if any. */
263 uint32_t idxL1;
264 /** L2 index to link, required in any case. */
265 uint32_t idxL2;
266 /** Start offset of the allocated cluster. */
267 uint64_t offClusterNew;
268 /** L2 cache entry if a L2 table is allocated. */
269 PQEDL2CACHEENTRY pL2Entry;
270 /** Number of bytes to write. */
271 size_t cbToWrite;
272} QEDCLUSTERASYNCALLOC, *PQEDCLUSTERASYNCALLOC;
273
274
275/*********************************************************************************************************************************
276* Static Variables *
277*********************************************************************************************************************************/
278
279/** NULL-terminated array of supported file extensions. */
280static const VDFILEEXTENSION s_aQedFileExtensions[] =
281{
282 {"qed", VDTYPE_HDD},
283 {NULL, VDTYPE_INVALID}
284};
285
286
287/*********************************************************************************************************************************
288* Internal Functions *
289*********************************************************************************************************************************/
290
291/**
292 * Converts the image header to the host endianess and performs basic checks.
293 *
294 * @returns Whether the given header is valid or not.
295 * @param pHeader Pointer to the header to convert.
296 */
297static bool qedHdrConvertToHostEndianess(PQedHeader pHeader)
298{
299 pHeader->u32Magic = RT_LE2H_U32(pHeader->u32Magic);
300 pHeader->u32ClusterSize = RT_LE2H_U32(pHeader->u32ClusterSize);
301 pHeader->u32TableSize = RT_LE2H_U32(pHeader->u32TableSize);
302 pHeader->u32HeaderSize = RT_LE2H_U32(pHeader->u32HeaderSize);
303 pHeader->u64FeatureFlags = RT_LE2H_U64(pHeader->u64FeatureFlags);
304 pHeader->u64CompatFeatureFlags = RT_LE2H_U64(pHeader->u64CompatFeatureFlags);
305 pHeader->u64AutoresetFeatureFlags = RT_LE2H_U64(pHeader->u64AutoresetFeatureFlags);
306 pHeader->u64OffL1Table = RT_LE2H_U64(pHeader->u64OffL1Table);
307 pHeader->u64Size = RT_LE2H_U64(pHeader->u64Size);
308 pHeader->u32OffBackingFilename = RT_LE2H_U32(pHeader->u32OffBackingFilename);
309 pHeader->u32BackingFilenameSize = RT_LE2H_U32(pHeader->u32BackingFilenameSize);
310
311 if (RT_UNLIKELY(pHeader->u32Magic != QED_MAGIC))
312 return false;
313 if (RT_UNLIKELY( pHeader->u32ClusterSize < QED_CLUSTER_SIZE_MIN
314 || pHeader->u32ClusterSize > QED_CLUSTER_SIZE_MAX))
315 return false;
316 if (RT_UNLIKELY( pHeader->u32TableSize < QED_TABLE_SIZE_MIN
317 || pHeader->u32TableSize > QED_TABLE_SIZE_MAX))
318 return false;
319 if (RT_UNLIKELY(pHeader->u64Size % 512 != 0))
320 return false;
321 if (RT_UNLIKELY( pHeader->u64FeatureFlags & QED_FEATURE_BACKING_FILE
322 && ( pHeader->u32BackingFilenameSize == 0
323 || pHeader->u32BackingFilenameSize == UINT32_MAX)))
324 return false;
325
326 return true;
327}
328
329/**
330 * Creates a QED header from the given image state.
331 *
332 * @returns nothing.
333 * @param pImage Image instance data.
334 * @param pHeader Pointer to the header to convert.
335 */
336static void qedHdrConvertFromHostEndianess(PQEDIMAGE pImage, PQedHeader pHeader)
337{
338 pHeader->u32Magic = RT_H2LE_U32(QED_MAGIC);
339 pHeader->u32ClusterSize = RT_H2LE_U32(pImage->cbCluster);
340 pHeader->u32TableSize = RT_H2LE_U32(pImage->cbTable / pImage->cbCluster);
341 pHeader->u32HeaderSize = RT_H2LE_U32(1);
342 pHeader->u64FeatureFlags = RT_H2LE_U64(pImage->pszBackingFilename ? QED_FEATURE_BACKING_FILE : UINT64_C(0));
343 pHeader->u64CompatFeatureFlags = RT_H2LE_U64(UINT64_C(0));
344 pHeader->u64AutoresetFeatureFlags = RT_H2LE_U64(UINT64_C(0));
345 pHeader->u64OffL1Table = RT_H2LE_U64(pImage->offL1Table);
346 pHeader->u64Size = RT_H2LE_U64(pImage->cbSize);
347 pHeader->u32OffBackingFilename = RT_H2LE_U32(pImage->offBackingFilename);
348 pHeader->u32BackingFilenameSize = RT_H2LE_U32(pImage->cbBackingFilename);
349}
350
351/**
352 * Convert table entries from little endian to host endianess.
353 *
354 * @returns nothing.
355 * @param paTbl Pointer to the table.
356 * @param cEntries Number of entries in the table.
357 */
358static void qedTableConvertToHostEndianess(uint64_t *paTbl, uint32_t cEntries)
359{
360 while(cEntries-- > 0)
361 {
362 *paTbl = RT_LE2H_U64(*paTbl);
363 paTbl++;
364 }
365}
366
367#if defined(RT_BIG_ENDIAN)
368/**
369 * Convert table entries from host to little endian format.
370 *
371 * @returns nothing.
372 * @param paTblImg Pointer to the table which will store the little endian table.
373 * @param paTbl The source table to convert.
374 * @param cEntries Number of entries in the table.
375 */
376static void qedTableConvertFromHostEndianess(uint64_t *paTblImg, uint64_t *paTbl,
377 uint32_t cEntries)
378{
379 while(cEntries-- > 0)
380 {
381 *paTblImg = RT_H2LE_U64(*paTbl);
382 paTbl++;
383 paTblImg++;
384 }
385}
386#endif
387
388/**
389 * Creates the L2 table cache.
390 *
391 * @returns VBox status code.
392 * @param pImage The image instance data.
393 */
394static int qedL2TblCacheCreate(PQEDIMAGE pImage)
395{
396 pImage->cbL2Cache = 0;
397 RTListInit(&pImage->ListSearch);
398 RTListInit(&pImage->ListLru);
399
400 return VINF_SUCCESS;
401}
402
403/**
404 * Destroys the L2 table cache.
405 *
406 * @returns nothing.
407 * @param pImage The image instance data.
408 */
409static void qedL2TblCacheDestroy(PQEDIMAGE pImage)
410{
411 PQEDL2CACHEENTRY pL2Entry;
412 PQEDL2CACHEENTRY pL2Next;
413 RTListForEachSafe(&pImage->ListSearch, pL2Entry, pL2Next, QEDL2CACHEENTRY, NodeSearch)
414 {
415 Assert(!pL2Entry->cRefs);
416
417 RTListNodeRemove(&pL2Entry->NodeSearch);
418 RTMemPageFree(pL2Entry->paL2Tbl, pImage->cbTable);
419 RTMemFree(pL2Entry);
420 }
421
422 pImage->cbL2Cache = 0;
423 RTListInit(&pImage->ListSearch);
424 RTListInit(&pImage->ListLru);
425}
426
427/**
428 * Returns the L2 table matching the given offset or NULL if none could be found.
429 *
430 * @returns Pointer to the L2 table cache entry or NULL.
431 * @param pImage The image instance data.
432 * @param offL2Tbl Offset of the L2 table to search for.
433 */
434static PQEDL2CACHEENTRY qedL2TblCacheRetain(PQEDIMAGE pImage, uint64_t offL2Tbl)
435{
436 if ( pImage->pL2TblAlloc
437 && pImage->pL2TblAlloc->offL2Tbl == offL2Tbl)
438 {
439 pImage->pL2TblAlloc->cRefs++;
440 return pImage->pL2TblAlloc;
441 }
442
443 PQEDL2CACHEENTRY pL2Entry;
444 RTListForEach(&pImage->ListSearch, pL2Entry, QEDL2CACHEENTRY, NodeSearch)
445 {
446 if (pL2Entry->offL2Tbl == offL2Tbl)
447 break;
448 }
449
450 if (!RTListNodeIsDummy(&pImage->ListSearch, pL2Entry, QEDL2CACHEENTRY, NodeSearch))
451 {
452 /* Update LRU list. */
453 RTListNodeRemove(&pL2Entry->NodeLru);
454 RTListPrepend(&pImage->ListLru, &pL2Entry->NodeLru);
455 pL2Entry->cRefs++;
456 return pL2Entry;
457 }
458 else
459 return NULL;
460}
461
462/**
463 * Releases a L2 table cache entry.
464 *
465 * @returns nothing.
466 * @param pL2Entry The L2 cache entry.
467 */
468static void qedL2TblCacheEntryRelease(PQEDL2CACHEENTRY pL2Entry)
469{
470 Assert(pL2Entry->cRefs > 0);
471 pL2Entry->cRefs--;
472}
473
474/**
475 * Allocates a new L2 table from the cache evicting old entries if required.
476 *
477 * @returns Pointer to the L2 cache entry or NULL.
478 * @param pImage The image instance data.
479 */
480static PQEDL2CACHEENTRY qedL2TblCacheEntryAlloc(PQEDIMAGE pImage)
481{
482 PQEDL2CACHEENTRY pL2Entry = NULL;
483
484 if (pImage->cbL2Cache + pImage->cbTable <= QED_L2_CACHE_MEMORY_MAX)
485 {
486 /* Add a new entry. */
487 pL2Entry = (PQEDL2CACHEENTRY)RTMemAllocZ(sizeof(QEDL2CACHEENTRY));
488 if (pL2Entry)
489 {
490 pL2Entry->paL2Tbl = (uint64_t *)RTMemPageAllocZ(pImage->cbTable);
491 if (RT_UNLIKELY(!pL2Entry->paL2Tbl))
492 {
493 RTMemFree(pL2Entry);
494 pL2Entry = NULL;
495 }
496 else
497 {
498 pL2Entry->cRefs = 1;
499 pImage->cbL2Cache += pImage->cbTable;
500 }
501 }
502 }
503 else
504 {
505 /* Evict the last not in use entry and use it */
506 Assert(!RTListIsEmpty(&pImage->ListLru));
507
508 RTListForEachReverse(&pImage->ListLru, pL2Entry, QEDL2CACHEENTRY, NodeLru)
509 {
510 if (!pL2Entry->cRefs)
511 break;
512 }
513
514 if (!RTListNodeIsDummy(&pImage->ListSearch, pL2Entry, QEDL2CACHEENTRY, NodeSearch))
515 {
516 RTListNodeRemove(&pL2Entry->NodeSearch);
517 RTListNodeRemove(&pL2Entry->NodeLru);
518 pL2Entry->offL2Tbl = 0;
519 pL2Entry->cRefs = 1;
520 }
521 else
522 pL2Entry = NULL;
523 }
524
525 return pL2Entry;
526}
527
528/**
529 * Frees a L2 table cache entry.
530 *
531 * @returns nothing.
532 * @param pImage The image instance data.
533 * @param pL2Entry The L2 cache entry to free.
534 */
535static void qedL2TblCacheEntryFree(PQEDIMAGE pImage, PQEDL2CACHEENTRY pL2Entry)
536{
537 Assert(!pL2Entry->cRefs);
538 RTMemPageFree(pL2Entry->paL2Tbl, pImage->cbTable);
539 RTMemFree(pL2Entry);
540
541 pImage->cbL2Cache -= pImage->cbTable;
542}
543
544/**
545 * Inserts an entry in the L2 table cache.
546 *
547 * @returns nothing.
548 * @param pImage The image instance data.
549 * @param pL2Entry The L2 cache entry to insert.
550 */
551static void qedL2TblCacheEntryInsert(PQEDIMAGE pImage, PQEDL2CACHEENTRY pL2Entry)
552{
553 Assert(pL2Entry->offL2Tbl > 0);
554
555 /* Insert at the top of the LRU list. */
556 RTListPrepend(&pImage->ListLru, &pL2Entry->NodeLru);
557
558 if (RTListIsEmpty(&pImage->ListSearch))
559 {
560 RTListAppend(&pImage->ListSearch, &pL2Entry->NodeSearch);
561 }
562 else
563 {
564 /* Insert into search list. */
565 PQEDL2CACHEENTRY pIt;
566 pIt = RTListGetFirst(&pImage->ListSearch, QEDL2CACHEENTRY, NodeSearch);
567 if (pIt->offL2Tbl > pL2Entry->offL2Tbl)
568 RTListPrepend(&pImage->ListSearch, &pL2Entry->NodeSearch);
569 else
570 {
571 bool fInserted = false;
572
573 RTListForEach(&pImage->ListSearch, pIt, QEDL2CACHEENTRY, NodeSearch)
574 {
575 Assert(pIt->offL2Tbl != pL2Entry->offL2Tbl);
576 if (pIt->offL2Tbl < pL2Entry->offL2Tbl)
577 {
578 RTListNodeInsertAfter(&pIt->NodeSearch, &pL2Entry->NodeSearch);
579 fInserted = true;
580 break;
581 }
582 }
583 Assert(fInserted);
584 }
585 }
586}
587
588/**
589 * Fetches the L2 from the given offset trying the LRU cache first and
590 * reading it from the image after a cache miss - version for async I/O.
591 *
592 * @returns VBox status code.
593 * @param pImage Image instance data.
594 * @param pIoCtx The I/O context.
595 * @param offL2Tbl The offset of the L2 table in the image.
596 * @param ppL2Entry Where to store the L2 table on success.
597 */
598static int qedL2TblCacheFetchAsync(PQEDIMAGE pImage, PVDIOCTX pIoCtx,
599 uint64_t offL2Tbl, PQEDL2CACHEENTRY *ppL2Entry)
600{
601 int rc = VINF_SUCCESS;
602
603 /* Try to fetch the L2 table from the cache first. */
604 PQEDL2CACHEENTRY pL2Entry = qedL2TblCacheRetain(pImage, offL2Tbl);
605 if (!pL2Entry)
606 {
607 pL2Entry = qedL2TblCacheEntryAlloc(pImage);
608
609 if (pL2Entry)
610 {
611 /* Read from the image. */
612 PVDMETAXFER pMetaXfer;
613
614 pL2Entry->offL2Tbl = offL2Tbl;
615 rc = vdIfIoIntFileReadMeta(pImage->pIfIo, pImage->pStorage,
616 offL2Tbl, pL2Entry->paL2Tbl,
617 pImage->cbTable, pIoCtx,
618 &pMetaXfer, NULL, NULL);
619 if (RT_SUCCESS(rc))
620 {
621 vdIfIoIntMetaXferRelease(pImage->pIfIo, pMetaXfer);
622#if defined(RT_BIG_ENDIAN)
623 qedTableConvertToHostEndianess(pL2Entry->paL2Tbl, pImage->cTableEntries);
624#endif
625 qedL2TblCacheEntryInsert(pImage, pL2Entry);
626 }
627 else
628 {
629 qedL2TblCacheEntryRelease(pL2Entry);
630 qedL2TblCacheEntryFree(pImage, pL2Entry);
631 }
632 }
633 else
634 rc = VERR_NO_MEMORY;
635 }
636
637 if (RT_SUCCESS(rc))
638 *ppL2Entry = pL2Entry;
639
640 return rc;
641}
642
643/**
644 * Return power of 2 or 0 if num error.
645 *
646 * @returns The power of 2 or 0 if the given number is not a power of 2.
647 * @param u32 The number.
648 */
649static uint32_t qedGetPowerOfTwo(uint32_t u32)
650{
651 if (u32 == 0)
652 return 0;
653 uint32_t uPower2 = 0;
654 while ((u32 & 1) == 0)
655 {
656 u32 >>= 1;
657 uPower2++;
658 }
659 return u32 == 1 ? uPower2 : 0;
660}
661
662/**
663 * Sets the L1, L2 and offset bitmasks and L1 and L2 bit shift members.
664 *
665 * @returns nothing.
666 * @param pImage The image instance data.
667 */
668static void qedTableMasksInit(PQEDIMAGE pImage)
669{
670 uint32_t cClusterBits, cTableBits;
671
672 cClusterBits = qedGetPowerOfTwo(pImage->cbCluster);
673 cTableBits = qedGetPowerOfTwo(pImage->cTableEntries);
674
675 Assert(cClusterBits + 2 * cTableBits <= 64);
676
677 pImage->fOffsetMask = ((uint64_t)pImage->cbCluster - 1);
678 pImage->fL2Mask = ((uint64_t)pImage->cTableEntries - 1) << cClusterBits;
679 pImage->cL2Shift = cClusterBits;
680 pImage->fL1Mask = ((uint64_t)pImage->cTableEntries - 1) << (cClusterBits + cTableBits);
681 pImage->cL1Shift = cClusterBits + cTableBits;
682}
683
684/**
685 * Converts a given logical offset into the
686 *
687 * @returns nothing.
688 * @param pImage The image instance data.
689 * @param off The logical offset to convert.
690 * @param pidxL1 Where to store the index in the L1 table on success.
691 * @param pidxL2 Where to store the index in the L2 table on success.
692 * @param poffCluster Where to store the offset in the cluster on success.
693 */
694DECLINLINE(void) qedConvertLogicalOffset(PQEDIMAGE pImage, uint64_t off, uint32_t *pidxL1,
695 uint32_t *pidxL2, uint32_t *poffCluster)
696{
697 AssertPtr(pidxL1);
698 AssertPtr(pidxL2);
699 AssertPtr(poffCluster);
700
701 *poffCluster = off & pImage->fOffsetMask;
702 *pidxL1 = (off & pImage->fL1Mask) >> pImage->cL1Shift;
703 *pidxL2 = (off & pImage->fL2Mask) >> pImage->cL2Shift;
704}
705
706/**
707 * Converts Cluster size to a byte size.
708 *
709 * @returns Number of bytes derived from the given number of clusters.
710 * @param pImage The image instance data.
711 * @param cClusters The clusters to convert.
712 */
713DECLINLINE(uint64_t) qedCluster2Byte(PQEDIMAGE pImage, uint64_t cClusters)
714{
715 return cClusters * pImage->cbCluster;
716}
717
718/**
719 * Converts number of bytes to cluster size rounding to the next cluster.
720 *
721 * @returns Number of bytes derived from the given number of clusters.
722 * @param pImage The image instance data.
723 * @param cb Number of bytes to convert.
724 */
725DECLINLINE(uint64_t) qedByte2Cluster(PQEDIMAGE pImage, uint64_t cb)
726{
727 return cb / pImage->cbCluster + (cb % pImage->cbCluster ? 1 : 0);
728}
729
730/**
731 * Allocates a new cluster in the image.
732 *
733 * @returns The start offset of the new cluster in the image.
734 * @param pImage The image instance data.
735 * @param cClusters Number of clusters to allocate.
736 */
737DECLINLINE(uint64_t) qedClusterAllocate(PQEDIMAGE pImage, uint32_t cClusters)
738{
739 uint64_t offCluster;
740
741 offCluster = pImage->cbImage;
742 pImage->cbImage += cClusters*pImage->cbCluster;
743
744 return offCluster;
745}
746
747/**
748 * Returns the real image offset for a given cluster or an error if the cluster is not
749 * yet allocated.
750 *
751 * @returns VBox status code.
752 * VERR_VD_BLOCK_FREE if the cluster is not yet allocated.
753 * @param pImage The image instance data.
754 * @param pIoCtx The I/O context.
755 * @param idxL1 The L1 index.
756 * @param idxL2 The L2 index.
757 * @param offCluster Offset inside the cluster.
758 * @param poffImage Where to store the image offset on success;
759 */
760static int qedConvertToImageOffset(PQEDIMAGE pImage, PVDIOCTX pIoCtx,
761 uint32_t idxL1, uint32_t idxL2,
762 uint32_t offCluster, uint64_t *poffImage)
763{
764 int rc = VERR_VD_BLOCK_FREE;
765
766 AssertReturn(idxL1 < pImage->cTableEntries, VERR_INVALID_PARAMETER);
767 AssertReturn(idxL2 < pImage->cTableEntries, VERR_INVALID_PARAMETER);
768
769 if (pImage->paL1Table[idxL1])
770 {
771 PQEDL2CACHEENTRY pL2Entry;
772
773 rc = qedL2TblCacheFetchAsync(pImage, pIoCtx, pImage->paL1Table[idxL1],
774 &pL2Entry);
775 if (RT_SUCCESS(rc))
776 {
777 /* Get real file offset. */
778 if (pL2Entry->paL2Tbl[idxL2])
779 *poffImage = pL2Entry->paL2Tbl[idxL2] + offCluster;
780 else
781 rc = VERR_VD_BLOCK_FREE;
782
783 qedL2TblCacheEntryRelease(pL2Entry);
784 }
785 }
786
787 return rc;
788}
789
790/**
791 * Write the given table to image converting to the image endianess if required.
792 *
793 * @returns VBox status code.
794 * @param pImage The image instance data.
795 * @param pIoCtx The I/O context.
796 * @param offTbl The offset the table should be written to.
797 * @param paTbl The table to write.
798 * @param pfnComplete Callback called when the write completes.
799 * @param pvUser Opaque user data to pass in the completion callback.
800 */
801static int qedTblWrite(PQEDIMAGE pImage, PVDIOCTX pIoCtx, uint64_t offTbl, uint64_t *paTbl,
802 PFNVDXFERCOMPLETED pfnComplete, void *pvUser)
803{
804 int rc = VINF_SUCCESS;
805
806#if defined(RT_BIG_ENDIAN)
807 uint64_t *paTblImg = (uint64_t *)RTMemAllocZ(pImage->cbTable);
808 if (paTblImg)
809 {
810 qedTableConvertFromHostEndianess(paTblImg, paTbl,
811 pImage->cTableEntries);
812 rc = vdIfIoIntFileWriteMeta(pImage->pIfIo, pImage->pStorage,
813 offTbl, paTblImg, pImage->cbTable,
814 pIoCtx, pfnComplete, pvUser);
815 RTMemFree(paTblImg);
816 }
817 else
818 rc = VERR_NO_MEMORY;
819#else
820 /* Write table directly. */
821 rc = vdIfIoIntFileWriteMeta(pImage->pIfIo, pImage->pStorage,
822 offTbl, paTbl, pImage->cbTable, pIoCtx,
823 pfnComplete, pvUser);
824#endif
825
826 return rc;
827}
828
829/**
830 * Internal. Flush image data to disk.
831 */
832static int qedFlushImage(PQEDIMAGE pImage)
833{
834 int rc = VINF_SUCCESS;
835
836 if ( pImage->pStorage
837 && !(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
838 {
839 QedHeader Header;
840
841 Assert(!(pImage->cbTable % pImage->cbCluster));
842#if defined(RT_BIG_ENDIAN)
843 uint64_t *paL1TblImg = (uint64_t *)RTMemAllocZ(pImage->cbTable);
844 if (paL1TblImg)
845 {
846 qedTableConvertFromHostEndianess(paL1TblImg, pImage->paL1Table,
847 pImage->cTableEntries);
848 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pImage->pStorage,
849 pImage->offL1Table, paL1TblImg,
850 pImage->cbTable);
851 RTMemFree(paL1TblImg);
852 }
853 else
854 rc = VERR_NO_MEMORY;
855#else
856 /* Write L1 table directly. */
857 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pImage->pStorage, pImage->offL1Table,
858 pImage->paL1Table, pImage->cbTable);
859#endif
860 if (RT_SUCCESS(rc))
861 {
862 /* Write header. */
863 qedHdrConvertFromHostEndianess(pImage, &Header);
864 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pImage->pStorage, 0, &Header,
865 sizeof(Header));
866 if (RT_SUCCESS(rc))
867 rc = vdIfIoIntFileFlushSync(pImage->pIfIo, pImage->pStorage);
868 }
869 }
870
871 return rc;
872}
873
874/**
875 * Checks whether the given cluster offset is valid.
876 *
877 * @returns Whether the given cluster offset is valid.
878 * @param offCluster The table offset to check.
879 * @param cbFile The real file size of the image.
880 * @param cbCluster The cluster size in bytes.
881 */
882DECLINLINE(bool) qedIsClusterOffsetValid(uint64_t offCluster, uint64_t cbFile, size_t cbCluster)
883{
884 return (offCluster <= cbFile - cbCluster)
885 && !(offCluster & (cbCluster - 1));
886}
887
888/**
889 * Checks whether the given table offset is valid.
890 *
891 * @returns Whether the given table offset is valid.
892 * @param offTbl The table offset to check.
893 * @param cbFile The real file size of the image.
894 * @param cbTable The table size in bytes.
895 * @param cbCluster The cluster size in bytes.
896 */
897DECLINLINE(bool) qedIsTblOffsetValid(uint64_t offTbl, uint64_t cbFile, size_t cbTable, size_t cbCluster)
898{
899 return (offTbl <= cbFile - cbTable)
900 && !(offTbl & (cbCluster - 1));
901}
902
903/**
904 * Sets the specified range in the cluster bitmap checking whether any of the clusters is already
905 * used before.
906 *
907 * @returns Whether the range was clear and is set now.
908 * @param pvClusterBitmap The cluster bitmap to use.
909 * @param offClusterStart The first cluster to check and set.
910 * @param offClusterEnd The first cluster to not check and set anymore.
911 */
912static bool qedClusterBitmapCheckAndSet(void *pvClusterBitmap, uint32_t offClusterStart, uint32_t offClusterEnd)
913{
914 for (uint32_t offCluster = offClusterStart; offCluster < offClusterEnd; offCluster++)
915 if (ASMBitTest(pvClusterBitmap, offCluster))
916 return false;
917
918 ASMBitSetRange(pvClusterBitmap, offClusterStart, offClusterEnd);
919 return true;
920}
921
922/**
923 * Checks the given image for consistency, usually called when the
924 * QED_FEATURE_NEED_CHECK bit is set.
925 *
926 * @returns VBox status code.
927 * @retval VINF_SUCCESS when the image can be accessed.
928 * @param pImage The image instance data.
929 * @param pHeader The header to use for checking.
930 *
931 * @note It is not required that the image state is fully initialized Only
932 * The I/O interface and storage handle need to be valid.
933 * @note The header must be converted to the host CPU endian format already
934 * and should be validated already.
935 */
936static int qedCheckImage(PQEDIMAGE pImage, PQedHeader pHeader)
937{
938 uint64_t cbFile;
939 uint32_t cbTable;
940 uint32_t cTableEntries;
941 uint64_t *paL1Tbl = NULL;
942 uint64_t *paL2Tbl = NULL;
943 void *pvClusterBitmap = NULL;
944 uint32_t offClusterStart;
945 int rc = VINF_SUCCESS;
946
947 pImage->cbCluster = pHeader->u32ClusterSize;
948 cbTable = pHeader->u32TableSize * pHeader->u32ClusterSize;
949 cTableEntries = cbTable / sizeof(uint64_t);
950
951 do
952 {
953 rc = vdIfIoIntFileGetSize(pImage->pIfIo, pImage->pStorage, &cbFile);
954 if (RT_FAILURE(rc))
955 {
956 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS,
957 N_("Qed: Querying the file size of image '%s' failed"),
958 pImage->pszFilename);
959 break;
960 }
961
962 /* Allocate L1 table. */
963 paL1Tbl = (uint64_t *)RTMemAllocZ(cbTable);
964 if (!paL1Tbl)
965 {
966 rc = vdIfError(pImage->pIfError, VERR_NO_MEMORY, RT_SRC_POS,
967 N_("Qed: Allocating memory for the L1 table for image '%s' failed"),
968 pImage->pszFilename);
969 break;
970 }
971
972 paL2Tbl = (uint64_t *)RTMemAllocZ(cbTable);
973 if (!paL2Tbl)
974 {
975 rc = vdIfError(pImage->pIfError, VERR_NO_MEMORY, RT_SRC_POS,
976 N_("Qed: Allocating memory for the L2 table for image '%s' failed"),
977 pImage->pszFilename);
978 break;
979 }
980
981 pvClusterBitmap = RTMemAllocZ(cbFile / pHeader->u32ClusterSize / 8);
982 if (!pvClusterBitmap)
983 {
984 rc = vdIfError(pImage->pIfError, VERR_NO_MEMORY, RT_SRC_POS,
985 N_("Qed: Allocating memory for the cluster bitmap for image '%s' failed"),
986 pImage->pszFilename);
987 break;
988 }
989
990 /* Validate L1 table offset. */
991 if (!qedIsTblOffsetValid(pHeader->u64OffL1Table, cbFile, cbTable, pHeader->u32ClusterSize))
992 {
993 rc = vdIfError(pImage->pIfError, VERR_VD_GEN_INVALID_HEADER, RT_SRC_POS,
994 N_("Qed: L1 table offset of image '%s' is corrupt (%llu)"),
995 pImage->pszFilename, pHeader->u64OffL1Table);
996 break;
997 }
998
999 /* Read L1 table. */
1000 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pImage->pStorage,
1001 pHeader->u64OffL1Table, paL1Tbl, cbTable);
1002 if (RT_FAILURE(rc))
1003 {
1004 rc = vdIfError(pImage->pIfError, VERR_VD_GEN_INVALID_HEADER, RT_SRC_POS,
1005 N_("Qed: Reading the L1 table from image '%s' failed"),
1006 pImage->pszFilename);
1007 break;
1008 }
1009
1010 /* Mark the L1 table in cluster bitmap. */
1011 ASMBitSet(pvClusterBitmap, 0); /* Header is always in cluster 0. */
1012 offClusterStart = qedByte2Cluster(pImage, pHeader->u64OffL1Table);
1013 bool fSet = qedClusterBitmapCheckAndSet(pvClusterBitmap, offClusterStart, offClusterStart + pHeader->u32TableSize);
1014 Assert(fSet);
1015
1016 /* Scan the L1 and L2 tables for invalid entries. */
1017 qedTableConvertToHostEndianess(paL1Tbl, cTableEntries);
1018
1019 for (unsigned iL1 = 0; iL1 < cTableEntries; iL1++)
1020 {
1021 if (!paL1Tbl[iL1])
1022 continue; /* Skip unallocated clusters. */
1023
1024 if (!qedIsTblOffsetValid(paL1Tbl[iL1], cbFile, cbTable, pHeader->u32ClusterSize))
1025 {
1026 rc = vdIfError(pImage->pIfError, VERR_VD_GEN_INVALID_HEADER, RT_SRC_POS,
1027 N_("Qed: Entry %d of the L1 table from image '%s' is invalid (%llu)"),
1028 iL1, pImage->pszFilename, paL1Tbl[iL1]);
1029 break;
1030 }
1031
1032 /* Now check that the clusters are not allocated already. */
1033 offClusterStart = qedByte2Cluster(pImage, paL1Tbl[iL1]);
1034 fSet = qedClusterBitmapCheckAndSet(pvClusterBitmap, offClusterStart, offClusterStart + pHeader->u32TableSize);
1035 if (!fSet)
1036 {
1037 rc = vdIfError(pImage->pIfError, VERR_VD_GEN_INVALID_HEADER, RT_SRC_POS,
1038 N_("Qed: Entry %d of the L1 table from image '%s' points to a already used cluster (%llu)"),
1039 iL1, pImage->pszFilename, paL1Tbl[iL1]);
1040 break;
1041 }
1042
1043 /* Read the linked L2 table and check it. */
1044 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pImage->pStorage,
1045 paL1Tbl[iL1], paL2Tbl, cbTable);
1046 if (RT_FAILURE(rc))
1047 {
1048 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS,
1049 N_("Qed: Reading the L2 table from image '%s' failed"),
1050 pImage->pszFilename);
1051 break;
1052 }
1053
1054 /* Check all L2 entries. */
1055 for (unsigned iL2 = 0; iL2 < cTableEntries; iL2++)
1056 {
1057 if (paL2Tbl[iL2])
1058 continue; /* Skip unallocated clusters. */
1059
1060 if (!qedIsClusterOffsetValid(paL2Tbl[iL2], cbFile, pHeader->u32ClusterSize))
1061 {
1062 rc = vdIfError(pImage->pIfError, VERR_VD_GEN_INVALID_HEADER, RT_SRC_POS,
1063 N_("Qed: Entry %d of the L2 table from image '%s' is invalid (%llu)"),
1064 iL2, pImage->pszFilename, paL2Tbl[iL2]);
1065 break;
1066 }
1067
1068 /* Now check that the clusters are not allocated already. */
1069 offClusterStart = qedByte2Cluster(pImage, paL2Tbl[iL2]);
1070 fSet = qedClusterBitmapCheckAndSet(pvClusterBitmap, offClusterStart, offClusterStart + 1);
1071 if (!fSet)
1072 {
1073 rc = vdIfError(pImage->pIfError, VERR_VD_GEN_INVALID_HEADER, RT_SRC_POS,
1074 N_("Qed: Entry %d of the L2 table from image '%s' points to a already used cluster (%llu)"),
1075 iL2, pImage->pszFilename, paL2Tbl[iL2]);
1076 break;
1077 }
1078 }
1079 }
1080 } while(0);
1081
1082 if (paL1Tbl)
1083 RTMemFree(paL1Tbl);
1084 if (paL2Tbl)
1085 RTMemFree(paL2Tbl);
1086 if (pvClusterBitmap)
1087 RTMemFree(pvClusterBitmap);
1088
1089 return rc;
1090}
1091
1092/**
1093 * Internal. Free all allocated space for representing an image except pImage,
1094 * and optionally delete the image from disk.
1095 */
1096static int qedFreeImage(PQEDIMAGE pImage, bool fDelete)
1097{
1098 int rc = VINF_SUCCESS;
1099
1100 /* Freeing a never allocated image (e.g. because the open failed) is
1101 * not signalled as an error. After all nothing bad happens. */
1102 if (pImage)
1103 {
1104 if (pImage->pStorage)
1105 {
1106 /* No point updating the file that is deleted anyway. */
1107 if (!fDelete)
1108 qedFlushImage(pImage);
1109
1110 rc = vdIfIoIntFileClose(pImage->pIfIo, pImage->pStorage);
1111 pImage->pStorage = NULL;
1112 }
1113
1114 if (pImage->paL1Table)
1115 RTMemFree(pImage->paL1Table);
1116
1117 if (pImage->pszBackingFilename)
1118 {
1119 RTStrFree(pImage->pszBackingFilename);
1120 pImage->pszBackingFilename = NULL;
1121 }
1122
1123 qedL2TblCacheDestroy(pImage);
1124
1125 if (fDelete && pImage->pszFilename)
1126 vdIfIoIntFileDelete(pImage->pIfIo, pImage->pszFilename);
1127 }
1128
1129 LogFlowFunc(("returns %Rrc\n", rc));
1130 return rc;
1131}
1132
1133/**
1134 * Internal: Open an image, constructing all necessary data structures.
1135 */
1136static int qedOpenImage(PQEDIMAGE pImage, unsigned uOpenFlags)
1137{
1138 pImage->uOpenFlags = uOpenFlags;
1139
1140 pImage->pIfError = VDIfErrorGet(pImage->pVDIfsDisk);
1141 pImage->pIfIo = VDIfIoIntGet(pImage->pVDIfsImage);
1142 AssertPtrReturn(pImage->pIfIo, VERR_INVALID_PARAMETER);
1143
1144 /*
1145 * Create the L2 cache before opening the image so we can call qedFreeImage()
1146 * even if opening the image file fails.
1147 */
1148 int rc = qedL2TblCacheCreate(pImage);
1149 if (RT_SUCCESS(rc))
1150 {
1151 /* Open the image. */
1152 rc = vdIfIoIntFileOpen(pImage->pIfIo, pImage->pszFilename,
1153 VDOpenFlagsToFileOpenFlags(uOpenFlags,
1154 false /* fCreate */),
1155 &pImage->pStorage);
1156 if (RT_SUCCESS(rc))
1157 {
1158 uint64_t cbFile;
1159 rc = vdIfIoIntFileGetSize(pImage->pIfIo, pImage->pStorage, &cbFile);
1160 if ( RT_SUCCESS(rc)
1161 && cbFile > sizeof(QedHeader))
1162 {
1163 QedHeader Header;
1164
1165 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pImage->pStorage, 0, &Header, sizeof(Header));
1166 if ( RT_SUCCESS(rc)
1167 && qedHdrConvertToHostEndianess(&Header))
1168 {
1169 if ( !(Header.u64FeatureFlags & ~QED_FEATURE_MASK)
1170 && !(Header.u64FeatureFlags & QED_FEATURE_BACKING_FILE_NO_PROBE))
1171 {
1172 if (Header.u64FeatureFlags & QED_FEATURE_NEED_CHECK)
1173 {
1174 /* Image needs checking. */
1175 if (!(uOpenFlags & VD_OPEN_FLAGS_READONLY))
1176 rc = qedCheckImage(pImage, &Header);
1177 else
1178 rc = vdIfError(pImage->pIfError, VERR_NOT_SUPPORTED, RT_SRC_POS,
1179 N_("Qed: Image '%s' needs checking but is opened readonly"),
1180 pImage->pszFilename);
1181 }
1182
1183 if ( RT_SUCCESS(rc)
1184 && (Header.u64FeatureFlags & QED_FEATURE_BACKING_FILE))
1185 {
1186 /* Load backing filename from image. */
1187 pImage->pszBackingFilename = RTStrAlloc(Header.u32BackingFilenameSize + 1); /* +1 for \0 terminator. */
1188 if (pImage->pszBackingFilename)
1189 {
1190 RT_BZERO(pImage->pszBackingFilename, Header.u32BackingFilenameSize + 1);
1191 pImage->cbBackingFilename = Header.u32BackingFilenameSize;
1192 pImage->offBackingFilename = Header.u32OffBackingFilename;
1193 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pImage->pStorage,
1194 Header.u32OffBackingFilename, pImage->pszBackingFilename,
1195 Header.u32BackingFilenameSize);
1196 if (RT_SUCCESS(rc))
1197 rc = RTStrValidateEncoding(pImage->pszBackingFilename);
1198 }
1199 else
1200 rc = VERR_NO_STR_MEMORY;
1201 }
1202
1203 if (RT_SUCCESS(rc))
1204 {
1205 pImage->cbImage = cbFile;
1206 pImage->cbCluster = Header.u32ClusterSize;
1207 pImage->cbTable = Header.u32TableSize * pImage->cbCluster;
1208 pImage->cTableEntries = pImage->cbTable / sizeof(uint64_t);
1209 pImage->offL1Table = Header.u64OffL1Table;
1210 pImage->cbSize = Header.u64Size;
1211 qedTableMasksInit(pImage);
1212
1213 /* Allocate L1 table. */
1214 pImage->paL1Table = (uint64_t *)RTMemAllocZ(pImage->cbTable);
1215 if (pImage->paL1Table)
1216 {
1217 /* Read from the image. */
1218 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pImage->pStorage,
1219 pImage->offL1Table, pImage->paL1Table,
1220 pImage->cbTable);
1221 if (RT_SUCCESS(rc))
1222 {
1223 qedTableConvertToHostEndianess(pImage->paL1Table, pImage->cTableEntries);
1224
1225 /* If the consistency check succeeded, clear the flag by flushing the image. */
1226 if (Header.u64FeatureFlags & QED_FEATURE_NEED_CHECK)
1227 rc = qedFlushImage(pImage);
1228 }
1229 else
1230 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS,
1231 N_("Qed: Reading the L1 table for image '%s' failed"),
1232 pImage->pszFilename);
1233 }
1234 else
1235 rc = vdIfError(pImage->pIfError, VERR_NO_MEMORY, RT_SRC_POS,
1236 N_("Qed: Out of memory allocating L1 table for image '%s'"),
1237 pImage->pszFilename);
1238 }
1239 }
1240 else
1241 rc = vdIfError(pImage->pIfError, VERR_NOT_SUPPORTED, RT_SRC_POS,
1242 N_("Qed: The image '%s' makes use of unsupported features"),
1243 pImage->pszFilename);
1244 }
1245 else if (RT_SUCCESS(rc))
1246 rc = VERR_VD_GEN_INVALID_HEADER;
1247 }
1248 else if (RT_SUCCESS(rc))
1249 rc = VERR_VD_GEN_INVALID_HEADER;
1250 }
1251 /* else: Do NOT signal an appropriate error here, as the VD layer has the
1252 * choice of retrying the open if it failed. */
1253 }
1254 else
1255 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS,
1256 N_("Qed: Creating the L2 table cache for image '%s' failed"),
1257 pImage->pszFilename);
1258
1259 if (RT_SUCCESS(rc))
1260 {
1261 PVDREGIONDESC pRegion = &pImage->RegionList.aRegions[0];
1262 pImage->RegionList.fFlags = 0;
1263 pImage->RegionList.cRegions = 1;
1264
1265 pRegion->offRegion = 0; /* Disk start. */
1266 pRegion->cbBlock = 512;
1267 pRegion->enmDataForm = VDREGIONDATAFORM_RAW;
1268 pRegion->enmMetadataForm = VDREGIONMETADATAFORM_NONE;
1269 pRegion->cbData = 512;
1270 pRegion->cbMetadata = 0;
1271 pRegion->cRegionBlocksOrBytes = pImage->cbSize;
1272 }
1273 else
1274 qedFreeImage(pImage, false);
1275 return rc;
1276}
1277
1278/**
1279 * Internal: Create a qed image.
1280 */
1281static int qedCreateImage(PQEDIMAGE pImage, uint64_t cbSize,
1282 unsigned uImageFlags, const char *pszComment,
1283 PCVDGEOMETRY pPCHSGeometry,
1284 PCVDGEOMETRY pLCHSGeometry, unsigned uOpenFlags,
1285 PVDINTERFACEPROGRESS pIfProgress,
1286 unsigned uPercentStart, unsigned uPercentSpan)
1287{
1288 RT_NOREF1(pszComment);
1289 int rc;
1290
1291 if (!(uImageFlags & VD_IMAGE_FLAGS_FIXED))
1292 {
1293 rc = qedL2TblCacheCreate(pImage);
1294 if (RT_SUCCESS(rc))
1295 {
1296 pImage->uOpenFlags = uOpenFlags & ~VD_OPEN_FLAGS_READONLY;
1297 pImage->uImageFlags = uImageFlags;
1298 pImage->PCHSGeometry = *pPCHSGeometry;
1299 pImage->LCHSGeometry = *pLCHSGeometry;
1300
1301 pImage->pIfError = VDIfErrorGet(pImage->pVDIfsDisk);
1302 pImage->pIfIo = VDIfIoIntGet(pImage->pVDIfsImage);
1303 AssertPtrReturn(pImage->pIfIo, VERR_INVALID_PARAMETER);
1304
1305 /* Create image file. */
1306 uint32_t fOpen = VDOpenFlagsToFileOpenFlags(pImage->uOpenFlags, true /* fCreate */);
1307 rc = vdIfIoIntFileOpen(pImage->pIfIo, pImage->pszFilename, fOpen, &pImage->pStorage);
1308 if (RT_SUCCESS(rc))
1309 {
1310 /* Init image state. */
1311 pImage->cbSize = cbSize;
1312 pImage->cbCluster = QED_CLUSTER_SIZE_DEFAULT;
1313 pImage->cbTable = qedCluster2Byte(pImage, QED_TABLE_SIZE_DEFAULT);
1314 pImage->cTableEntries = pImage->cbTable / sizeof(uint64_t);
1315 pImage->offL1Table = qedCluster2Byte(pImage, 1); /* Cluster 0 is the header. */
1316 pImage->cbImage = (1 * pImage->cbCluster) + pImage->cbTable; /* Header + L1 table size. */
1317 pImage->cbBackingFilename = 0;
1318 pImage->offBackingFilename = 0;
1319 qedTableMasksInit(pImage);
1320
1321 /* Init L1 table. */
1322 pImage->paL1Table = (uint64_t *)RTMemAllocZ(pImage->cbTable);
1323 if (RT_LIKELY(pImage->paL1Table))
1324 {
1325 vdIfProgress(pIfProgress, uPercentStart + uPercentSpan * 98 / 100);
1326 rc = qedFlushImage(pImage);
1327 }
1328 else
1329 rc = vdIfError(pImage->pIfError, VERR_NO_MEMORY, RT_SRC_POS, N_("Qed: cannot allocate memory for L1 table of image '%s'"),
1330 pImage->pszFilename);
1331 }
1332 else
1333 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("Qed: cannot create image '%s'"), pImage->pszFilename);
1334 }
1335 else
1336 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("Qed: Failed to create L2 cache for image '%s'"),
1337 pImage->pszFilename);
1338 }
1339 else
1340 rc = vdIfError(pImage->pIfError, VERR_VD_INVALID_TYPE, RT_SRC_POS, N_("Qed: cannot create fixed image '%s'"), pImage->pszFilename);
1341
1342 if (RT_SUCCESS(rc))
1343 {
1344 PVDREGIONDESC pRegion = &pImage->RegionList.aRegions[0];
1345 pImage->RegionList.fFlags = 0;
1346 pImage->RegionList.cRegions = 1;
1347
1348 pRegion->offRegion = 0; /* Disk start. */
1349 pRegion->cbBlock = 512;
1350 pRegion->enmDataForm = VDREGIONDATAFORM_RAW;
1351 pRegion->enmMetadataForm = VDREGIONMETADATAFORM_NONE;
1352 pRegion->cbData = 512;
1353 pRegion->cbMetadata = 0;
1354 pRegion->cRegionBlocksOrBytes = pImage->cbSize;
1355
1356 vdIfProgress(pIfProgress, uPercentStart + uPercentSpan);
1357 }
1358 else
1359 qedFreeImage(pImage, rc != VERR_ALREADY_EXISTS);
1360
1361 return rc;
1362}
1363
1364/**
1365 * Rollback anything done during async cluster allocation.
1366 *
1367 * @returns VBox status code.
1368 * @param pImage The image instance data.
1369 * @param pIoCtx The I/O context.
1370 * @param pClusterAlloc The cluster allocation to rollback.
1371 */
1372static int qedAsyncClusterAllocRollback(PQEDIMAGE pImage, PVDIOCTX pIoCtx, PQEDCLUSTERASYNCALLOC pClusterAlloc)
1373{
1374 RT_NOREF1(pIoCtx);
1375 int rc = VINF_SUCCESS;
1376
1377 switch (pClusterAlloc->enmAllocState)
1378 {
1379 case QEDCLUSTERASYNCALLOCSTATE_L2_ALLOC:
1380 case QEDCLUSTERASYNCALLOCSTATE_L2_LINK:
1381 {
1382 /* Revert the L1 table entry */
1383 pImage->paL1Table[pClusterAlloc->idxL1] = 0;
1384 pImage->pL2TblAlloc = NULL;
1385
1386 /* Assumption right now is that the L1 table is not modified on storage if the link fails. */
1387 rc = vdIfIoIntFileSetSize(pImage->pIfIo, pImage->pStorage, pClusterAlloc->cbImageOld);
1388 qedL2TblCacheEntryRelease(pClusterAlloc->pL2Entry); /* Release L2 cache entry. */
1389 Assert(!pClusterAlloc->pL2Entry->cRefs);
1390 qedL2TblCacheEntryFree(pImage, pClusterAlloc->pL2Entry); /* Free it, it is not in the cache yet. */
1391 break;
1392 }
1393 case QEDCLUSTERASYNCALLOCSTATE_USER_ALLOC:
1394 case QEDCLUSTERASYNCALLOCSTATE_USER_LINK:
1395 {
1396 /* Assumption right now is that the L2 table is not modified if the link fails. */
1397 pClusterAlloc->pL2Entry->paL2Tbl[pClusterAlloc->idxL2] = 0;
1398 rc = vdIfIoIntFileSetSize(pImage->pIfIo, pImage->pStorage, pClusterAlloc->cbImageOld);
1399 qedL2TblCacheEntryRelease(pClusterAlloc->pL2Entry); /* Release L2 cache entry. */
1400 break;
1401 }
1402 default:
1403 AssertMsgFailed(("Invalid cluster allocation state %d\n", pClusterAlloc->enmAllocState));
1404 rc = VERR_INVALID_STATE;
1405 }
1406
1407 RTMemFree(pClusterAlloc);
1408 return rc;
1409}
1410
1411/**
1412 * Updates the state of the async cluster allocation.
1413 *
1414 * @returns VBox status code.
1415 * @param pBackendData The opaque backend data.
1416 * @param pIoCtx I/O context associated with this request.
1417 * @param pvUser Opaque user data passed during a read/write request.
1418 * @param rcReq Status code for the completed request.
1419 */
1420static DECLCALLBACK(int) qedAsyncClusterAllocUpdate(void *pBackendData, PVDIOCTX pIoCtx, void *pvUser, int rcReq)
1421{
1422 int rc = VINF_SUCCESS;
1423 PQEDIMAGE pImage = (PQEDIMAGE)pBackendData;
1424 PQEDCLUSTERASYNCALLOC pClusterAlloc = (PQEDCLUSTERASYNCALLOC)pvUser;
1425
1426 if (RT_FAILURE(rcReq))
1427 return qedAsyncClusterAllocRollback(pImage, pIoCtx, pClusterAlloc);
1428
1429 AssertPtr(pClusterAlloc->pL2Entry);
1430
1431 switch (pClusterAlloc->enmAllocState)
1432 {
1433 case QEDCLUSTERASYNCALLOCSTATE_L2_ALLOC:
1434 {
1435 /* Update the link in the in memory L1 table now. */
1436 pImage->paL1Table[pClusterAlloc->idxL1] = pClusterAlloc->pL2Entry->offL2Tbl;
1437
1438 /* Update the link in the on disk L1 table now. */
1439 pClusterAlloc->enmAllocState = QEDCLUSTERASYNCALLOCSTATE_L2_LINK;
1440 rc = qedTblWrite(pImage, pIoCtx, pImage->offL1Table, pImage->paL1Table,
1441 qedAsyncClusterAllocUpdate, pClusterAlloc);
1442 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
1443 break;
1444 else if (RT_FAILURE(rc))
1445 {
1446 /* Rollback. */
1447 qedAsyncClusterAllocRollback(pImage, pIoCtx, pClusterAlloc);
1448 break;
1449 }
1450 }
1451 RT_FALL_THRU();
1452 case QEDCLUSTERASYNCALLOCSTATE_L2_LINK:
1453 {
1454 /* L2 link updated in L1 , save L2 entry in cache and allocate new user data cluster. */
1455 uint64_t offData = qedClusterAllocate(pImage, 1);
1456
1457 pImage->pL2TblAlloc = NULL;
1458 qedL2TblCacheEntryInsert(pImage, pClusterAlloc->pL2Entry);
1459
1460 pClusterAlloc->enmAllocState = QEDCLUSTERASYNCALLOCSTATE_USER_ALLOC;
1461 pClusterAlloc->cbImageOld = offData;
1462 pClusterAlloc->offClusterNew = offData;
1463
1464 /* Write data. */
1465 rc = vdIfIoIntFileWriteUser(pImage->pIfIo, pImage->pStorage,
1466 offData, pIoCtx, pClusterAlloc->cbToWrite,
1467 qedAsyncClusterAllocUpdate, pClusterAlloc);
1468 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
1469 break;
1470 else if (RT_FAILURE(rc))
1471 {
1472 qedAsyncClusterAllocRollback(pImage, pIoCtx, pClusterAlloc);
1473 RTMemFree(pClusterAlloc);
1474 break;
1475 }
1476 }
1477 RT_FALL_THRU();
1478 case QEDCLUSTERASYNCALLOCSTATE_USER_ALLOC:
1479 {
1480 pClusterAlloc->enmAllocState = QEDCLUSTERASYNCALLOCSTATE_USER_LINK;
1481 pClusterAlloc->pL2Entry->paL2Tbl[pClusterAlloc->idxL2] = pClusterAlloc->offClusterNew;
1482
1483 /* Link L2 table and update it. */
1484 rc = qedTblWrite(pImage, pIoCtx, pImage->paL1Table[pClusterAlloc->idxL1],
1485 pClusterAlloc->pL2Entry->paL2Tbl,
1486 qedAsyncClusterAllocUpdate, pClusterAlloc);
1487 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
1488 break;
1489 else if (RT_FAILURE(rc))
1490 {
1491 qedAsyncClusterAllocRollback(pImage, pIoCtx, pClusterAlloc);
1492 RTMemFree(pClusterAlloc);
1493 break;
1494 }
1495 }
1496 RT_FALL_THRU();
1497 case QEDCLUSTERASYNCALLOCSTATE_USER_LINK:
1498 {
1499 /* Everything done without errors, signal completion. */
1500 qedL2TblCacheEntryRelease(pClusterAlloc->pL2Entry);
1501 RTMemFree(pClusterAlloc);
1502 rc = VINF_SUCCESS;
1503 break;
1504 }
1505 default:
1506 AssertMsgFailed(("Invalid async cluster allocation state %d\n",
1507 pClusterAlloc->enmAllocState));
1508 }
1509
1510 return rc;
1511}
1512
1513/** @copydoc VDIMAGEBACKEND::pfnProbe */
1514static DECLCALLBACK(int) qedProbe(const char *pszFilename, PVDINTERFACE pVDIfsDisk,
1515 PVDINTERFACE pVDIfsImage, VDTYPE enmDesiredType, VDTYPE *penmType)
1516{
1517 RT_NOREF(pVDIfsDisk, enmDesiredType);
1518 LogFlowFunc(("pszFilename=\"%s\" pVDIfsDisk=%#p pVDIfsImage=%#p\n", pszFilename, pVDIfsDisk, pVDIfsImage));
1519 PVDIOSTORAGE pStorage = NULL;
1520 int rc = VINF_SUCCESS;
1521
1522 /* Get I/O interface. */
1523 PVDINTERFACEIOINT pIfIo = VDIfIoIntGet(pVDIfsImage);
1524 AssertPtrReturn(pIfIo, VERR_INVALID_PARAMETER);
1525 AssertPtrReturn(pszFilename, VERR_INVALID_POINTER);
1526 AssertReturn(*pszFilename != '\0', VERR_INVALID_PARAMETER);
1527
1528
1529 /*
1530 * Open the file and read the footer.
1531 */
1532 rc = vdIfIoIntFileOpen(pIfIo, pszFilename,
1533 VDOpenFlagsToFileOpenFlags(VD_OPEN_FLAGS_READONLY,
1534 false /* fCreate */),
1535 &pStorage);
1536 if (RT_SUCCESS(rc))
1537 {
1538 uint64_t cbFile;
1539
1540 rc = vdIfIoIntFileGetSize(pIfIo, pStorage, &cbFile);
1541 if ( RT_SUCCESS(rc)
1542 && cbFile > sizeof(QedHeader))
1543 {
1544 QedHeader Header;
1545
1546 rc = vdIfIoIntFileReadSync(pIfIo, pStorage, 0, &Header, sizeof(Header));
1547 if ( RT_SUCCESS(rc)
1548 && qedHdrConvertToHostEndianess(&Header))
1549 *penmType = VDTYPE_HDD;
1550 else
1551 rc = VERR_VD_GEN_INVALID_HEADER;
1552 }
1553 else
1554 rc = VERR_VD_GEN_INVALID_HEADER;
1555 }
1556
1557 if (pStorage)
1558 vdIfIoIntFileClose(pIfIo, pStorage);
1559
1560 LogFlowFunc(("returns %Rrc\n", rc));
1561 return rc;
1562}
1563
1564/** @copydoc VDIMAGEBACKEND::pfnOpen */
1565static DECLCALLBACK(int) qedOpen(const char *pszFilename, unsigned uOpenFlags,
1566 PVDINTERFACE pVDIfsDisk, PVDINTERFACE pVDIfsImage,
1567 VDTYPE enmType, void **ppBackendData)
1568{
1569 RT_NOREF1(enmType); /**< @todo r=klaus make use of the type info. */
1570
1571 LogFlowFunc(("pszFilename=\"%s\" uOpenFlags=%#x pVDIfsDisk=%#p pVDIfsImage=%#p enmType=%u ppBackendData=%#p\n",
1572 pszFilename, uOpenFlags, pVDIfsDisk, pVDIfsImage, enmType, ppBackendData));
1573 int rc;
1574
1575 /* Check open flags. All valid flags are supported. */
1576 AssertReturn(!(uOpenFlags & ~VD_OPEN_FLAGS_MASK), VERR_INVALID_PARAMETER);
1577 AssertPtrReturn(pszFilename, VERR_INVALID_POINTER);
1578 AssertReturn(*pszFilename != '\0', VERR_INVALID_PARAMETER);
1579
1580
1581 PQEDIMAGE pImage = (PQEDIMAGE)RTMemAllocZ(RT_UOFFSETOF(QEDIMAGE, RegionList.aRegions[1]));
1582 if (RT_LIKELY(pImage))
1583 {
1584 pImage->pszFilename = pszFilename;
1585 pImage->pStorage = NULL;
1586 pImage->pVDIfsDisk = pVDIfsDisk;
1587 pImage->pVDIfsImage = pVDIfsImage;
1588
1589 rc = qedOpenImage(pImage, uOpenFlags);
1590 if (RT_SUCCESS(rc))
1591 *ppBackendData = pImage;
1592 else
1593 RTMemFree(pImage);
1594 }
1595 else
1596 rc = VERR_NO_MEMORY;
1597
1598 LogFlowFunc(("returns %Rrc (pBackendData=%#p)\n", rc, *ppBackendData));
1599 return rc;
1600}
1601
1602/** @copydoc VDIMAGEBACKEND::pfnCreate */
1603static DECLCALLBACK(int) qedCreate(const char *pszFilename, uint64_t cbSize,
1604 unsigned uImageFlags, const char *pszComment,
1605 PCVDGEOMETRY pPCHSGeometry, PCVDGEOMETRY pLCHSGeometry,
1606 PCRTUUID pUuid, unsigned uOpenFlags,
1607 unsigned uPercentStart, unsigned uPercentSpan,
1608 PVDINTERFACE pVDIfsDisk, PVDINTERFACE pVDIfsImage,
1609 PVDINTERFACE pVDIfsOperation, VDTYPE enmType,
1610 void **ppBackendData)
1611{
1612 RT_NOREF1(pUuid);
1613 LogFlowFunc(("pszFilename=\"%s\" cbSize=%llu uImageFlags=%#x pszComment=\"%s\" pPCHSGeometry=%#p pLCHSGeometry=%#p Uuid=%RTuuid uOpenFlags=%#x uPercentStart=%u uPercentSpan=%u pVDIfsDisk=%#p pVDIfsImage=%#p pVDIfsOperation=%#p enmType=%d ppBackendData=%#p",
1614 pszFilename, cbSize, uImageFlags, pszComment, pPCHSGeometry, pLCHSGeometry, pUuid, uOpenFlags, uPercentStart, uPercentSpan, pVDIfsDisk, pVDIfsImage, pVDIfsOperation, enmType, ppBackendData));
1615 int rc;
1616
1617 /* Check the VD container type. */
1618 if (enmType != VDTYPE_HDD)
1619 return VERR_VD_INVALID_TYPE;
1620
1621 /* Check open flags. All valid flags are supported. */
1622 AssertReturn(!(uOpenFlags & ~VD_OPEN_FLAGS_MASK), VERR_INVALID_PARAMETER);
1623 AssertPtrReturn(pszFilename, VERR_INVALID_POINTER);
1624 AssertReturn(*pszFilename != '\0', VERR_INVALID_PARAMETER);
1625 AssertPtrReturn(pPCHSGeometry, VERR_INVALID_POINTER);
1626 AssertPtrReturn(pLCHSGeometry, VERR_INVALID_POINTER);
1627
1628 PQEDIMAGE pImage = (PQEDIMAGE)RTMemAllocZ(RT_UOFFSETOF(QEDIMAGE, RegionList.aRegions[1]));
1629 if (RT_LIKELY(pImage))
1630 {
1631 PVDINTERFACEPROGRESS pIfProgress = VDIfProgressGet(pVDIfsOperation);
1632
1633 pImage->pszFilename = pszFilename;
1634 pImage->pStorage = NULL;
1635 pImage->pVDIfsDisk = pVDIfsDisk;
1636 pImage->pVDIfsImage = pVDIfsImage;
1637
1638 rc = qedCreateImage(pImage, cbSize, uImageFlags, pszComment,
1639 pPCHSGeometry, pLCHSGeometry, uOpenFlags,
1640 pIfProgress, uPercentStart, uPercentSpan);
1641 if (RT_SUCCESS(rc))
1642 {
1643 /* So far the image is opened in read/write mode. Make sure the
1644 * image is opened in read-only mode if the caller requested that. */
1645 if (uOpenFlags & VD_OPEN_FLAGS_READONLY)
1646 {
1647 qedFreeImage(pImage, false);
1648 rc = qedOpenImage(pImage, uOpenFlags);
1649 }
1650
1651 if (RT_SUCCESS(rc))
1652 *ppBackendData = pImage;
1653 }
1654
1655 if (RT_FAILURE(rc))
1656 RTMemFree(pImage);
1657 }
1658 else
1659 rc = VERR_NO_MEMORY;
1660
1661 LogFlowFunc(("returns %Rrc (pBackendData=%#p)\n", rc, *ppBackendData));
1662 return rc;
1663}
1664
1665/** @copydoc VDIMAGEBACKEND::pfnRename */
1666static DECLCALLBACK(int) qedRename(void *pBackendData, const char *pszFilename)
1667{
1668 LogFlowFunc(("pBackendData=%#p pszFilename=%#p\n", pBackendData, pszFilename));
1669 int rc = VINF_SUCCESS;
1670 PQEDIMAGE pImage = (PQEDIMAGE)pBackendData;
1671
1672 /* Check arguments. */
1673 AssertReturn((pImage && pszFilename && *pszFilename), VERR_INVALID_PARAMETER);
1674
1675 /* Close the image. */
1676 rc = qedFreeImage(pImage, false);
1677 if (RT_SUCCESS(rc))
1678 {
1679 /* Rename the file. */
1680 rc = vdIfIoIntFileMove(pImage->pIfIo, pImage->pszFilename, pszFilename, 0);
1681 if (RT_SUCCESS(rc))
1682 {
1683 /* Update pImage with the new information. */
1684 pImage->pszFilename = pszFilename;
1685
1686 /* Open the old image with new name. */
1687 rc = qedOpenImage(pImage, pImage->uOpenFlags);
1688 }
1689 else
1690 {
1691 /* The move failed, try to reopen the original image. */
1692 int rc2 = qedOpenImage(pImage, pImage->uOpenFlags);
1693 if (RT_FAILURE(rc2))
1694 rc = rc2;
1695 }
1696 }
1697
1698 LogFlowFunc(("returns %Rrc\n", rc));
1699 return rc;
1700}
1701
1702/** @copydoc VDIMAGEBACKEND::pfnClose */
1703static DECLCALLBACK(int) qedClose(void *pBackendData, bool fDelete)
1704{
1705 LogFlowFunc(("pBackendData=%#p fDelete=%d\n", pBackendData, fDelete));
1706 PQEDIMAGE pImage = (PQEDIMAGE)pBackendData;
1707
1708 int rc = qedFreeImage(pImage, fDelete);
1709 RTMemFree(pImage);
1710
1711 LogFlowFunc(("returns %Rrc\n", rc));
1712 return rc;
1713}
1714
1715/** @copydoc VDIMAGEBACKEND::pfnRead */
1716static DECLCALLBACK(int) qedRead(void *pBackendData, uint64_t uOffset, size_t cbToRead,
1717 PVDIOCTX pIoCtx, size_t *pcbActuallyRead)
1718{
1719 LogFlowFunc(("pBackendData=%#p uOffset=%llu pIoCtx=%#p cbToRead=%zu pcbActuallyRead=%#p\n",
1720 pBackendData, uOffset, pIoCtx, cbToRead, pcbActuallyRead));
1721 PQEDIMAGE pImage = (PQEDIMAGE)pBackendData;
1722 uint32_t offCluster = 0;
1723 uint32_t idxL1 = 0;
1724 uint32_t idxL2 = 0;
1725 uint64_t offFile = 0;
1726
1727 AssertPtr(pImage);
1728 Assert(uOffset % 512 == 0);
1729 Assert(cbToRead % 512 == 0);
1730 AssertPtrReturn(pIoCtx, VERR_INVALID_POINTER);
1731 AssertReturn(cbToRead, VERR_INVALID_PARAMETER);
1732 AssertReturn(uOffset + cbToRead <= pImage->cbSize, VERR_INVALID_PARAMETER);
1733
1734 qedConvertLogicalOffset(pImage, uOffset, &idxL1, &idxL2, &offCluster);
1735
1736 /* Clip read size to remain in the cluster. */
1737 cbToRead = RT_MIN(cbToRead, pImage->cbCluster - offCluster);
1738
1739 /* Get offset in image. */
1740 int rc = qedConvertToImageOffset(pImage, pIoCtx, idxL1, idxL2, offCluster, &offFile);
1741 if (RT_SUCCESS(rc))
1742 rc = vdIfIoIntFileReadUser(pImage->pIfIo, pImage->pStorage, offFile,
1743 pIoCtx, cbToRead);
1744
1745 if ( ( RT_SUCCESS(rc)
1746 || rc == VERR_VD_BLOCK_FREE
1747 || rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
1748 && pcbActuallyRead)
1749 *pcbActuallyRead = cbToRead;
1750
1751 LogFlowFunc(("returns %Rrc\n", rc));
1752 return rc;
1753}
1754
1755/** @copydoc VDIMAGEBACKEND::pfnWrite */
1756static DECLCALLBACK(int) qedWrite(void *pBackendData, uint64_t uOffset, size_t cbToWrite,
1757 PVDIOCTX pIoCtx, size_t *pcbWriteProcess, size_t *pcbPreRead,
1758 size_t *pcbPostRead, unsigned fWrite)
1759{
1760 LogFlowFunc(("pBackendData=%#p uOffset=%llu pIoCtx=%#p cbToWrite=%zu pcbWriteProcess=%#p pcbPreRead=%#p pcbPostRead=%#p\n",
1761 pBackendData, uOffset, pIoCtx, cbToWrite, pcbWriteProcess, pcbPreRead, pcbPostRead));
1762 PQEDIMAGE pImage = (PQEDIMAGE)pBackendData;
1763 uint32_t offCluster = 0;
1764 uint32_t idxL1 = 0;
1765 uint32_t idxL2 = 0;
1766 uint64_t offImage = 0;
1767 int rc = VINF_SUCCESS;
1768
1769 AssertPtr(pImage);
1770 Assert(!(uOffset % 512));
1771 Assert(!(cbToWrite % 512));
1772 AssertPtrReturn(pIoCtx, VERR_INVALID_POINTER);
1773 AssertReturn(cbToWrite, VERR_INVALID_PARAMETER);
1774 AssertReturn(uOffset + cbToWrite <= pImage->cbSize, VERR_INVALID_PARAMETER);
1775
1776 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
1777 {
1778 /* Convert offset to L1, L2 index and cluster offset. */
1779 qedConvertLogicalOffset(pImage, uOffset, &idxL1, &idxL2, &offCluster);
1780
1781 /* Clip write size to remain in the cluster. */
1782 cbToWrite = RT_MIN(cbToWrite, pImage->cbCluster - offCluster);
1783 Assert(!(cbToWrite % 512));
1784
1785 /* Get offset in image. */
1786 rc = qedConvertToImageOffset(pImage, pIoCtx, idxL1, idxL2, offCluster, &offImage);
1787 if (RT_SUCCESS(rc))
1788 rc = vdIfIoIntFileWriteUser(pImage->pIfIo, pImage->pStorage,
1789 offImage, pIoCtx, cbToWrite, NULL, NULL);
1790 else if (rc == VERR_VD_BLOCK_FREE)
1791 {
1792 if ( cbToWrite == pImage->cbCluster
1793 && !(fWrite & VD_WRITE_NO_ALLOC))
1794 {
1795 PQEDL2CACHEENTRY pL2Entry = NULL;
1796
1797 /* Full cluster write to previously unallocated cluster.
1798 * Allocate cluster and write data. */
1799 Assert(!offCluster);
1800
1801 do
1802 {
1803 /* Check if we have to allocate a new cluster for L2 tables. */
1804 if (!pImage->paL1Table[idxL1])
1805 {
1806 uint64_t offL2Tbl;
1807 PQEDCLUSTERASYNCALLOC pL2ClusterAlloc = NULL;
1808
1809 /* Allocate new async cluster allocation state. */
1810 pL2ClusterAlloc = (PQEDCLUSTERASYNCALLOC)RTMemAllocZ(sizeof(QEDCLUSTERASYNCALLOC));
1811 if (RT_UNLIKELY(!pL2ClusterAlloc))
1812 {
1813 rc = VERR_NO_MEMORY;
1814 break;
1815 }
1816
1817 pL2Entry = qedL2TblCacheEntryAlloc(pImage);
1818 if (!pL2Entry)
1819 {
1820 rc = VERR_NO_MEMORY;
1821 RTMemFree(pL2ClusterAlloc);
1822 break;
1823 }
1824
1825 offL2Tbl = qedClusterAllocate(pImage, qedByte2Cluster(pImage, pImage->cbTable));
1826 pL2Entry->offL2Tbl = offL2Tbl;
1827 memset(pL2Entry->paL2Tbl, 0, pImage->cbTable);
1828
1829 pL2ClusterAlloc->enmAllocState = QEDCLUSTERASYNCALLOCSTATE_L2_ALLOC;
1830 pL2ClusterAlloc->cbImageOld = offL2Tbl;
1831 pL2ClusterAlloc->offClusterNew = offL2Tbl;
1832 pL2ClusterAlloc->idxL1 = idxL1;
1833 pL2ClusterAlloc->idxL2 = idxL2;
1834 pL2ClusterAlloc->cbToWrite = cbToWrite;
1835 pL2ClusterAlloc->pL2Entry = pL2Entry;
1836
1837 pImage->pL2TblAlloc = pL2Entry;
1838
1839 LogFlowFunc(("Allocating new L2 table at cluster offset %llu\n", offL2Tbl));
1840
1841 /*
1842 * Write the L2 table first and link to the L1 table afterwards.
1843 * If something unexpected happens the worst case which can happen
1844 * is a leak of some clusters.
1845 */
1846 rc = vdIfIoIntFileWriteMeta(pImage->pIfIo, pImage->pStorage,
1847 offL2Tbl, pL2Entry->paL2Tbl, pImage->cbTable, pIoCtx,
1848 qedAsyncClusterAllocUpdate, pL2ClusterAlloc);
1849 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
1850 break;
1851 else if (RT_FAILURE(rc))
1852 {
1853 RTMemFree(pL2ClusterAlloc);
1854 qedL2TblCacheEntryFree(pImage, pL2Entry);
1855 break;
1856 }
1857
1858 rc = qedAsyncClusterAllocUpdate(pImage, pIoCtx, pL2ClusterAlloc, rc);
1859 }
1860 else
1861 {
1862 LogFlowFunc(("Fetching L2 table at cluster offset %llu\n", pImage->paL1Table[idxL1]));
1863
1864 rc = qedL2TblCacheFetchAsync(pImage, pIoCtx, pImage->paL1Table[idxL1],
1865 &pL2Entry);
1866
1867 if (RT_SUCCESS(rc))
1868 {
1869 PQEDCLUSTERASYNCALLOC pDataClusterAlloc = NULL;
1870
1871 /* Allocate new async cluster allocation state. */
1872 pDataClusterAlloc = (PQEDCLUSTERASYNCALLOC)RTMemAllocZ(sizeof(QEDCLUSTERASYNCALLOC));
1873 if (RT_UNLIKELY(!pDataClusterAlloc))
1874 {
1875 rc = VERR_NO_MEMORY;
1876 break;
1877 }
1878
1879 /* Allocate new cluster for the data. */
1880 uint64_t offData = qedClusterAllocate(pImage, 1);
1881
1882 pDataClusterAlloc->enmAllocState = QEDCLUSTERASYNCALLOCSTATE_USER_ALLOC;
1883 pDataClusterAlloc->cbImageOld = offData;
1884 pDataClusterAlloc->offClusterNew = offData;
1885 pDataClusterAlloc->idxL1 = idxL1;
1886 pDataClusterAlloc->idxL2 = idxL2;
1887 pDataClusterAlloc->cbToWrite = cbToWrite;
1888 pDataClusterAlloc->pL2Entry = pL2Entry;
1889
1890 /* Write data. */
1891 rc = vdIfIoIntFileWriteUser(pImage->pIfIo, pImage->pStorage,
1892 offData, pIoCtx, cbToWrite,
1893 qedAsyncClusterAllocUpdate, pDataClusterAlloc);
1894 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
1895 break;
1896 else if (RT_FAILURE(rc))
1897 {
1898 RTMemFree(pDataClusterAlloc);
1899 break;
1900 }
1901
1902 rc = qedAsyncClusterAllocUpdate(pImage, pIoCtx, pDataClusterAlloc, rc);
1903 }
1904 }
1905
1906 } while (0);
1907
1908 *pcbPreRead = 0;
1909 *pcbPostRead = 0;
1910 }
1911 else
1912 {
1913 /* Trying to do a partial write to an unallocated cluster. Don't do
1914 * anything except letting the upper layer know what to do. */
1915 *pcbPreRead = offCluster;
1916 *pcbPostRead = pImage->cbCluster - cbToWrite - *pcbPreRead;
1917 }
1918 }
1919
1920 if (pcbWriteProcess)
1921 *pcbWriteProcess = cbToWrite;
1922 }
1923 else
1924 rc = VERR_VD_IMAGE_READ_ONLY;
1925
1926 LogFlowFunc(("returns %Rrc\n", rc));
1927 return rc;
1928}
1929
1930/** @copydoc VDIMAGEBACKEND::pfnFlush */
1931static DECLCALLBACK(int) qedFlush(void *pBackendData, PVDIOCTX pIoCtx)
1932{
1933 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
1934 PQEDIMAGE pImage = (PQEDIMAGE)pBackendData;
1935 int rc = VINF_SUCCESS;
1936
1937 AssertPtr(pImage);
1938 AssertPtrReturn(pIoCtx, VERR_INVALID_PARAMETER);
1939
1940 if ( pImage->pStorage
1941 && !(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
1942 {
1943 QedHeader Header;
1944
1945 Assert(!(pImage->cbTable % pImage->cbCluster));
1946 rc = qedTblWrite(pImage, pIoCtx, pImage->offL1Table, pImage->paL1Table,
1947 NULL, NULL);
1948 if (RT_SUCCESS(rc) || rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
1949 {
1950 /* Write header. */
1951 qedHdrConvertFromHostEndianess(pImage, &Header);
1952 rc = vdIfIoIntFileWriteMeta(pImage->pIfIo, pImage->pStorage,
1953 0, &Header, sizeof(Header),
1954 pIoCtx, NULL, NULL);
1955 if (RT_SUCCESS(rc) || rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
1956 rc = vdIfIoIntFileFlush(pImage->pIfIo, pImage->pStorage,
1957 pIoCtx, NULL, NULL);
1958 }
1959 }
1960
1961 LogFlowFunc(("returns %Rrc\n", rc));
1962 return rc;
1963}
1964
1965/** @copydoc VDIMAGEBACKEND::pfnGetVersion */
1966static DECLCALLBACK(unsigned) qedGetVersion(void *pBackendData)
1967{
1968 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
1969 PQEDIMAGE pImage = (PQEDIMAGE)pBackendData;
1970
1971 AssertPtrReturn(pImage, 0);
1972
1973 return 1;
1974}
1975
1976/** @copydoc VDIMAGEBACKEND::pfnGetFileSize */
1977static DECLCALLBACK(uint64_t) qedGetFileSize(void *pBackendData)
1978{
1979 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
1980 PQEDIMAGE pImage = (PQEDIMAGE)pBackendData;
1981 uint64_t cb = 0;
1982
1983 AssertPtrReturn(pImage, 0);
1984
1985 uint64_t cbFile;
1986 if (pImage->pStorage)
1987 {
1988 int rc = vdIfIoIntFileGetSize(pImage->pIfIo, pImage->pStorage, &cbFile);
1989 if (RT_SUCCESS(rc))
1990 cb += cbFile;
1991 }
1992
1993 LogFlowFunc(("returns %lld\n", cb));
1994 return cb;
1995}
1996
1997/** @copydoc VDIMAGEBACKEND::pfnGetPCHSGeometry */
1998static DECLCALLBACK(int) qedGetPCHSGeometry(void *pBackendData,
1999 PVDGEOMETRY pPCHSGeometry)
2000{
2001 LogFlowFunc(("pBackendData=%#p pPCHSGeometry=%#p\n", pBackendData, pPCHSGeometry));
2002 PQEDIMAGE pImage = (PQEDIMAGE)pBackendData;
2003 int rc = VINF_SUCCESS;
2004
2005 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
2006
2007 if (pImage->PCHSGeometry.cCylinders)
2008 *pPCHSGeometry = pImage->PCHSGeometry;
2009 else
2010 rc = VERR_VD_GEOMETRY_NOT_SET;
2011
2012 LogFlowFunc(("returns %Rrc (PCHS=%u/%u/%u)\n", rc, pPCHSGeometry->cCylinders, pPCHSGeometry->cHeads, pPCHSGeometry->cSectors));
2013 return rc;
2014}
2015
2016/** @copydoc VDIMAGEBACKEND::pfnSetPCHSGeometry */
2017static DECLCALLBACK(int) qedSetPCHSGeometry(void *pBackendData,
2018 PCVDGEOMETRY pPCHSGeometry)
2019{
2020 LogFlowFunc(("pBackendData=%#p pPCHSGeometry=%#p PCHS=%u/%u/%u\n",
2021 pBackendData, pPCHSGeometry, pPCHSGeometry->cCylinders, pPCHSGeometry->cHeads, pPCHSGeometry->cSectors));
2022 PQEDIMAGE pImage = (PQEDIMAGE)pBackendData;
2023 int rc = VINF_SUCCESS;
2024
2025 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
2026
2027 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
2028 rc = VERR_VD_IMAGE_READ_ONLY;
2029 else
2030 pImage->PCHSGeometry = *pPCHSGeometry;
2031
2032 LogFlowFunc(("returns %Rrc\n", rc));
2033 return rc;
2034}
2035
2036/** @copydoc VDIMAGEBACKEND::pfnGetLCHSGeometry */
2037static DECLCALLBACK(int) qedGetLCHSGeometry(void *pBackendData, PVDGEOMETRY pLCHSGeometry)
2038{
2039 LogFlowFunc(("pBackendData=%#p pLCHSGeometry=%#p\n", pBackendData, pLCHSGeometry));
2040 PQEDIMAGE pImage = (PQEDIMAGE)pBackendData;
2041 int rc = VINF_SUCCESS;
2042
2043 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
2044
2045 if (pImage->LCHSGeometry.cCylinders)
2046 *pLCHSGeometry = pImage->LCHSGeometry;
2047 else
2048 rc = VERR_VD_GEOMETRY_NOT_SET;
2049
2050 LogFlowFunc(("returns %Rrc (LCHS=%u/%u/%u)\n", rc, pLCHSGeometry->cCylinders,
2051 pLCHSGeometry->cHeads, pLCHSGeometry->cSectors));
2052 return rc;
2053}
2054
2055/** @copydoc VDIMAGEBACKEND::pfnSetLCHSGeometry */
2056static DECLCALLBACK(int) qedSetLCHSGeometry(void *pBackendData, PCVDGEOMETRY pLCHSGeometry)
2057{
2058 LogFlowFunc(("pBackendData=%#p pLCHSGeometry=%#p LCHS=%u/%u/%u\n", pBackendData,
2059 pLCHSGeometry, pLCHSGeometry->cCylinders, pLCHSGeometry->cHeads, pLCHSGeometry->cSectors));
2060 PQEDIMAGE pImage = (PQEDIMAGE)pBackendData;
2061 int rc = VINF_SUCCESS;
2062
2063 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
2064
2065 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
2066 rc = VERR_VD_IMAGE_READ_ONLY;
2067 else
2068 pImage->LCHSGeometry = *pLCHSGeometry;
2069
2070 LogFlowFunc(("returns %Rrc\n", rc));
2071 return rc;
2072}
2073
2074/** @copydoc VDIMAGEBACKEND::pfnQueryRegions */
2075static DECLCALLBACK(int) qedQueryRegions(void *pBackendData, PCVDREGIONLIST *ppRegionList)
2076{
2077 LogFlowFunc(("pBackendData=%#p ppRegionList=%#p\n", pBackendData, ppRegionList));
2078 PQEDIMAGE pThis = (PQEDIMAGE)pBackendData;
2079
2080 AssertPtrReturn(pThis, VERR_VD_NOT_OPENED);
2081
2082 *ppRegionList = &pThis->RegionList;
2083 LogFlowFunc(("returns %Rrc\n", VINF_SUCCESS));
2084 return VINF_SUCCESS;
2085}
2086
2087/** @copydoc VDIMAGEBACKEND::pfnRegionListRelease */
2088static DECLCALLBACK(void) qedRegionListRelease(void *pBackendData, PCVDREGIONLIST pRegionList)
2089{
2090 RT_NOREF1(pRegionList);
2091 LogFlowFunc(("pBackendData=%#p pRegionList=%#p\n", pBackendData, pRegionList));
2092 PQEDIMAGE pThis = (PQEDIMAGE)pBackendData;
2093 AssertPtr(pThis); RT_NOREF(pThis);
2094
2095 /* Nothing to do here. */
2096}
2097
2098/** @copydoc VDIMAGEBACKEND::pfnGetImageFlags */
2099static DECLCALLBACK(unsigned) qedGetImageFlags(void *pBackendData)
2100{
2101 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
2102 PQEDIMAGE pImage = (PQEDIMAGE)pBackendData;
2103
2104 AssertPtrReturn(pImage, 0);
2105
2106 LogFlowFunc(("returns %#x\n", pImage->uImageFlags));
2107 return pImage->uImageFlags;
2108}
2109
2110/** @copydoc VDIMAGEBACKEND::pfnGetOpenFlags */
2111static DECLCALLBACK(unsigned) qedGetOpenFlags(void *pBackendData)
2112{
2113 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
2114 PQEDIMAGE pImage = (PQEDIMAGE)pBackendData;
2115
2116 AssertPtrReturn(pImage, 0);
2117
2118 LogFlowFunc(("returns %#x\n", pImage->uOpenFlags));
2119 return pImage->uOpenFlags;
2120}
2121
2122/** @copydoc VDIMAGEBACKEND::pfnSetOpenFlags */
2123static DECLCALLBACK(int) qedSetOpenFlags(void *pBackendData, unsigned uOpenFlags)
2124{
2125 LogFlowFunc(("pBackendData=%#p\n uOpenFlags=%#x", pBackendData, uOpenFlags));
2126 PQEDIMAGE pImage = (PQEDIMAGE)pBackendData;
2127 int rc = VINF_SUCCESS;
2128
2129 /* Image must be opened and the new flags must be valid. */
2130 if (!pImage || (uOpenFlags & ~( VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_INFO
2131 | VD_OPEN_FLAGS_ASYNC_IO | VD_OPEN_FLAGS_SHAREABLE
2132 | VD_OPEN_FLAGS_SEQUENTIAL | VD_OPEN_FLAGS_SKIP_CONSISTENCY_CHECKS)))
2133 rc = VERR_INVALID_PARAMETER;
2134 else
2135 {
2136 /* Implement this operation via reopening the image. */
2137 rc = qedFreeImage(pImage, false);
2138 if (RT_SUCCESS(rc))
2139 rc = qedOpenImage(pImage, uOpenFlags);
2140 }
2141
2142 LogFlowFunc(("returns %Rrc\n", rc));
2143 return rc;
2144}
2145
2146/** @copydoc VDIMAGEBACKEND::pfnGetComment */
2147VD_BACKEND_CALLBACK_GET_COMMENT_DEF_NOT_SUPPORTED(qedGetComment);
2148
2149/** @copydoc VDIMAGEBACKEND::pfnSetComment */
2150VD_BACKEND_CALLBACK_SET_COMMENT_DEF_NOT_SUPPORTED(qedSetComment, PQEDIMAGE);
2151
2152/** @copydoc VDIMAGEBACKEND::pfnGetUuid */
2153VD_BACKEND_CALLBACK_GET_UUID_DEF_NOT_SUPPORTED(qedGetUuid);
2154
2155/** @copydoc VDIMAGEBACKEND::pfnSetUuid */
2156VD_BACKEND_CALLBACK_SET_UUID_DEF_NOT_SUPPORTED(qedSetUuid, PQEDIMAGE);
2157
2158/** @copydoc VDIMAGEBACKEND::pfnGetModificationUuid */
2159VD_BACKEND_CALLBACK_GET_UUID_DEF_NOT_SUPPORTED(qedGetModificationUuid);
2160
2161/** @copydoc VDIMAGEBACKEND::pfnSetModificationUuid */
2162VD_BACKEND_CALLBACK_SET_UUID_DEF_NOT_SUPPORTED(qedSetModificationUuid, PQEDIMAGE);
2163
2164/** @copydoc VDIMAGEBACKEND::pfnGetParentUuid */
2165VD_BACKEND_CALLBACK_GET_UUID_DEF_NOT_SUPPORTED(qedGetParentUuid);
2166
2167/** @copydoc VDIMAGEBACKEND::pfnSetParentUuid */
2168VD_BACKEND_CALLBACK_SET_UUID_DEF_NOT_SUPPORTED(qedSetParentUuid, PQEDIMAGE);
2169
2170/** @copydoc VDIMAGEBACKEND::pfnGetParentModificationUuid */
2171VD_BACKEND_CALLBACK_GET_UUID_DEF_NOT_SUPPORTED(qedGetParentModificationUuid);
2172
2173/** @copydoc VDIMAGEBACKEND::pfnSetParentModificationUuid */
2174VD_BACKEND_CALLBACK_SET_UUID_DEF_NOT_SUPPORTED(qedSetParentModificationUuid, PQEDIMAGE);
2175
2176/** @copydoc VDIMAGEBACKEND::pfnDump */
2177static DECLCALLBACK(void) qedDump(void *pBackendData)
2178{
2179 PQEDIMAGE pImage = (PQEDIMAGE)pBackendData;
2180
2181 AssertPtrReturnVoid(pImage);
2182 vdIfErrorMessage(pImage->pIfError, "Header: Geometry PCHS=%u/%u/%u LCHS=%u/%u/%u cbSector=%llu\n",
2183 pImage->PCHSGeometry.cCylinders, pImage->PCHSGeometry.cHeads, pImage->PCHSGeometry.cSectors,
2184 pImage->LCHSGeometry.cCylinders, pImage->LCHSGeometry.cHeads, pImage->LCHSGeometry.cSectors,
2185 pImage->cbSize / 512);
2186}
2187
2188/** @copydoc VDIMAGEBACKEND::pfnGetParentFilename */
2189static DECLCALLBACK(int) qedGetParentFilename(void *pBackendData, char **ppszParentFilename)
2190{
2191 int rc = VINF_SUCCESS;
2192 PQEDIMAGE pImage = (PQEDIMAGE)pBackendData;
2193
2194 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
2195
2196 if (pImage->pszBackingFilename)
2197 *ppszParentFilename = RTStrDup(pImage->pszBackingFilename);
2198 else
2199 rc = VERR_NOT_SUPPORTED;
2200
2201 LogFlowFunc(("returns %Rrc\n", rc));
2202 return rc;
2203}
2204
2205/** @copydoc VDIMAGEBACKEND::pfnSetParentFilename */
2206static DECLCALLBACK(int) qedSetParentFilename(void *pBackendData, const char *pszParentFilename)
2207{
2208 int rc = VINF_SUCCESS;
2209 PQEDIMAGE pImage = (PQEDIMAGE)pBackendData;
2210
2211 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
2212
2213 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
2214 rc = VERR_VD_IMAGE_READ_ONLY;
2215 else if ( pImage->pszBackingFilename
2216 && (strlen(pszParentFilename) > pImage->cbBackingFilename))
2217 rc = VERR_NOT_SUPPORTED; /* The new filename is longer than the old one. */
2218 else
2219 {
2220 if (pImage->pszBackingFilename)
2221 RTStrFree(pImage->pszBackingFilename);
2222 pImage->pszBackingFilename = RTStrDup(pszParentFilename);
2223 if (!pImage->pszBackingFilename)
2224 rc = VERR_NO_STR_MEMORY;
2225 else
2226 {
2227 if (!pImage->offBackingFilename)
2228 {
2229 /* Allocate new cluster. */
2230 uint64_t offData = qedClusterAllocate(pImage, 1);
2231
2232 Assert((offData & UINT32_MAX) == offData);
2233 pImage->offBackingFilename = (uint32_t)offData;
2234 pImage->cbBackingFilename = (uint32_t)strlen(pszParentFilename);
2235 rc = vdIfIoIntFileSetSize(pImage->pIfIo, pImage->pStorage,
2236 offData + pImage->cbCluster);
2237 }
2238
2239 if (RT_SUCCESS(rc))
2240 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pImage->pStorage,
2241 pImage->offBackingFilename,
2242 pImage->pszBackingFilename,
2243 strlen(pImage->pszBackingFilename));
2244 }
2245 }
2246
2247 LogFlowFunc(("returns %Rrc\n", rc));
2248 return rc;
2249}
2250
2251/** @copydoc VDIMAGEBACKEND::pfnResize */
2252static DECLCALLBACK(int) qedResize(void *pBackendData, uint64_t cbSize,
2253 PCVDGEOMETRY pPCHSGeometry, PCVDGEOMETRY pLCHSGeometry,
2254 unsigned uPercentStart, unsigned uPercentSpan,
2255 PVDINTERFACE pVDIfsDisk, PVDINTERFACE pVDIfsImage,
2256 PVDINTERFACE pVDIfsOperation)
2257{
2258 RT_NOREF7(pPCHSGeometry, pLCHSGeometry, uPercentStart, uPercentSpan, pVDIfsDisk, pVDIfsImage, pVDIfsOperation);
2259 PQEDIMAGE pImage = (PQEDIMAGE)pBackendData;
2260 int rc = VINF_SUCCESS;
2261
2262 /* Making the image smaller is not supported at the moment. */
2263 if (cbSize < pImage->cbSize)
2264 rc = VERR_NOT_SUPPORTED;
2265 else if (cbSize > pImage->cbSize)
2266 {
2267 /*
2268 * It is enough to just update the size field in the header to complete
2269 * growing. With the default cluster and table sizes the image can be expanded
2270 * to 64TB without overflowing the L1 and L2 tables making block relocation
2271 * superfluous.
2272 * @todo: The rare case where block relocation is still required (non default
2273 * table and/or cluster size or images with more than 64TB) is not
2274 * implemented yet and resizing such an image will fail with an error.
2275 */
2276 if (qedByte2Cluster(pImage, pImage->cbTable)*pImage->cTableEntries*pImage->cTableEntries*pImage->cbCluster < cbSize)
2277 rc = vdIfError(pImage->pIfError, VERR_BUFFER_OVERFLOW, RT_SRC_POS,
2278 N_("Qed: Resizing the image '%s' is not supported because it would overflow the L1 and L2 table\n"),
2279 pImage->pszFilename);
2280 else
2281 {
2282 uint64_t cbSizeOld = pImage->cbSize;
2283
2284 pImage->cbSize = cbSize;
2285 rc = qedFlushImage(pImage);
2286 if (RT_FAILURE(rc))
2287 {
2288 pImage->cbSize = cbSizeOld; /* Restore */
2289
2290 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("Qed: Resizing the image '%s' failed\n"),
2291 pImage->pszFilename);
2292 }
2293 }
2294 }
2295 /* Same size doesn't change the image at all. */
2296
2297 LogFlowFunc(("returns %Rrc\n", rc));
2298 return rc;
2299}
2300
2301
2302const VDIMAGEBACKEND g_QedBackend =
2303{
2304 /* u32Version */
2305 VD_IMGBACKEND_VERSION,
2306 /* pszBackendName */
2307 "QED",
2308 /* uBackendCaps */
2309 VD_CAP_FILE | VD_CAP_VFS | VD_CAP_CREATE_DYNAMIC | VD_CAP_DIFF | VD_CAP_ASYNC,
2310 /* paFileExtensions */
2311 s_aQedFileExtensions,
2312 /* paConfigInfo */
2313 NULL,
2314 /* pfnProbe */
2315 qedProbe,
2316 /* pfnOpen */
2317 qedOpen,
2318 /* pfnCreate */
2319 qedCreate,
2320 /* pfnRename */
2321 qedRename,
2322 /* pfnClose */
2323 qedClose,
2324 /* pfnRead */
2325 qedRead,
2326 /* pfnWrite */
2327 qedWrite,
2328 /* pfnFlush */
2329 qedFlush,
2330 /* pfnDiscard */
2331 NULL,
2332 /* pfnGetVersion */
2333 qedGetVersion,
2334 /* pfnGetFileSize */
2335 qedGetFileSize,
2336 /* pfnGetPCHSGeometry */
2337 qedGetPCHSGeometry,
2338 /* pfnSetPCHSGeometry */
2339 qedSetPCHSGeometry,
2340 /* pfnGetLCHSGeometry */
2341 qedGetLCHSGeometry,
2342 /* pfnSetLCHSGeometry */
2343 qedSetLCHSGeometry,
2344 /* pfnQueryRegions */
2345 qedQueryRegions,
2346 /* pfnRegionListRelease */
2347 qedRegionListRelease,
2348 /* pfnGetImageFlags */
2349 qedGetImageFlags,
2350 /* pfnGetOpenFlags */
2351 qedGetOpenFlags,
2352 /* pfnSetOpenFlags */
2353 qedSetOpenFlags,
2354 /* pfnGetComment */
2355 qedGetComment,
2356 /* pfnSetComment */
2357 qedSetComment,
2358 /* pfnGetUuid */
2359 qedGetUuid,
2360 /* pfnSetUuid */
2361 qedSetUuid,
2362 /* pfnGetModificationUuid */
2363 qedGetModificationUuid,
2364 /* pfnSetModificationUuid */
2365 qedSetModificationUuid,
2366 /* pfnGetParentUuid */
2367 qedGetParentUuid,
2368 /* pfnSetParentUuid */
2369 qedSetParentUuid,
2370 /* pfnGetParentModificationUuid */
2371 qedGetParentModificationUuid,
2372 /* pfnSetParentModificationUuid */
2373 qedSetParentModificationUuid,
2374 /* pfnDump */
2375 qedDump,
2376 /* pfnGetTimestamp */
2377 NULL,
2378 /* pfnGetParentTimestamp */
2379 NULL,
2380 /* pfnSetParentTimestamp */
2381 NULL,
2382 /* pfnGetParentFilename */
2383 qedGetParentFilename,
2384 /* pfnSetParentFilename */
2385 qedSetParentFilename,
2386 /* pfnComposeLocation */
2387 genericFileComposeLocation,
2388 /* pfnComposeName */
2389 genericFileComposeName,
2390 /* pfnCompact */
2391 NULL,
2392 /* pfnResize */
2393 qedResize,
2394 /* pfnRepair */
2395 NULL,
2396 /* pfnTraverseMetadata */
2397 NULL,
2398 /* u32Version */
2399 VD_IMGBACKEND_VERSION
2400};
Note: See TracBrowser for help on using the repository browser.

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