VirtualBox

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

Last change on this file since 99880 was 99739, checked in by vboxsync, 19 months ago

*: doxygen corrections (mostly about removing @returns from functions returning void).

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