VirtualBox

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

Last change on this file was 103005, checked in by vboxsync, 4 months ago

iprt/asm.h,*: Split out the ASMMem* and related stuff into a separate header, asm-mem.h, so that we can get the RT_ASM_PAGE_SIZE stuff out of the way.

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

© 2023 Oracle
ContactPrivacy policyTerms of Use