VirtualBox

source: vbox/trunk/src/VBox/Storage/QCOW.cpp@ 63768

Last change on this file since 63768 was 63741, checked in by vboxsync, 8 years ago

Storage/QED,QCOW: Always write the complete L1 and L2 table when allocating a new cluster instead of just the updated entry

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 91.0 KB
Line 
1/* $Id: QCOW.cpp 63741 2016-09-07 07:53:09Z vboxsync $ */
2/** @file
3 * QCOW - QCOW Disk image.
4 */
5
6/*
7 * Copyright (C) 2011-2016 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18
19/*********************************************************************************************************************************
20* Header Files *
21*********************************************************************************************************************************/
22#define LOG_GROUP LOG_GROUP_VD_QCOW
23#include <VBox/vd-plugin.h>
24#include <VBox/err.h>
25
26#include <VBox/log.h>
27#include <iprt/asm.h>
28#include <iprt/assert.h>
29#include <iprt/string.h>
30#include <iprt/alloc.h>
31#include <iprt/path.h>
32#include <iprt/list.h>
33
34#include "VDBackends.h"
35
36/** @page pg_storage_qcow QCOW Storage Backend
37 * The QCOW backend implements support for the qemu copy on write format (short QCOW).
38 * There is no official specification available but the format is described
39 * at http://people.gnome.org/~markmc/qcow-image-format.html for version 2
40 * and http://people.gnome.org/~markmc/qcow-image-format-version-1.html for version 1.
41 *
42 * Missing things to implement:
43 * - v2 image creation and handling of the reference count table. (Blocker to enable support for V2 images)
44 * - cluster encryption
45 * - cluster compression
46 * - compaction
47 * - resizing
48 */
49
50
51/*********************************************************************************************************************************
52* Structures in a QCOW image, big endian *
53*********************************************************************************************************************************/
54
55#pragma pack(1) /* Completely unnecessary. */
56typedef struct QCowHeader
57{
58 /** Magic value. */
59 uint32_t u32Magic;
60 /** Version of the image. */
61 uint32_t u32Version;
62 /** Version dependent data. */
63 union
64 {
65 /** Version 1. */
66 struct
67 {
68 /** Backing file offset. */
69 uint64_t u64BackingFileOffset;
70 /** Size of the backing file. */
71 uint32_t u32BackingFileSize;
72 /** mtime (Modification time?) - can be ignored. */
73 uint32_t u32MTime;
74 /** Logical size of the image in bytes. */
75 uint64_t u64Size;
76 /** Number of bits in the virtual offset used as a cluster offset. */
77 uint8_t u8ClusterBits;
78 /** Number of bits in the virtual offset used for the L2 index. */
79 uint8_t u8L2Bits;
80 /** Padding because the header is not packed in the original source. */
81 uint16_t u16Padding;
82 /** Used cryptographic method. */
83 uint32_t u32CryptMethod;
84 /** Offset of the L1 table in the image in bytes. */
85 uint64_t u64L1TableOffset;
86 } v1;
87 /** Version 2. */
88 struct
89 {
90 /** Backing file offset. */
91 uint64_t u64BackingFileOffset;
92 /** Size of the backing file. */
93 uint32_t u32BackingFileSize;
94 /** Number of bits in the virtual offset used as a cluster offset. */
95 uint32_t u32ClusterBits;
96 /** Logical size of the image. */
97 uint64_t u64Size;
98 /** Used cryptographic method. */
99 uint32_t u32CryptMethod;
100 /** Size of the L1 table in entries (each 8bytes big). */
101 uint32_t u32L1Size;
102 /** Offset of the L1 table in the image in bytes. */
103 uint64_t u64L1TableOffset;
104 /** Start of the refcount table in the image. */
105 uint64_t u64RefcountTableOffset;
106 /** Size of the refcount table in clusters. */
107 uint32_t u32RefcountTableClusters;
108 /** Number of snapshots in the image. */
109 uint32_t u32NbSnapshots;
110 /** Offset of the first snapshot header in the image. */
111 uint64_t u64SnapshotsOffset;
112 } v2;
113 } Version;
114} QCowHeader;
115#pragma pack()
116/** Pointer to a on disk QCOW header. */
117typedef QCowHeader *PQCowHeader;
118
119/** QCOW magic value. */
120#define QCOW_MAGIC UINT32_C(0x514649fb) /* QFI\0xfb */
121/** Size of the V1 header. */
122#define QCOW_V1_HDR_SIZE (48)
123/** Size of the V2 header. */
124#define QCOW_V2_HDR_SIZE (72)
125
126/** Cluster is compressed flag for QCOW images. */
127#define QCOW_V1_COMPRESSED_FLAG RT_BIT_64(63)
128
129/** Copied flag for QCOW2 images. */
130#define QCOW_V2_COPIED_FLAG RT_BIT_64(63)
131/** Cluster is compressed flag for QCOW2 images. */
132#define QCOW_V2_COMPRESSED_FLAG RT_BIT_64(62)
133
134
135/*********************************************************************************************************************************
136* Constants And Macros, Structures and Typedefs *
137*********************************************************************************************************************************/
138
139/**
140 * QCOW L2 cache entry.
141 */
142typedef struct QCOWL2CACHEENTRY
143{
144 /** List node for the search list. */
145 RTLISTNODE NodeSearch;
146 /** List node for the LRU list. */
147 RTLISTNODE NodeLru;
148 /** Reference counter. */
149 uint32_t cRefs;
150 /** The offset of the L2 table, used as search key. */
151 uint64_t offL2Tbl;
152 /** Pointer to the cached L2 table. */
153 uint64_t *paL2Tbl;
154} QCOWL2CACHEENTRY, *PQCOWL2CACHEENTRY;
155
156/** Maximum amount of memory the cache is allowed to use. */
157#define QCOW_L2_CACHE_MEMORY_MAX (2*_1M)
158
159/** QCOW default cluster size for image version 2. */
160#define QCOW2_CLUSTER_SIZE_DEFAULT (64*_1K)
161/** QCOW default cluster size for image version 1. */
162#define QCOW_CLUSTER_SIZE_DEFAULT (4*_1K)
163/** QCOW default L2 table size in clusters. */
164#define QCOW_L2_CLUSTERS_DEFAULT (1)
165
166/**
167 * QCOW image data structure.
168 */
169typedef struct QCOWIMAGE
170{
171 /** Image name. */
172 const char *pszFilename;
173 /** Storage handle. */
174 PVDIOSTORAGE pStorage;
175
176 /** Pointer to the per-disk VD interface list. */
177 PVDINTERFACE pVDIfsDisk;
178 /** Pointer to the per-image VD interface list. */
179 PVDINTERFACE pVDIfsImage;
180 /** Error interface. */
181 PVDINTERFACEERROR pIfError;
182 /** I/O interface. */
183 PVDINTERFACEIOINT pIfIo;
184
185 /** Open flags passed by VBoxHD layer. */
186 unsigned uOpenFlags;
187 /** Image flags defined during creation or determined during open. */
188 unsigned uImageFlags;
189 /** Total size of the image. */
190 uint64_t cbSize;
191 /** Physical geometry of this image. */
192 VDGEOMETRY PCHSGeometry;
193 /** Logical geometry of this image. */
194 VDGEOMETRY LCHSGeometry;
195
196 /** Image version. */
197 unsigned uVersion;
198 /** MTime field - used only to preserve value in opened images, unmodified otherwise. */
199 uint32_t MTime;
200
201 /** Filename of the backing file if any. */
202 char *pszBackingFilename;
203 /** Offset of the filename in the image. */
204 uint64_t offBackingFilename;
205 /** Size of the backing filename excluding \0. */
206 uint32_t cbBackingFilename;
207
208 /** Next offset of a new cluster, aligned to sector size. */
209 uint64_t offNextCluster;
210 /** Cluster size in bytes. */
211 uint32_t cbCluster;
212 /** Number of entries in the L1 table. */
213 uint32_t cL1TableEntries;
214 /** Size of an L1 rounded to the next cluster size. */
215 uint32_t cbL1Table;
216 /** Pointer to the L1 table. */
217 uint64_t *paL1Table;
218 /** Offset of the L1 table. */
219 uint64_t offL1Table;
220
221 /** Size of the L2 table in bytes. */
222 uint32_t cbL2Table;
223 /** Number of entries in the L2 table. */
224 uint32_t cL2TableEntries;
225 /** Memory occupied by the L2 table cache. */
226 size_t cbL2Cache;
227 /** The sorted L2 entry list used for searching. */
228 RTLISTNODE ListSearch;
229 /** The LRU L2 entry list used for eviction. */
230 RTLISTNODE ListLru;
231
232 /** Offset of the refcount table. */
233 uint64_t offRefcountTable;
234 /** Size of the refcount table in bytes. */
235 uint32_t cbRefcountTable;
236 /** Number of entries in the refcount table. */
237 uint32_t cRefcountTableEntries;
238 /** Pointer to the refcount table. */
239 uint64_t *paRefcountTable;
240
241 /** Offset mask for a cluster. */
242 uint64_t fOffsetMask;
243 /** Number of bits to shift to get the L1 index. */
244 uint32_t cL1Shift;
245 /** L2 table mask to get the L2 index. */
246 uint64_t fL2Mask;
247 /** Number of bits to shift to get the L2 index. */
248 uint32_t cL2Shift;
249
250} QCOWIMAGE, *PQCOWIMAGE;
251
252/**
253 * State of the async cluster allocation.
254 */
255typedef enum QCOWCLUSTERASYNCALLOCSTATE
256{
257 /** Invalid. */
258 QCOWCLUSTERASYNCALLOCSTATE_INVALID = 0,
259 /** L2 table allocation. */
260 QCOWCLUSTERASYNCALLOCSTATE_L2_ALLOC,
261 /** Link L2 table into L1. */
262 QCOWCLUSTERASYNCALLOCSTATE_L2_LINK,
263 /** Allocate user data cluster. */
264 QCOWCLUSTERASYNCALLOCSTATE_USER_ALLOC,
265 /** Link user data cluster. */
266 QCOWCLUSTERASYNCALLOCSTATE_USER_LINK,
267 /** 32bit blowup. */
268 QCOWCLUSTERASYNCALLOCSTATE_32BIT_HACK = 0x7fffffff
269} QCOWCLUSTERASYNCALLOCSTATE, *PQCOWCLUSTERASYNCALLOCSTATE;
270
271/**
272 * Data needed to track async cluster allocation.
273 */
274typedef struct QCOWCLUSTERASYNCALLOC
275{
276 /** The state of the cluster allocation. */
277 QCOWCLUSTERASYNCALLOCSTATE enmAllocState;
278 /** Old image size to rollback in case of an error. */
279 uint64_t offNextClusterOld;
280 /** L1 index to link if any. */
281 uint32_t idxL1;
282 /** L2 index to link, required in any case. */
283 uint32_t idxL2;
284 /** Start offset of the allocated cluster. */
285 uint64_t offClusterNew;
286 /** L2 cache entry if a L2 table is allocated. */
287 PQCOWL2CACHEENTRY pL2Entry;
288 /** Number of bytes to write. */
289 size_t cbToWrite;
290} QCOWCLUSTERASYNCALLOC, *PQCOWCLUSTERASYNCALLOC;
291
292
293/*********************************************************************************************************************************
294* Static Variables *
295*********************************************************************************************************************************/
296
297/** NULL-terminated array of supported file extensions. */
298static const VDFILEEXTENSION s_aQCowFileExtensions[] =
299{
300 {"qcow", VDTYPE_HDD},
301 {"qcow2", VDTYPE_HDD},
302 {NULL, VDTYPE_INVALID}
303};
304
305
306/*********************************************************************************************************************************
307* Internal Functions *
308*********************************************************************************************************************************/
309
310/**
311 * Return power of 2 or 0 if num error.
312 *
313 * @returns The power of 2 or 0 if the given number is not a power of 2.
314 * @param u32 The number.
315 */
316static uint32_t qcowGetPowerOfTwo(uint32_t u32)
317{
318 if (u32 == 0)
319 return 0;
320 uint32_t uPower2 = 0;
321 while ((u32 & 1) == 0)
322 {
323 u32 >>= 1;
324 uPower2++;
325 }
326 return u32 == 1 ? uPower2 : 0;
327}
328
329
330/**
331 * Converts the image header to the host endianess and performs basic checks.
332 *
333 * @returns Whether the given header is valid or not.
334 * @param pHeader Pointer to the header to convert.
335 */
336static bool qcowHdrConvertToHostEndianess(PQCowHeader pHeader)
337{
338 pHeader->u32Magic = RT_BE2H_U32(pHeader->u32Magic);
339 pHeader->u32Version = RT_BE2H_U32(pHeader->u32Version);
340
341 if (pHeader->u32Magic != QCOW_MAGIC)
342 return false;
343
344 if (pHeader->u32Version == 1)
345 {
346 pHeader->Version.v1.u64BackingFileOffset = RT_BE2H_U64(pHeader->Version.v1.u64BackingFileOffset);
347 pHeader->Version.v1.u32BackingFileSize = RT_BE2H_U32(pHeader->Version.v1.u32BackingFileSize);
348 pHeader->Version.v1.u32MTime = RT_BE2H_U32(pHeader->Version.v1.u32MTime);
349 pHeader->Version.v1.u64Size = RT_BE2H_U64(pHeader->Version.v1.u64Size);
350 pHeader->Version.v1.u32CryptMethod = RT_BE2H_U32(pHeader->Version.v1.u32CryptMethod);
351 pHeader->Version.v1.u64L1TableOffset = RT_BE2H_U64(pHeader->Version.v1.u64L1TableOffset);
352 }
353 else if (pHeader->u32Version == 2)
354 {
355 pHeader->Version.v2.u64BackingFileOffset = RT_BE2H_U64(pHeader->Version.v2.u64BackingFileOffset);
356 pHeader->Version.v2.u32BackingFileSize = RT_BE2H_U32(pHeader->Version.v2.u32BackingFileSize);
357 pHeader->Version.v2.u32ClusterBits = RT_BE2H_U32(pHeader->Version.v2.u32ClusterBits);
358 pHeader->Version.v2.u64Size = RT_BE2H_U64(pHeader->Version.v2.u64Size);
359 pHeader->Version.v2.u32CryptMethod = RT_BE2H_U32(pHeader->Version.v2.u32CryptMethod);
360 pHeader->Version.v2.u32L1Size = RT_BE2H_U32(pHeader->Version.v2.u32L1Size);
361 pHeader->Version.v2.u64L1TableOffset = RT_BE2H_U64(pHeader->Version.v2.u64L1TableOffset);
362 pHeader->Version.v2.u64RefcountTableOffset = RT_BE2H_U64(pHeader->Version.v2.u64RefcountTableOffset);
363 pHeader->Version.v2.u32RefcountTableClusters = RT_BE2H_U32(pHeader->Version.v2.u32RefcountTableClusters);
364 pHeader->Version.v2.u32NbSnapshots = RT_BE2H_U32(pHeader->Version.v2.u32NbSnapshots);
365 pHeader->Version.v2.u64SnapshotsOffset = RT_BE2H_U64(pHeader->Version.v2.u64SnapshotsOffset);
366 }
367 else
368 return false;
369
370 return true;
371}
372
373/**
374 * Creates a QCOW header from the given image state.
375 *
376 * @returns nothing.
377 * @param pImage Image instance data.
378 * @param pHeader Pointer to the header to convert.
379 * @param pcbHeader Where to store the size of the header to write.
380 */
381static void qcowHdrConvertFromHostEndianess(PQCOWIMAGE pImage, PQCowHeader pHeader,
382 size_t *pcbHeader)
383{
384 memset(pHeader, 0, sizeof(QCowHeader));
385
386 pHeader->u32Magic = RT_H2BE_U32(QCOW_MAGIC);
387 pHeader->u32Version = RT_H2BE_U32(pImage->uVersion);
388 if (pImage->uVersion == 1)
389 {
390 pHeader->Version.v1.u64BackingFileOffset = RT_H2BE_U64(pImage->offBackingFilename);
391 pHeader->Version.v1.u32BackingFileSize = RT_H2BE_U32(pImage->cbBackingFilename);
392 pHeader->Version.v1.u32MTime = RT_H2BE_U32(pImage->MTime);
393 pHeader->Version.v1.u64Size = RT_H2BE_U64(pImage->cbSize);
394 pHeader->Version.v1.u8ClusterBits = (uint8_t)qcowGetPowerOfTwo(pImage->cbCluster);
395 pHeader->Version.v1.u8L2Bits = (uint8_t)qcowGetPowerOfTwo(pImage->cL2TableEntries);
396 pHeader->Version.v1.u32CryptMethod = RT_H2BE_U32(0);
397 pHeader->Version.v1.u64L1TableOffset = RT_H2BE_U64(pImage->offL1Table);
398 *pcbHeader = QCOW_V1_HDR_SIZE;
399 }
400 else if (pImage->uVersion == 2)
401 {
402 pHeader->Version.v2.u64BackingFileOffset = RT_H2BE_U64(pImage->offBackingFilename);
403 pHeader->Version.v2.u32BackingFileSize = RT_H2BE_U32(pImage->cbBackingFilename);
404 pHeader->Version.v2.u32ClusterBits = RT_H2BE_U32(qcowGetPowerOfTwo(pImage->cbCluster));
405 pHeader->Version.v2.u64Size = RT_H2BE_U64(pImage->cbSize);
406 pHeader->Version.v2.u32CryptMethod = RT_H2BE_U32(0);
407 pHeader->Version.v2.u32L1Size = RT_H2BE_U32(pImage->cL1TableEntries);
408 pHeader->Version.v2.u64L1TableOffset = RT_H2BE_U64(pImage->offL1Table);
409 pHeader->Version.v2.u64RefcountTableOffset = RT_H2BE_U64(pImage->offRefcountTable);
410 pHeader->Version.v2.u32RefcountTableClusters = RT_H2BE_U32(pImage->cbRefcountTable / pImage->cbCluster);
411 pHeader->Version.v2.u32NbSnapshots = RT_H2BE_U32(0);
412 pHeader->Version.v2.u64SnapshotsOffset = RT_H2BE_U64((uint64_t)0);
413 *pcbHeader = QCOW_V2_HDR_SIZE;
414 }
415 else
416 AssertMsgFailed(("Invalid version of the QCOW image format %d\n", pImage->uVersion));
417}
418
419/**
420 * Convert table entries from little endian to host endianess.
421 *
422 * @returns nothing.
423 * @param paTbl Pointer to the table.
424 * @param cEntries Number of entries in the table.
425 */
426static void qcowTableConvertToHostEndianess(uint64_t *paTbl, uint32_t cEntries)
427{
428 while(cEntries-- > 0)
429 {
430 *paTbl = RT_BE2H_U64(*paTbl);
431 paTbl++;
432 }
433}
434
435/**
436 * Convert table entries from host to little endian format.
437 *
438 * @returns nothing.
439 * @param paTblImg Pointer to the table which will store the little endian table.
440 * @param paTbl The source table to convert.
441 * @param cEntries Number of entries in the table.
442 */
443static void qcowTableConvertFromHostEndianess(uint64_t *paTblImg, uint64_t *paTbl,
444 uint32_t cEntries)
445{
446 while(cEntries-- > 0)
447 {
448 *paTblImg = RT_H2BE_U64(*paTbl);
449 paTbl++;
450 paTblImg++;
451 }
452}
453
454#if 0 /* unused */
455/**
456 * Convert refcount table entries from little endian to host endianess.
457 *
458 * @returns nothing.
459 * @param paTbl Pointer to the table.
460 * @param cEntries Number of entries in the table.
461 */
462static void qcowRefcountTableConvertToHostEndianess(uint16_t *paTbl, uint32_t cEntries)
463{
464 while(cEntries-- > 0)
465 {
466 *paTbl = RT_BE2H_U16(*paTbl);
467 paTbl++;
468 }
469}
470#endif
471
472#if 0 /* unused */
473/**
474 * Convert table entries from host to little endian format.
475 *
476 * @returns nothing.
477 * @param paTblImg Pointer to the table which will store the little endian table.
478 * @param paTbl The source table to convert.
479 * @param cEntries Number of entries in the table.
480 */
481static void qcowRefcountTableConvertFromHostEndianess(uint16_t *paTblImg, uint16_t *paTbl,
482 uint32_t cEntries)
483{
484 while(cEntries-- > 0)
485 {
486 *paTblImg = RT_H2BE_U16(*paTbl);
487 paTbl++;
488 paTblImg++;
489 }
490}
491#endif
492
493/**
494 * Creates the L2 table cache.
495 *
496 * @returns VBox status code.
497 * @param pImage The image instance data.
498 */
499static int qcowL2TblCacheCreate(PQCOWIMAGE pImage)
500{
501 pImage->cbL2Cache = 0;
502 RTListInit(&pImage->ListSearch);
503 RTListInit(&pImage->ListLru);
504
505 return VINF_SUCCESS;
506}
507
508/**
509 * Destroys the L2 table cache.
510 *
511 * @returns nothing.
512 * @param pImage The image instance data.
513 */
514static void qcowL2TblCacheDestroy(PQCOWIMAGE pImage)
515{
516 PQCOWL2CACHEENTRY pL2Entry = NULL;
517 PQCOWL2CACHEENTRY pL2Next = NULL;
518
519 RTListForEachSafe(&pImage->ListSearch, pL2Entry, pL2Next, QCOWL2CACHEENTRY, NodeSearch)
520 {
521 Assert(!pL2Entry->cRefs);
522
523 RTListNodeRemove(&pL2Entry->NodeSearch);
524 RTMemPageFree(pL2Entry->paL2Tbl, pImage->cbL2Table);
525 RTMemFree(pL2Entry);
526 }
527
528 pImage->cbL2Cache = 0;
529 RTListInit(&pImage->ListSearch);
530 RTListInit(&pImage->ListLru);
531}
532
533/**
534 * Returns the L2 table matching the given offset or NULL if none could be found.
535 *
536 * @returns Pointer to the L2 table cache entry or NULL.
537 * @param pImage The image instance data.
538 * @param offL2Tbl Offset of the L2 table to search for.
539 */
540static PQCOWL2CACHEENTRY qcowL2TblCacheRetain(PQCOWIMAGE pImage, uint64_t offL2Tbl)
541{
542 PQCOWL2CACHEENTRY pL2Entry = NULL;
543
544 RTListForEach(&pImage->ListSearch, pL2Entry, QCOWL2CACHEENTRY, NodeSearch)
545 {
546 if (pL2Entry->offL2Tbl == offL2Tbl)
547 break;
548 }
549
550 if (!RTListNodeIsDummy(&pImage->ListSearch, pL2Entry, QCOWL2CACHEENTRY, NodeSearch))
551 {
552 /* Update LRU list. */
553 RTListNodeRemove(&pL2Entry->NodeLru);
554 RTListPrepend(&pImage->ListLru, &pL2Entry->NodeLru);
555 pL2Entry->cRefs++;
556 return pL2Entry;
557 }
558 else
559 return NULL;
560}
561
562/**
563 * Releases a L2 table cache entry.
564 *
565 * @returns nothing.
566 * @param pL2Entry The L2 cache entry.
567 */
568static void qcowL2TblCacheEntryRelease(PQCOWL2CACHEENTRY pL2Entry)
569{
570 Assert(pL2Entry->cRefs > 0);
571 pL2Entry->cRefs--;
572}
573
574/**
575 * Allocates a new L2 table from the cache evicting old entries if required.
576 *
577 * @returns Pointer to the L2 cache entry or NULL.
578 * @param pImage The image instance data.
579 */
580static PQCOWL2CACHEENTRY qcowL2TblCacheEntryAlloc(PQCOWIMAGE pImage)
581{
582 PQCOWL2CACHEENTRY pL2Entry = NULL;
583
584 if (pImage->cbL2Cache + pImage->cbL2Table <= QCOW_L2_CACHE_MEMORY_MAX)
585 {
586 /* Add a new entry. */
587 pL2Entry = (PQCOWL2CACHEENTRY)RTMemAllocZ(sizeof(QCOWL2CACHEENTRY));
588 if (pL2Entry)
589 {
590 pL2Entry->paL2Tbl = (uint64_t *)RTMemPageAllocZ(pImage->cbL2Table);
591 if (RT_UNLIKELY(!pL2Entry->paL2Tbl))
592 {
593 RTMemFree(pL2Entry);
594 pL2Entry = NULL;
595 }
596 else
597 {
598 pL2Entry->cRefs = 1;
599 pImage->cbL2Cache += pImage->cbL2Table;
600 }
601 }
602 }
603 else
604 {
605 /* Evict the last not in use entry and use it */
606 Assert(!RTListIsEmpty(&pImage->ListLru));
607
608 RTListForEachReverse(&pImage->ListLru, pL2Entry, QCOWL2CACHEENTRY, NodeLru)
609 {
610 if (!pL2Entry->cRefs)
611 break;
612 }
613
614 if (!RTListNodeIsDummy(&pImage->ListSearch, pL2Entry, QCOWL2CACHEENTRY, NodeSearch))
615 {
616 RTListNodeRemove(&pL2Entry->NodeSearch);
617 RTListNodeRemove(&pL2Entry->NodeLru);
618 pL2Entry->offL2Tbl = 0;
619 pL2Entry->cRefs = 1;
620 }
621 else
622 pL2Entry = NULL;
623 }
624
625 return pL2Entry;
626}
627
628/**
629 * Frees a L2 table cache entry.
630 *
631 * @returns nothing.
632 * @param pImage The image instance data.
633 * @param pL2Entry The L2 cache entry to free.
634 */
635static void qcowL2TblCacheEntryFree(PQCOWIMAGE pImage, PQCOWL2CACHEENTRY pL2Entry)
636{
637 Assert(!pL2Entry->cRefs);
638 RTMemPageFree(pL2Entry->paL2Tbl, pImage->cbL2Table);
639 RTMemFree(pL2Entry);
640
641 pImage->cbL2Cache -= pImage->cbL2Table;
642}
643
644/**
645 * Inserts an entry in the L2 table cache.
646 *
647 * @returns nothing.
648 * @param pImage The image instance data.
649 * @param pL2Entry The L2 cache entry to insert.
650 */
651static void qcowL2TblCacheEntryInsert(PQCOWIMAGE pImage, PQCOWL2CACHEENTRY pL2Entry)
652{
653 PQCOWL2CACHEENTRY pIt = NULL;
654
655 Assert(pL2Entry->offL2Tbl > 0);
656
657 /* Insert at the top of the LRU list. */
658 RTListPrepend(&pImage->ListLru, &pL2Entry->NodeLru);
659
660 if (RTListIsEmpty(&pImage->ListSearch))
661 {
662 RTListAppend(&pImage->ListSearch, &pL2Entry->NodeSearch);
663 }
664 else
665 {
666 /* Insert into search list. */
667 pIt = RTListGetFirst(&pImage->ListSearch, QCOWL2CACHEENTRY, NodeSearch);
668 if (pIt->offL2Tbl > pL2Entry->offL2Tbl)
669 RTListPrepend(&pImage->ListSearch, &pL2Entry->NodeSearch);
670 else
671 {
672 bool fInserted = false;
673
674 RTListForEach(&pImage->ListSearch, pIt, QCOWL2CACHEENTRY, NodeSearch)
675 {
676 Assert(pIt->offL2Tbl != pL2Entry->offL2Tbl);
677 if (pIt->offL2Tbl < pL2Entry->offL2Tbl)
678 {
679 RTListNodeInsertAfter(&pIt->NodeSearch, &pL2Entry->NodeSearch);
680 fInserted = true;
681 break;
682 }
683 }
684 Assert(fInserted);
685 }
686 }
687}
688
689/**
690 * Fetches the L2 from the given offset trying the LRU cache first and
691 * reading it from the image after a cache miss.
692 *
693 * @returns VBox status code.
694 * @param pImage Image instance data.
695 * @param pIoCtx The I/O context.
696 * @param offL2Tbl The offset of the L2 table in the image.
697 * @param ppL2Entry Where to store the L2 table on success.
698 */
699static int qcowL2TblCacheFetch(PQCOWIMAGE pImage, PVDIOCTX pIoCtx, uint64_t offL2Tbl,
700 PQCOWL2CACHEENTRY *ppL2Entry)
701{
702 int rc = VINF_SUCCESS;
703
704 /* Try to fetch the L2 table from the cache first. */
705 PQCOWL2CACHEENTRY pL2Entry = qcowL2TblCacheRetain(pImage, offL2Tbl);
706 if (!pL2Entry)
707 {
708 pL2Entry = qcowL2TblCacheEntryAlloc(pImage);
709
710 if (pL2Entry)
711 {
712 /* Read from the image. */
713 PVDMETAXFER pMetaXfer;
714
715 pL2Entry->offL2Tbl = offL2Tbl;
716 rc = vdIfIoIntFileReadMeta(pImage->pIfIo, pImage->pStorage,
717 offL2Tbl, pL2Entry->paL2Tbl,
718 pImage->cbL2Table, pIoCtx,
719 &pMetaXfer, NULL, NULL);
720 if (RT_SUCCESS(rc))
721 {
722 vdIfIoIntMetaXferRelease(pImage->pIfIo, pMetaXfer);
723#if defined(RT_LITTLE_ENDIAN)
724 qcowTableConvertToHostEndianess(pL2Entry->paL2Tbl, pImage->cL2TableEntries);
725#endif
726 qcowL2TblCacheEntryInsert(pImage, pL2Entry);
727 }
728 else
729 {
730 qcowL2TblCacheEntryRelease(pL2Entry);
731 qcowL2TblCacheEntryFree(pImage, pL2Entry);
732 }
733 }
734 else
735 rc = VERR_NO_MEMORY;
736 }
737
738 if (RT_SUCCESS(rc))
739 *ppL2Entry = pL2Entry;
740
741 return rc;
742}
743
744/**
745 * Sets the L1, L2 and offset bitmasks and L1 and L2 bit shift members.
746 *
747 * @returns nothing.
748 * @param pImage The image instance data.
749 */
750static void qcowTableMasksInit(PQCOWIMAGE pImage)
751{
752 uint32_t cClusterBits, cL2TableBits;
753
754 cClusterBits = qcowGetPowerOfTwo(pImage->cbCluster);
755 cL2TableBits = qcowGetPowerOfTwo(pImage->cL2TableEntries);
756
757 Assert(cClusterBits + cL2TableBits < 64);
758
759 pImage->fOffsetMask = ((uint64_t)pImage->cbCluster - 1);
760 pImage->fL2Mask = ((uint64_t)pImage->cL2TableEntries - 1) << cClusterBits;
761 pImage->cL2Shift = cClusterBits;
762 pImage->cL1Shift = cClusterBits + cL2TableBits;
763}
764
765/**
766 * Converts a given logical offset into the
767 *
768 * @returns nothing.
769 * @param pImage The image instance data.
770 * @param off The logical offset to convert.
771 * @param pidxL1 Where to store the index in the L1 table on success.
772 * @param pidxL2 Where to store the index in the L2 table on success.
773 * @param poffCluster Where to store the offset in the cluster on success.
774 */
775DECLINLINE(void) qcowConvertLogicalOffset(PQCOWIMAGE pImage, uint64_t off, uint32_t *pidxL1,
776 uint32_t *pidxL2, uint32_t *poffCluster)
777{
778 AssertPtr(pidxL1);
779 AssertPtr(pidxL2);
780 AssertPtr(poffCluster);
781
782 *poffCluster = off & pImage->fOffsetMask;
783 *pidxL1 = off >> pImage->cL1Shift;
784 *pidxL2 = (off & pImage->fL2Mask) >> pImage->cL2Shift;
785}
786
787/**
788 * Converts Cluster size to a byte size.
789 *
790 * @returns Number of bytes derived from the given number of clusters.
791 * @param pImage The image instance data.
792 * @param cClusters The clusters to convert.
793 */
794DECLINLINE(uint64_t) qcowCluster2Byte(PQCOWIMAGE pImage, uint64_t cClusters)
795{
796 return cClusters * pImage->cbCluster;
797}
798
799/**
800 * Converts number of bytes to cluster size rounding to the next cluster.
801 *
802 * @returns Number of bytes derived from the given number of clusters.
803 * @param pImage The image instance data.
804 * @param cb Number of bytes to convert.
805 */
806DECLINLINE(uint64_t) qcowByte2Cluster(PQCOWIMAGE pImage, uint64_t cb)
807{
808 return cb / pImage->cbCluster + (cb % pImage->cbCluster ? 1 : 0);
809}
810
811/**
812 * Allocates a new cluster in the image.
813 *
814 * @returns The start offset of the new cluster in the image.
815 * @param pImage The image instance data.
816 * @param cCLusters Number of clusters to allocate.
817 */
818DECLINLINE(uint64_t) qcowClusterAllocate(PQCOWIMAGE pImage, uint32_t cClusters)
819{
820 uint64_t offCluster;
821
822 offCluster = pImage->offNextCluster;
823 pImage->offNextCluster += cClusters*pImage->cbCluster;
824
825 return offCluster;
826}
827
828/**
829 * Returns the real image offset for a given cluster or an error if the cluster is not
830 * yet allocated.
831 *
832 * @returns VBox status code.
833 * VERR_VD_BLOCK_FREE if the cluster is not yet allocated.
834 * @param pImage The image instance data.
835 * @param pIoCtx The I/O context.
836 * @param idxL1 The L1 index.
837 * @param idxL2 The L2 index.
838 * @param offCluster Offset inside the cluster.
839 * @param poffImage Where to store the image offset on success;
840 */
841static int qcowConvertToImageOffset(PQCOWIMAGE pImage, PVDIOCTX pIoCtx,
842 uint32_t idxL1, uint32_t idxL2,
843 uint32_t offCluster, uint64_t *poffImage)
844{
845 int rc = VERR_VD_BLOCK_FREE;
846
847 AssertReturn(idxL1 < pImage->cL1TableEntries, VERR_INVALID_PARAMETER);
848 AssertReturn(idxL2 < pImage->cL2TableEntries, VERR_INVALID_PARAMETER);
849
850 if (pImage->paL1Table[idxL1])
851 {
852 PQCOWL2CACHEENTRY pL2Entry;
853
854 rc = qcowL2TblCacheFetch(pImage, pIoCtx, pImage->paL1Table[idxL1], &pL2Entry);
855 if (RT_SUCCESS(rc))
856 {
857 /* Get real file offset. */
858 if (pL2Entry->paL2Tbl[idxL2])
859 {
860 uint64_t off = pL2Entry->paL2Tbl[idxL2];
861
862 /* Strip flags */
863 if (pImage->uVersion == 2)
864 {
865 if (RT_UNLIKELY(off & QCOW_V2_COMPRESSED_FLAG))
866 rc = VERR_NOT_SUPPORTED;
867 else
868 off &= ~(QCOW_V2_COMPRESSED_FLAG | QCOW_V2_COPIED_FLAG);
869 }
870 else
871 {
872 if (RT_UNLIKELY(off & QCOW_V1_COMPRESSED_FLAG))
873 rc = VERR_NOT_SUPPORTED;
874 else
875 off &= ~QCOW_V1_COMPRESSED_FLAG;
876 }
877
878 *poffImage = off + offCluster;
879 }
880 else
881 rc = VERR_VD_BLOCK_FREE;
882
883 qcowL2TblCacheEntryRelease(pL2Entry);
884 }
885 }
886
887 return rc;
888}
889
890/**
891 * Write the given table to image converting to the image endianess if required.
892 *
893 * @returns VBox status code.
894 * @param pImage The image instance data.
895 * @param pIoCtx The I/O context.
896 * @param offTbl The offset the table should be written to.
897 * @param paTbl The table to write.
898 * @param pfnComplete Callback called when the write completes.
899 * @param pvUser Opaque user data to pass in the completion callback.
900 */
901static int qcowTblWrite(PQCOWIMAGE pImage, PVDIOCTX pIoCtx, uint64_t offTbl, uint64_t *paTbl,
902 size_t cbTbl, unsigned cTblEntries,
903 PFNVDXFERCOMPLETED pfnComplete, void *pvUser)
904{
905 int rc = VINF_SUCCESS;
906
907#if defined(RT_LITTLE_ENDIAN)
908 uint64_t *paTblImg = (uint64_t *)RTMemAllocZ(cbTbl);
909 if (paTblImg)
910 {
911 qcowTableConvertFromHostEndianess(paTblImg, paTbl, cTblEntries);
912 rc = vdIfIoIntFileWriteMeta(pImage->pIfIo, pImage->pStorage,
913 offTbl, paTblImg, cbTbl,
914 pIoCtx, pfnComplete, pvUser);
915 RTMemFree(paTblImg);
916 }
917 else
918 rc = VERR_NO_MEMORY;
919#else
920 /* Write table directly. */
921 RT_NOREF(cTblEntries);
922 rc = vdIfIoIntFileWriteMeta(pImage->pIfIo, pImage->pStorage,
923 offTbl, paTbl, cbTbl, pIoCtx,
924 pfnComplete, pvUser);
925#endif
926
927 return rc;
928}
929
930/**
931 * Internal. Flush image data to disk.
932 */
933static int qcowFlushImage(PQCOWIMAGE pImage)
934{
935 int rc = VINF_SUCCESS;
936
937 if ( pImage->pStorage
938 && !(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
939 && pImage->cbL1Table)
940 {
941 QCowHeader Header;
942
943#if defined(RT_LITTLE_ENDIAN)
944 uint64_t *paL1TblImg = (uint64_t *)RTMemAllocZ(pImage->cbL1Table);
945 if (paL1TblImg)
946 {
947 qcowTableConvertFromHostEndianess(paL1TblImg, pImage->paL1Table,
948 pImage->cL1TableEntries);
949 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pImage->pStorage,
950 pImage->offL1Table, paL1TblImg,
951 pImage->cbL1Table);
952 RTMemFree(paL1TblImg);
953 }
954 else
955 rc = VERR_NO_MEMORY;
956#else
957 /* Write L1 table directly. */
958 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pImage->pStorage, pImage->offL1Table,
959 pImage->paL1Table, pImage->cbL1Table);
960#endif
961 if (RT_SUCCESS(rc))
962 {
963 /* Write header. */
964 size_t cbHeader = 0;
965 qcowHdrConvertFromHostEndianess(pImage, &Header, &cbHeader);
966 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pImage->pStorage, 0, &Header,
967 cbHeader);
968 if (RT_SUCCESS(rc))
969 rc = vdIfIoIntFileFlushSync(pImage->pIfIo, pImage->pStorage);
970 }
971 }
972
973 return rc;
974}
975
976/**
977 * Flush image data to disk - version for async I/O.
978 *
979 * @returns VBox status code.
980 * @param pImage The image instance data.
981 * @param pIoCtx The I/o context
982 */
983static int qcowFlushImageAsync(PQCOWIMAGE pImage, PVDIOCTX pIoCtx)
984{
985 int rc = VINF_SUCCESS;
986
987 if ( pImage->pStorage
988 && !(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
989 {
990 QCowHeader Header;
991
992 rc = qcowTblWrite(pImage, pIoCtx, pImage->offL1Table, pImage->paL1Table,
993 pImage->cbL1Table, pImage->cL1TableEntries, NULL, NULL);
994 if (RT_SUCCESS(rc) || rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
995 {
996 /* Write header. */
997 size_t cbHeader = 0;
998 qcowHdrConvertFromHostEndianess(pImage, &Header, &cbHeader);
999 rc = vdIfIoIntFileWriteMeta(pImage->pIfIo, pImage->pStorage,
1000 0, &Header, cbHeader,
1001 pIoCtx, NULL, NULL);
1002 if (RT_SUCCESS(rc) || rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
1003 rc = vdIfIoIntFileFlush(pImage->pIfIo, pImage->pStorage,
1004 pIoCtx, NULL, NULL);
1005 }
1006 }
1007
1008 return rc;
1009}
1010
1011/**
1012 * Internal. Free all allocated space for representing an image except pImage,
1013 * and optionally delete the image from disk.
1014 */
1015static int qcowFreeImage(PQCOWIMAGE pImage, bool fDelete)
1016{
1017 int rc = VINF_SUCCESS;
1018
1019 /* Freeing a never allocated image (e.g. because the open failed) is
1020 * not signalled as an error. After all nothing bad happens. */
1021 if (pImage)
1022 {
1023 if (pImage->pStorage)
1024 {
1025 /* No point updating the file that is deleted anyway. */
1026 if (!fDelete)
1027 qcowFlushImage(pImage);
1028
1029 rc = vdIfIoIntFileClose(pImage->pIfIo, pImage->pStorage);
1030 pImage->pStorage = NULL;
1031 }
1032
1033 if (pImage->paL1Table)
1034 RTMemFree(pImage->paL1Table);
1035
1036 if (pImage->pszBackingFilename)
1037 {
1038 RTMemFree(pImage->pszBackingFilename);
1039 pImage->pszBackingFilename = NULL;
1040 }
1041
1042 qcowL2TblCacheDestroy(pImage);
1043
1044 if (fDelete && pImage->pszFilename)
1045 vdIfIoIntFileDelete(pImage->pIfIo, pImage->pszFilename);
1046 }
1047
1048 LogFlowFunc(("returns %Rrc\n", rc));
1049 return rc;
1050}
1051
1052/**
1053 * Validates the header.
1054 *
1055 * @returns VBox status code.
1056 * @param pImage Image backend instance data.
1057 * @param pHdr The header to validate.
1058 * @param cbFile The image file size in bytes.
1059 */
1060static int qcowHdrValidate(PQCOWIMAGE pImage, PQCowHeader pHdr, uint64_t cbFile)
1061{
1062 if (pHdr->u32Version == 1)
1063 {
1064 /* Check that the backing filename is contained in the file. */
1065 if (pHdr->Version.v1.u64BackingFileOffset + pHdr->Version.v1.u32BackingFileSize > cbFile)
1066 return vdIfError(pImage->pIfError, VERR_INVALID_STATE, RT_SRC_POS,
1067 N_("QCOW: Backing file offset and size exceed size of image '%s' (%u vs %u)"),
1068 pImage->pszFilename, pHdr->Version.v1.u64BackingFileOffset + pHdr->Version.v1.u32BackingFileSize,
1069 cbFile);
1070
1071 /* Check that the cluster bits indicate at least a 512byte sector size. */
1072 if (RT_BIT_32(pHdr->Version.v1.u8ClusterBits) < 512)
1073 return vdIfError(pImage->pIfError, VERR_INVALID_STATE, RT_SRC_POS,
1074 N_("QCOW: Cluster size is too small for image '%s' (%u vs %u)"),
1075 pImage->pszFilename, RT_BIT_32(pHdr->Version.v1.u8ClusterBits), 512);
1076
1077 /*
1078 * Check for possible overflow when multiplying cluster size and L2 entry count because it is used
1079 * to calculate the number of L1 table entries later on.
1080 */
1081 if (RT_BIT_32(pHdr->Version.v1.u8L2Bits) * RT_BIT_32(pHdr->Version.v1.u8ClusterBits) == 0)
1082 return vdIfError(pImage->pIfError, VERR_INVALID_STATE, RT_SRC_POS,
1083 N_("QCOW: Overflow during L1 table size calculation for image '%s'"),
1084 pImage->pszFilename);
1085 }
1086 else if (pHdr->u32Version == 2)
1087 {
1088 /* Check that the backing filename is contained in the file. */
1089 if (pHdr->Version.v2.u64BackingFileOffset + pHdr->Version.v2.u32BackingFileSize > cbFile)
1090 return vdIfError(pImage->pIfError, VERR_INVALID_STATE, RT_SRC_POS,
1091 N_("QCOW: Backing file offset and size exceed size of image '%s' (%u vs %u)"),
1092 pImage->pszFilename, pHdr->Version.v2.u64BackingFileOffset + pHdr->Version.v2.u32BackingFileSize,
1093 cbFile);
1094
1095 /* Check that the cluster bits indicate at least a 512byte sector size. */
1096 if (RT_BIT_32(pHdr->Version.v2.u32ClusterBits) < 512)
1097 return vdIfError(pImage->pIfError, VERR_INVALID_STATE, RT_SRC_POS,
1098 N_("QCOW: Cluster size is too small for image '%s' (%u vs %u)"),
1099 pImage->pszFilename, RT_BIT_32(pHdr->Version.v2.u32ClusterBits), 512);
1100 }
1101 else
1102 return vdIfError(pImage->pIfError, VERR_NOT_SUPPORTED, RT_SRC_POS,
1103 N_("QCOW: Version %u in image '%s' is not supported"),
1104 pHdr->u32Version, pImage->pszFilename);
1105
1106 return VINF_SUCCESS;
1107}
1108
1109/**
1110 * Internal: Open an image, constructing all necessary data structures.
1111 */
1112static int qcowOpenImage(PQCOWIMAGE pImage, unsigned uOpenFlags)
1113{
1114 int rc;
1115
1116 pImage->uOpenFlags = uOpenFlags;
1117
1118 pImage->pIfError = VDIfErrorGet(pImage->pVDIfsDisk);
1119 pImage->pIfIo = VDIfIoIntGet(pImage->pVDIfsImage);
1120 AssertPtrReturn(pImage->pIfIo, VERR_INVALID_PARAMETER);
1121
1122 rc = qcowL2TblCacheCreate(pImage);
1123 AssertRC(rc);
1124
1125 /*
1126 * Open the image.
1127 */
1128 rc = vdIfIoIntFileOpen(pImage->pIfIo, pImage->pszFilename,
1129 VDOpenFlagsToFileOpenFlags(uOpenFlags,
1130 false /* fCreate */),
1131 &pImage->pStorage);
1132 if (RT_FAILURE(rc))
1133 {
1134 /* Do NOT signal an appropriate error here, as the VD layer has the
1135 * choice of retrying the open if it failed. */
1136 goto out;
1137 }
1138
1139 uint64_t cbFile;
1140 QCowHeader Header;
1141 rc = vdIfIoIntFileGetSize(pImage->pIfIo, pImage->pStorage, &cbFile);
1142 if (RT_FAILURE(rc))
1143 goto out;
1144 if (cbFile > sizeof(Header))
1145 {
1146 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pImage->pStorage, 0, &Header, sizeof(Header));
1147 if ( RT_SUCCESS(rc)
1148 && qcowHdrConvertToHostEndianess(&Header))
1149 {
1150 pImage->offNextCluster = RT_ALIGN_64(cbFile, 512); /* Align image to sector boundary. */
1151 Assert(pImage->offNextCluster >= cbFile);
1152
1153 rc = qcowHdrValidate(pImage, &Header, cbFile);
1154 if (RT_SUCCESS(rc))
1155 {
1156 if (Header.u32Version == 1)
1157 {
1158 if (!Header.Version.v1.u32CryptMethod)
1159 {
1160 pImage->uVersion = 1;
1161 pImage->offBackingFilename = Header.Version.v1.u64BackingFileOffset;
1162 pImage->cbBackingFilename = Header.Version.v1.u32BackingFileSize;
1163 pImage->MTime = Header.Version.v1.u32MTime;
1164 pImage->cbSize = Header.Version.v1.u64Size;
1165 pImage->cbCluster = RT_BIT_32(Header.Version.v1.u8ClusterBits);
1166 pImage->cL2TableEntries = RT_BIT_32(Header.Version.v1.u8L2Bits);
1167 pImage->cbL2Table = RT_ALIGN_64(pImage->cL2TableEntries * sizeof(uint64_t), pImage->cbCluster);
1168 pImage->offL1Table = Header.Version.v1.u64L1TableOffset;
1169 pImage->cL1TableEntries = pImage->cbSize / (pImage->cbCluster * pImage->cL2TableEntries);
1170 if (pImage->cbSize % (pImage->cbCluster * pImage->cL2TableEntries))
1171 pImage->cL1TableEntries++;
1172 }
1173 else
1174 rc = vdIfError(pImage->pIfError, VERR_NOT_SUPPORTED, RT_SRC_POS,
1175 N_("QCow: Encrypted image '%s' is not supported"),
1176 pImage->pszFilename);
1177 }
1178 else if (Header.u32Version == 2)
1179 {
1180 if (Header.Version.v2.u32CryptMethod)
1181 rc = vdIfError(pImage->pIfError, VERR_NOT_SUPPORTED, RT_SRC_POS,
1182 N_("QCow: Encrypted image '%s' is not supported"),
1183 pImage->pszFilename);
1184 else if (Header.Version.v2.u32NbSnapshots)
1185 rc = vdIfError(pImage->pIfError, VERR_NOT_SUPPORTED, RT_SRC_POS,
1186 N_("QCow: Image '%s' contains snapshots which is not supported"),
1187 pImage->pszFilename);
1188 else
1189 {
1190 pImage->uVersion = 2;
1191 pImage->offBackingFilename = Header.Version.v2.u64BackingFileOffset;
1192 pImage->cbBackingFilename = Header.Version.v2.u32BackingFileSize;
1193 pImage->cbSize = Header.Version.v2.u64Size;
1194 pImage->cbCluster = RT_BIT_32(Header.Version.v2.u32ClusterBits);
1195 pImage->cL2TableEntries = pImage->cbCluster / sizeof(uint64_t);
1196 pImage->cbL2Table = pImage->cbCluster;
1197 pImage->offL1Table = Header.Version.v2.u64L1TableOffset;
1198 pImage->cL1TableEntries = Header.Version.v2.u32L1Size;
1199 pImage->offRefcountTable = Header.Version.v2.u64RefcountTableOffset;
1200 pImage->cbRefcountTable = qcowCluster2Byte(pImage, Header.Version.v2.u32RefcountTableClusters);
1201 pImage->cRefcountTableEntries = pImage->cbRefcountTable / sizeof(uint64_t);
1202 }
1203 }
1204 else
1205 rc = vdIfError(pImage->pIfError, VERR_NOT_SUPPORTED, RT_SRC_POS,
1206 N_("QCow: Image '%s' uses version %u which is not supported"),
1207 pImage->pszFilename, Header.u32Version);
1208
1209 pImage->cbL1Table = RT_ALIGN_64(pImage->cL1TableEntries * sizeof(uint64_t), pImage->cbCluster);
1210 if ((uint64_t)pImage->cbL1Table != RT_ALIGN_64(pImage->cL1TableEntries * sizeof(uint64_t), pImage->cbCluster))
1211 rc = vdIfError(pImage->pIfError, VERR_INVALID_STATE, RT_SRC_POS,
1212 N_("QCOW: L1 table size overflow in image '%s'"),
1213 pImage->pszFilename);
1214 }
1215
1216 /** @todo Check that there are no compressed clusters in the image
1217 * (by traversing the L2 tables and checking each offset).
1218 * Refuse to open such images.
1219 */
1220
1221 if ( RT_SUCCESS(rc)
1222 && pImage->cbBackingFilename
1223 && pImage->offBackingFilename)
1224 {
1225 /* Load backing filename from image. */
1226 pImage->pszBackingFilename = (char *)RTMemAllocZ(pImage->cbBackingFilename + 1); /* +1 for \0 terminator. */
1227 if (pImage->pszBackingFilename)
1228 {
1229 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pImage->pStorage,
1230 pImage->offBackingFilename, pImage->pszBackingFilename,
1231 pImage->cbBackingFilename);
1232 }
1233 else
1234 rc = VERR_NO_MEMORY;
1235 }
1236
1237 if ( RT_SUCCESS(rc)
1238 && pImage->cbRefcountTable
1239 && pImage->offRefcountTable)
1240 {
1241 /* Load refcount table. */
1242 Assert(pImage->cRefcountTableEntries);
1243 pImage->paRefcountTable = (uint64_t *)RTMemAllocZ(pImage->cbRefcountTable);
1244 if (RT_LIKELY(pImage->paRefcountTable))
1245 {
1246 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pImage->pStorage,
1247 pImage->offRefcountTable, pImage->paRefcountTable,
1248 pImage->cbRefcountTable);
1249 if (RT_SUCCESS(rc))
1250 qcowTableConvertToHostEndianess(pImage->paRefcountTable,
1251 pImage->cRefcountTableEntries);
1252 else
1253 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS,
1254 N_("QCow: Reading refcount table of image '%s' failed"),
1255 pImage->pszFilename);
1256 }
1257 else
1258 rc = vdIfError(pImage->pIfError, VERR_NO_MEMORY, RT_SRC_POS,
1259 N_("QCow: Allocating memory for refcount table of image '%s' failed"),
1260 pImage->pszFilename);
1261 }
1262
1263 if (RT_SUCCESS(rc))
1264 {
1265 qcowTableMasksInit(pImage);
1266
1267 /* Allocate L1 table. */
1268 pImage->paL1Table = (uint64_t *)RTMemAllocZ(pImage->cbL1Table);
1269 if (pImage->paL1Table)
1270 {
1271 /* Read from the image. */
1272 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pImage->pStorage,
1273 pImage->offL1Table, pImage->paL1Table,
1274 pImage->cbL1Table);
1275 if (RT_SUCCESS(rc))
1276 qcowTableConvertToHostEndianess(pImage->paL1Table, pImage->cL1TableEntries);
1277 else
1278 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS,
1279 N_("QCow: Reading the L1 table for image '%s' failed"),
1280 pImage->pszFilename);
1281 }
1282 else
1283 rc = vdIfError(pImage->pIfError, VERR_NO_MEMORY, RT_SRC_POS,
1284 N_("QCow: Out of memory allocating L1 table for image '%s'"),
1285 pImage->pszFilename);
1286 }
1287 }
1288 else if (RT_SUCCESS(rc))
1289 rc = VERR_VD_GEN_INVALID_HEADER;
1290 }
1291 else
1292 rc = VERR_VD_GEN_INVALID_HEADER;
1293
1294out:
1295 if (RT_FAILURE(rc))
1296 qcowFreeImage(pImage, false);
1297 return rc;
1298}
1299
1300/**
1301 * Internal: Create a qcow image.
1302 */
1303static int qcowCreateImage(PQCOWIMAGE pImage, uint64_t cbSize,
1304 unsigned uImageFlags, const char *pszComment,
1305 PCVDGEOMETRY pPCHSGeometry,
1306 PCVDGEOMETRY pLCHSGeometry, unsigned uOpenFlags,
1307 PFNVDPROGRESS pfnProgress, void *pvUser,
1308 unsigned uPercentStart, unsigned uPercentSpan)
1309{
1310 RT_NOREF1(pszComment);
1311 int rc;
1312 int32_t fOpen;
1313
1314 if (uImageFlags & VD_IMAGE_FLAGS_FIXED)
1315 {
1316 rc = vdIfError(pImage->pIfError, VERR_VD_INVALID_TYPE, RT_SRC_POS, N_("QCow: cannot create fixed image '%s'"), pImage->pszFilename);
1317 goto out;
1318 }
1319
1320 pImage->uOpenFlags = uOpenFlags & ~VD_OPEN_FLAGS_READONLY;
1321 pImage->uImageFlags = uImageFlags;
1322 pImage->PCHSGeometry = *pPCHSGeometry;
1323 pImage->LCHSGeometry = *pLCHSGeometry;
1324
1325 pImage->pIfError = VDIfErrorGet(pImage->pVDIfsDisk);
1326 pImage->pIfIo = VDIfIoIntGet(pImage->pVDIfsImage);
1327 AssertPtrReturn(pImage->pIfIo, VERR_INVALID_PARAMETER);
1328
1329 /* Create image file. */
1330 fOpen = VDOpenFlagsToFileOpenFlags(pImage->uOpenFlags, true /* fCreate */);
1331 rc = vdIfIoIntFileOpen(pImage->pIfIo, pImage->pszFilename, fOpen, &pImage->pStorage);
1332 if (RT_FAILURE(rc))
1333 {
1334 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("QCow: cannot create image '%s'"), pImage->pszFilename);
1335 goto out;
1336 }
1337
1338 /* Init image state. */
1339 pImage->uVersion = 1; /* We create only version 1 images at the moment. */
1340 pImage->cbSize = cbSize;
1341 pImage->cbCluster = QCOW_CLUSTER_SIZE_DEFAULT;
1342 pImage->cbL2Table = qcowCluster2Byte(pImage, QCOW_L2_CLUSTERS_DEFAULT);
1343 pImage->cL2TableEntries = pImage->cbL2Table / sizeof(uint64_t);
1344 pImage->cL1TableEntries = cbSize / (pImage->cbCluster * pImage->cL2TableEntries);
1345 if (cbSize % (pImage->cbCluster * pImage->cL2TableEntries))
1346 pImage->cL1TableEntries++;
1347 pImage->cbL1Table = pImage->cL1TableEntries * sizeof(uint64_t);
1348 pImage->offL1Table = QCOW_V1_HDR_SIZE;
1349 pImage->cbBackingFilename = 0;
1350 pImage->offBackingFilename = 0;
1351 pImage->offNextCluster = RT_ALIGN_64(QCOW_V1_HDR_SIZE + pImage->cbL1Table, pImage->cbCluster);
1352 qcowTableMasksInit(pImage);
1353
1354 /* Init L1 table. */
1355 pImage->paL1Table = (uint64_t *)RTMemAllocZ(pImage->cbL1Table);
1356 if (!pImage->paL1Table)
1357 {
1358 rc = vdIfError(pImage->pIfError, VERR_NO_MEMORY, RT_SRC_POS, N_("QCow: cannot allocate memory for L1 table of image '%s'"),
1359 pImage->pszFilename);
1360 goto out;
1361 }
1362
1363 rc = qcowL2TblCacheCreate(pImage);
1364 if (RT_FAILURE(rc))
1365 {
1366 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("QCow: Failed to create L2 cache for image '%s'"),
1367 pImage->pszFilename);
1368 goto out;
1369 }
1370
1371 if (RT_SUCCESS(rc) && pfnProgress)
1372 pfnProgress(pvUser, uPercentStart + uPercentSpan * 98 / 100);
1373
1374 rc = qcowFlushImage(pImage);
1375 if (RT_SUCCESS(rc))
1376 rc = vdIfIoIntFileSetSize(pImage->pIfIo, pImage->pStorage, pImage->offNextCluster);
1377
1378out:
1379 if (RT_SUCCESS(rc) && pfnProgress)
1380 pfnProgress(pvUser, uPercentStart + uPercentSpan);
1381
1382 if (RT_FAILURE(rc))
1383 qcowFreeImage(pImage, rc != VERR_ALREADY_EXISTS);
1384 return rc;
1385}
1386
1387/**
1388 * Rollback anything done during async cluster allocation.
1389 *
1390 * @returns VBox status code.
1391 * @param pImage The image instance data.
1392 * @param pIoCtx The I/O context.
1393 * @param pClusterAlloc The cluster allocation to rollback.
1394 */
1395static int qcowAsyncClusterAllocRollback(PQCOWIMAGE pImage, PVDIOCTX pIoCtx, PQCOWCLUSTERASYNCALLOC pClusterAlloc)
1396{
1397 RT_NOREF1(pIoCtx);
1398 int rc = VINF_SUCCESS;
1399
1400 switch (pClusterAlloc->enmAllocState)
1401 {
1402 case QCOWCLUSTERASYNCALLOCSTATE_L2_ALLOC:
1403 case QCOWCLUSTERASYNCALLOCSTATE_L2_LINK:
1404 {
1405 /* Revert the L1 table entry */
1406 pImage->paL1Table[pClusterAlloc->idxL1] = 0;
1407
1408 /* Assumption right now is that the L1 table is not modified on storage if the link fails. */
1409 rc = vdIfIoIntFileSetSize(pImage->pIfIo, pImage->pStorage, pClusterAlloc->offNextClusterOld);
1410 qcowL2TblCacheEntryRelease(pClusterAlloc->pL2Entry); /* Release L2 cache entry. */
1411 qcowL2TblCacheEntryFree(pImage, pClusterAlloc->pL2Entry); /* Free it, it is not in the cache yet. */
1412 break;
1413 }
1414 case QCOWCLUSTERASYNCALLOCSTATE_USER_ALLOC:
1415 case QCOWCLUSTERASYNCALLOCSTATE_USER_LINK:
1416 {
1417 /* Assumption right now is that the L2 table is not modified if the link fails. */
1418 pClusterAlloc->pL2Entry->paL2Tbl[pClusterAlloc->idxL2] = 0;
1419 rc = vdIfIoIntFileSetSize(pImage->pIfIo, pImage->pStorage, pClusterAlloc->offNextClusterOld);
1420 qcowL2TblCacheEntryRelease(pClusterAlloc->pL2Entry); /* Release L2 cache entry. */
1421 break;
1422 }
1423 default:
1424 AssertMsgFailed(("Invalid cluster allocation state %d\n", pClusterAlloc->enmAllocState));
1425 rc = VERR_INVALID_STATE;
1426 }
1427
1428 RTMemFree(pClusterAlloc);
1429 return rc;
1430}
1431
1432/**
1433 * Updates the state of the async cluster allocation.
1434 *
1435 * @returns VBox status code.
1436 * @param pBackendData The opaque backend data.
1437 * @param pIoCtx I/O context associated with this request.
1438 * @param pvUser Opaque user data passed during a read/write request.
1439 * @param rcReq Status code for the completed request.
1440 */
1441static DECLCALLBACK(int) qcowAsyncClusterAllocUpdate(void *pBackendData, PVDIOCTX pIoCtx, void *pvUser, int rcReq)
1442{
1443 int rc = VINF_SUCCESS;
1444 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
1445 PQCOWCLUSTERASYNCALLOC pClusterAlloc = (PQCOWCLUSTERASYNCALLOC)pvUser;
1446
1447 if (RT_FAILURE(rcReq))
1448 return qcowAsyncClusterAllocRollback(pImage, pIoCtx, pClusterAlloc);
1449
1450 AssertPtr(pClusterAlloc->pL2Entry);
1451
1452 switch (pClusterAlloc->enmAllocState)
1453 {
1454 case QCOWCLUSTERASYNCALLOCSTATE_L2_ALLOC:
1455 {
1456 /* Update the link in the in memory L1 table now. */
1457 pImage->paL1Table[pClusterAlloc->idxL1] = pClusterAlloc->pL2Entry->offL2Tbl;
1458
1459 /* Update the link in the on disk L1 table now. */
1460 pClusterAlloc->enmAllocState = QCOWCLUSTERASYNCALLOCSTATE_L2_LINK;
1461 rc = qcowTblWrite(pImage, pIoCtx, pImage->offL1Table, pImage->paL1Table,
1462 pImage->cbL1Table, pImage->cL1TableEntries,
1463 qcowAsyncClusterAllocUpdate, pClusterAlloc);
1464 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
1465 break;
1466 else if (RT_FAILURE(rc))
1467 {
1468 /* Rollback. */
1469 qcowAsyncClusterAllocRollback(pImage, pIoCtx, pClusterAlloc);
1470 break;
1471 }
1472 /* Success, fall through. */
1473 }
1474 case QCOWCLUSTERASYNCALLOCSTATE_L2_LINK:
1475 {
1476 /* L2 link updated in L1 , save L2 entry in cache and allocate new user data cluster. */
1477 uint64_t offData = qcowClusterAllocate(pImage, 1);
1478
1479 qcowL2TblCacheEntryInsert(pImage, pClusterAlloc->pL2Entry);
1480
1481 pClusterAlloc->enmAllocState = QCOWCLUSTERASYNCALLOCSTATE_USER_ALLOC;
1482 pClusterAlloc->offNextClusterOld = offData;
1483 pClusterAlloc->offClusterNew = offData;
1484
1485 /* Write data. */
1486 rc = vdIfIoIntFileWriteUser(pImage->pIfIo, pImage->pStorage,
1487 offData, pIoCtx, pClusterAlloc->cbToWrite,
1488 qcowAsyncClusterAllocUpdate, pClusterAlloc);
1489 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
1490 break;
1491 else if (RT_FAILURE(rc))
1492 {
1493 qcowAsyncClusterAllocRollback(pImage, pIoCtx, pClusterAlloc);
1494 RTMemFree(pClusterAlloc);
1495 break;
1496 }
1497 }
1498 case QCOWCLUSTERASYNCALLOCSTATE_USER_ALLOC:
1499 {
1500 pClusterAlloc->enmAllocState = QCOWCLUSTERASYNCALLOCSTATE_USER_LINK;
1501 pClusterAlloc->pL2Entry->paL2Tbl[pClusterAlloc->idxL2] = pClusterAlloc->offClusterNew;
1502
1503 /* Link L2 table and update it. */
1504 rc = qcowTblWrite(pImage, pIoCtx, pImage->paL1Table[pClusterAlloc->idxL1],
1505 pClusterAlloc->pL2Entry->paL2Tbl,
1506 pImage->cbL2Table, pImage->cL2TableEntries,
1507 qcowAsyncClusterAllocUpdate, pClusterAlloc);
1508 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
1509 break;
1510 else if (RT_FAILURE(rc))
1511 {
1512 qcowAsyncClusterAllocRollback(pImage, pIoCtx, pClusterAlloc);
1513 RTMemFree(pClusterAlloc);
1514 break;
1515 }
1516 }
1517 case QCOWCLUSTERASYNCALLOCSTATE_USER_LINK:
1518 {
1519 /* Everything done without errors, signal completion. */
1520 qcowL2TblCacheEntryRelease(pClusterAlloc->pL2Entry);
1521 RTMemFree(pClusterAlloc);
1522 rc = VINF_SUCCESS;
1523 break;
1524 }
1525 default:
1526 AssertMsgFailed(("Invalid async cluster allocation state %d\n",
1527 pClusterAlloc->enmAllocState));
1528 }
1529
1530 return rc;
1531}
1532
1533/** @copydoc VBOXHDDBACKEND::pfnCheckIfValid */
1534static DECLCALLBACK(int) qcowCheckIfValid(const char *pszFilename, PVDINTERFACE pVDIfsDisk,
1535 PVDINTERFACE pVDIfsImage, VDTYPE *penmType)
1536{
1537 RT_NOREF1(pVDIfsDisk);
1538 LogFlowFunc(("pszFilename=\"%s\" pVDIfsDisk=%#p pVDIfsImage=%#p\n", pszFilename, pVDIfsDisk, pVDIfsImage));
1539 PVDIOSTORAGE pStorage = NULL;
1540 uint64_t cbFile;
1541 int rc = VINF_SUCCESS;
1542
1543 /* Get I/O interface. */
1544 PVDINTERFACEIOINT pIfIo = VDIfIoIntGet(pVDIfsImage);
1545 AssertPtrReturn(pIfIo, VERR_INVALID_PARAMETER);
1546
1547 if ( !VALID_PTR(pszFilename)
1548 || !*pszFilename)
1549 {
1550 rc = VERR_INVALID_PARAMETER;
1551 goto out;
1552 }
1553
1554 /*
1555 * Open the file and read the footer.
1556 */
1557 rc = vdIfIoIntFileOpen(pIfIo, pszFilename,
1558 VDOpenFlagsToFileOpenFlags(VD_OPEN_FLAGS_READONLY,
1559 false /* fCreate */),
1560 &pStorage);
1561 if (RT_SUCCESS(rc))
1562 {
1563 rc = vdIfIoIntFileGetSize(pIfIo, pStorage, &cbFile);
1564 if ( RT_SUCCESS(rc)
1565 && cbFile > sizeof(QCowHeader))
1566 {
1567 QCowHeader Header;
1568
1569 rc = vdIfIoIntFileReadSync(pIfIo, pStorage, 0, &Header, sizeof(Header));
1570 if ( RT_SUCCESS(rc)
1571 && qcowHdrConvertToHostEndianess(&Header))
1572 {
1573 *penmType = VDTYPE_HDD;
1574 rc = VINF_SUCCESS;
1575 }
1576 else
1577 rc = VERR_VD_GEN_INVALID_HEADER;
1578 }
1579 else
1580 rc = VERR_VD_GEN_INVALID_HEADER;
1581 }
1582
1583 if (pStorage)
1584 vdIfIoIntFileClose(pIfIo, pStorage);
1585
1586out:
1587 LogFlowFunc(("returns %Rrc\n", rc));
1588 return rc;
1589}
1590
1591/** @copydoc VBOXHDDBACKEND::pfnOpen */
1592static DECLCALLBACK(int) qcowOpen(const char *pszFilename, unsigned uOpenFlags,
1593 PVDINTERFACE pVDIfsDisk, PVDINTERFACE pVDIfsImage,
1594 VDTYPE enmType, void **ppBackendData)
1595{
1596 LogFlowFunc(("pszFilename=\"%s\" uOpenFlags=%#x pVDIfsDisk=%#p pVDIfsImage=%#p enmType=%u ppBackendData=%#p\n", pszFilename, uOpenFlags, pVDIfsDisk, pVDIfsImage, enmType, ppBackendData));
1597 int rc;
1598 PQCOWIMAGE pImage;
1599
1600 NOREF(enmType); /**< @todo r=klaus make use of the type info. */
1601
1602 /* Check open flags. All valid flags are supported. */
1603 if (uOpenFlags & ~VD_OPEN_FLAGS_MASK)
1604 {
1605 rc = VERR_INVALID_PARAMETER;
1606 goto out;
1607 }
1608
1609 /* Check remaining arguments. */
1610 if ( !VALID_PTR(pszFilename)
1611 || !*pszFilename)
1612 {
1613 rc = VERR_INVALID_PARAMETER;
1614 goto out;
1615 }
1616
1617
1618 pImage = (PQCOWIMAGE)RTMemAllocZ(sizeof(QCOWIMAGE));
1619 if (!pImage)
1620 {
1621 rc = VERR_NO_MEMORY;
1622 goto out;
1623 }
1624 pImage->pszFilename = pszFilename;
1625 pImage->pStorage = NULL;
1626 pImage->pVDIfsDisk = pVDIfsDisk;
1627 pImage->pVDIfsImage = pVDIfsImage;
1628
1629 rc = qcowOpenImage(pImage, uOpenFlags);
1630 if (RT_SUCCESS(rc))
1631 *ppBackendData = pImage;
1632 else
1633 RTMemFree(pImage);
1634
1635out:
1636 LogFlowFunc(("returns %Rrc (pBackendData=%#p)\n", rc, *ppBackendData));
1637 return rc;
1638}
1639
1640/** @copydoc VBOXHDDBACKEND::pfnCreate */
1641static DECLCALLBACK(int) qcowCreate(const char *pszFilename, uint64_t cbSize,
1642 unsigned uImageFlags, const char *pszComment,
1643 PCVDGEOMETRY pPCHSGeometry, PCVDGEOMETRY pLCHSGeometry,
1644 PCRTUUID pUuid, unsigned uOpenFlags,
1645 unsigned uPercentStart, unsigned uPercentSpan,
1646 PVDINTERFACE pVDIfsDisk, PVDINTERFACE pVDIfsImage,
1647 PVDINTERFACE pVDIfsOperation, VDTYPE enmType,
1648 void **ppBackendData)
1649{
1650 RT_NOREF1(pUuid);
1651 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=%u ppBackendData=%#p",
1652 pszFilename, cbSize, uImageFlags, pszComment, pPCHSGeometry, pLCHSGeometry, pUuid, uOpenFlags, uPercentStart, uPercentSpan, pVDIfsDisk, pVDIfsImage, pVDIfsOperation, enmType, ppBackendData));
1653 int rc;
1654 PQCOWIMAGE pImage;
1655
1656 PFNVDPROGRESS pfnProgress = NULL;
1657 void *pvUser = NULL;
1658 PVDINTERFACEPROGRESS pIfProgress = VDIfProgressGet(pVDIfsOperation);
1659 if (pIfProgress)
1660 {
1661 pfnProgress = pIfProgress->pfnProgress;
1662 pvUser = pIfProgress->Core.pvUser;
1663 }
1664
1665 /* Check the VD container type. */
1666 if (enmType != VDTYPE_HDD)
1667 {
1668 rc = VERR_VD_INVALID_TYPE;
1669 goto out;
1670 }
1671
1672 /* Check open flags. All valid flags are supported. */
1673 if (uOpenFlags & ~VD_OPEN_FLAGS_MASK)
1674 {
1675 rc = VERR_INVALID_PARAMETER;
1676 goto out;
1677 }
1678
1679 /* Check remaining arguments. */
1680 if ( !VALID_PTR(pszFilename)
1681 || !*pszFilename
1682 || !VALID_PTR(pPCHSGeometry)
1683 || !VALID_PTR(pLCHSGeometry))
1684 {
1685 rc = VERR_INVALID_PARAMETER;
1686 goto out;
1687 }
1688
1689 pImage = (PQCOWIMAGE)RTMemAllocZ(sizeof(QCOWIMAGE));
1690 if (!pImage)
1691 {
1692 rc = VERR_NO_MEMORY;
1693 goto out;
1694 }
1695 pImage->pszFilename = pszFilename;
1696 pImage->pStorage = NULL;
1697 pImage->pVDIfsDisk = pVDIfsDisk;
1698 pImage->pVDIfsImage = pVDIfsImage;
1699
1700 rc = qcowCreateImage(pImage, cbSize, uImageFlags, pszComment,
1701 pPCHSGeometry, pLCHSGeometry, uOpenFlags,
1702 pfnProgress, pvUser, uPercentStart, uPercentSpan);
1703 if (RT_SUCCESS(rc))
1704 {
1705 /* So far the image is opened in read/write mode. Make sure the
1706 * image is opened in read-only mode if the caller requested that. */
1707 if (uOpenFlags & VD_OPEN_FLAGS_READONLY)
1708 {
1709 qcowFreeImage(pImage, false);
1710 rc = qcowOpenImage(pImage, uOpenFlags);
1711 if (RT_FAILURE(rc))
1712 {
1713 RTMemFree(pImage);
1714 goto out;
1715 }
1716 }
1717 *ppBackendData = pImage;
1718 }
1719 else
1720 RTMemFree(pImage);
1721
1722out:
1723 LogFlowFunc(("returns %Rrc (pBackendData=%#p)\n", rc, *ppBackendData));
1724 return rc;
1725}
1726
1727/** @copydoc VBOXHDDBACKEND::pfnRename */
1728static DECLCALLBACK(int) qcowRename(void *pBackendData, const char *pszFilename)
1729{
1730 LogFlowFunc(("pBackendData=%#p pszFilename=%#p\n", pBackendData, pszFilename));
1731 int rc = VINF_SUCCESS;
1732 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
1733
1734 /* Check arguments. */
1735 if ( !pImage
1736 || !pszFilename
1737 || !*pszFilename)
1738 {
1739 rc = VERR_INVALID_PARAMETER;
1740 goto out;
1741 }
1742
1743 /* Close the image. */
1744 rc = qcowFreeImage(pImage, false);
1745 if (RT_FAILURE(rc))
1746 goto out;
1747
1748 /* Rename the file. */
1749 rc = vdIfIoIntFileMove(pImage->pIfIo, pImage->pszFilename, pszFilename, 0);
1750 if (RT_FAILURE(rc))
1751 {
1752 /* The move failed, try to reopen the original image. */
1753 int rc2 = qcowOpenImage(pImage, pImage->uOpenFlags);
1754 if (RT_FAILURE(rc2))
1755 rc = rc2;
1756
1757 goto out;
1758 }
1759
1760 /* Update pImage with the new information. */
1761 pImage->pszFilename = pszFilename;
1762
1763 /* Open the old image with new name. */
1764 rc = qcowOpenImage(pImage, pImage->uOpenFlags);
1765 if (RT_FAILURE(rc))
1766 goto out;
1767
1768out:
1769 LogFlowFunc(("returns %Rrc\n", rc));
1770 return rc;
1771}
1772
1773/** @copydoc VBOXHDDBACKEND::pfnClose */
1774static DECLCALLBACK(int) qcowClose(void *pBackendData, bool fDelete)
1775{
1776 LogFlowFunc(("pBackendData=%#p fDelete=%d\n", pBackendData, fDelete));
1777 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
1778 int rc;
1779
1780 rc = qcowFreeImage(pImage, fDelete);
1781 RTMemFree(pImage);
1782
1783 LogFlowFunc(("returns %Rrc\n", rc));
1784 return rc;
1785}
1786
1787static DECLCALLBACK(int) qcowRead(void *pBackendData, uint64_t uOffset, size_t cbToRead,
1788 PVDIOCTX pIoCtx, size_t *pcbActuallyRead)
1789{
1790 LogFlowFunc(("pBackendData=%#p uOffset=%llu pIoCtx=%#p cbToRead=%zu pcbActuallyRead=%#p\n",
1791 pBackendData, uOffset, pIoCtx, cbToRead, pcbActuallyRead));
1792 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
1793 uint32_t offCluster = 0;
1794 uint32_t idxL1 = 0;
1795 uint32_t idxL2 = 0;
1796 uint64_t offFile = 0;
1797 int rc;
1798
1799 AssertPtr(pImage);
1800 Assert(uOffset % 512 == 0);
1801 Assert(cbToRead % 512 == 0);
1802
1803 if (!VALID_PTR(pIoCtx) || !cbToRead)
1804 {
1805 rc = VERR_INVALID_PARAMETER;
1806 goto out;
1807 }
1808
1809 if ( uOffset + cbToRead > pImage->cbSize
1810 || cbToRead == 0)
1811 {
1812 rc = VERR_INVALID_PARAMETER;
1813 goto out;
1814 }
1815
1816 qcowConvertLogicalOffset(pImage, uOffset, &idxL1, &idxL2, &offCluster);
1817
1818 /* Clip read size to remain in the cluster. */
1819 cbToRead = RT_MIN(cbToRead, pImage->cbCluster - offCluster);
1820
1821 /* Get offset in image. */
1822 rc = qcowConvertToImageOffset(pImage, pIoCtx, idxL1, idxL2, offCluster, &offFile);
1823 if (RT_SUCCESS(rc))
1824 rc = vdIfIoIntFileReadUser(pImage->pIfIo, pImage->pStorage, offFile,
1825 pIoCtx, cbToRead);
1826
1827 if ( ( RT_SUCCESS(rc)
1828 || rc == VERR_VD_BLOCK_FREE
1829 || rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
1830 && pcbActuallyRead)
1831 *pcbActuallyRead = cbToRead;
1832
1833out:
1834 LogFlowFunc(("returns %Rrc\n", rc));
1835 return rc;
1836}
1837
1838static DECLCALLBACK(int) qcowWrite(void *pBackendData, uint64_t uOffset, size_t cbToWrite,
1839 PVDIOCTX pIoCtx, size_t *pcbWriteProcess, size_t *pcbPreRead,
1840 size_t *pcbPostRead, unsigned fWrite)
1841{
1842 LogFlowFunc(("pBackendData=%#p uOffset=%llu pIoCtx=%#p cbToWrite=%zu pcbWriteProcess=%#p pcbPreRead=%#p pcbPostRead=%#p\n",
1843 pBackendData, uOffset, pIoCtx, cbToWrite, pcbWriteProcess, pcbPreRead, pcbPostRead));
1844 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
1845 uint32_t offCluster = 0;
1846 uint32_t idxL1 = 0;
1847 uint32_t idxL2 = 0;
1848 uint64_t offImage = 0;
1849 int rc = VINF_SUCCESS;
1850
1851 AssertPtr(pImage);
1852 Assert(!(uOffset % 512));
1853 Assert(!(cbToWrite % 512));
1854
1855 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
1856 {
1857 rc = VERR_VD_IMAGE_READ_ONLY;
1858 goto out;
1859 }
1860
1861 if (!VALID_PTR(pIoCtx) || !cbToWrite)
1862 {
1863 rc = VERR_INVALID_PARAMETER;
1864 goto out;
1865 }
1866
1867 if ( uOffset + cbToWrite > pImage->cbSize
1868 || cbToWrite == 0)
1869 {
1870 rc = VERR_INVALID_PARAMETER;
1871 goto out;
1872 }
1873
1874 /* Convert offset to L1, L2 index and cluster offset. */
1875 qcowConvertLogicalOffset(pImage, uOffset, &idxL1, &idxL2, &offCluster);
1876
1877 /* Clip write size to remain in the cluster. */
1878 cbToWrite = RT_MIN(cbToWrite, pImage->cbCluster - offCluster);
1879 Assert(!(cbToWrite % 512));
1880
1881 /* Get offset in image. */
1882 rc = qcowConvertToImageOffset(pImage, pIoCtx, idxL1, idxL2, offCluster, &offImage);
1883 if (RT_SUCCESS(rc))
1884 rc = vdIfIoIntFileWriteUser(pImage->pIfIo, pImage->pStorage,
1885 offImage, pIoCtx, cbToWrite, NULL, NULL);
1886 else if (rc == VERR_VD_BLOCK_FREE)
1887 {
1888 if ( cbToWrite == pImage->cbCluster
1889 && !(fWrite & VD_WRITE_NO_ALLOC))
1890 {
1891 PQCOWL2CACHEENTRY pL2Entry = NULL;
1892
1893 /* Full cluster write to previously unallocated cluster.
1894 * Allocate cluster and write data. */
1895 Assert(!offCluster);
1896
1897 do
1898 {
1899 /* Check if we have to allocate a new cluster for L2 tables. */
1900 if (!pImage->paL1Table[idxL1])
1901 {
1902 uint64_t offL2Tbl;
1903 PQCOWCLUSTERASYNCALLOC pL2ClusterAlloc = NULL;
1904
1905 /* Allocate new async cluster allocation state. */
1906 pL2ClusterAlloc = (PQCOWCLUSTERASYNCALLOC)RTMemAllocZ(sizeof(QCOWCLUSTERASYNCALLOC));
1907 if (RT_UNLIKELY(!pL2ClusterAlloc))
1908 {
1909 rc = VERR_NO_MEMORY;
1910 break;
1911 }
1912
1913 pL2Entry = qcowL2TblCacheEntryAlloc(pImage);
1914 if (!pL2Entry)
1915 {
1916 rc = VERR_NO_MEMORY;
1917 RTMemFree(pL2ClusterAlloc);
1918 break;
1919 }
1920
1921 offL2Tbl = qcowClusterAllocate(pImage, qcowByte2Cluster(pImage, pImage->cbL2Table));
1922 pL2Entry->offL2Tbl = offL2Tbl;
1923 memset(pL2Entry->paL2Tbl, 0, pImage->cbL2Table);
1924
1925 pL2ClusterAlloc->enmAllocState = QCOWCLUSTERASYNCALLOCSTATE_L2_ALLOC;
1926 pL2ClusterAlloc->offNextClusterOld = offL2Tbl;
1927 pL2ClusterAlloc->offClusterNew = offL2Tbl;
1928 pL2ClusterAlloc->idxL1 = idxL1;
1929 pL2ClusterAlloc->idxL2 = idxL2;
1930 pL2ClusterAlloc->cbToWrite = cbToWrite;
1931 pL2ClusterAlloc->pL2Entry = pL2Entry;
1932
1933 /*
1934 * Write the L2 table first and link to the L1 table afterwards.
1935 * If something unexpected happens the worst case which can happen
1936 * is a leak of some clusters.
1937 */
1938 rc = vdIfIoIntFileWriteMeta(pImage->pIfIo, pImage->pStorage,
1939 offL2Tbl, pL2Entry->paL2Tbl, pImage->cbL2Table, pIoCtx,
1940 qcowAsyncClusterAllocUpdate, pL2ClusterAlloc);
1941 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
1942 break;
1943 else if (RT_FAILURE(rc))
1944 {
1945 RTMemFree(pL2ClusterAlloc);
1946 qcowL2TblCacheEntryFree(pImage, pL2Entry);
1947 break;
1948 }
1949
1950 rc = qcowAsyncClusterAllocUpdate(pImage, pIoCtx, pL2ClusterAlloc, rc);
1951 }
1952 else
1953 {
1954 rc = qcowL2TblCacheFetch(pImage, pIoCtx, pImage->paL1Table[idxL1],
1955 &pL2Entry);
1956 if (RT_SUCCESS(rc))
1957 {
1958 PQCOWCLUSTERASYNCALLOC pDataClusterAlloc = NULL;
1959
1960 /* Allocate new async cluster allocation state. */
1961 pDataClusterAlloc = (PQCOWCLUSTERASYNCALLOC)RTMemAllocZ(sizeof(QCOWCLUSTERASYNCALLOC));
1962 if (RT_UNLIKELY(!pDataClusterAlloc))
1963 {
1964 rc = VERR_NO_MEMORY;
1965 break;
1966 }
1967
1968 /* Allocate new cluster for the data. */
1969 uint64_t offData = qcowClusterAllocate(pImage, 1);
1970
1971 pDataClusterAlloc->enmAllocState = QCOWCLUSTERASYNCALLOCSTATE_USER_ALLOC;
1972 pDataClusterAlloc->offNextClusterOld = offData;
1973 pDataClusterAlloc->offClusterNew = offData;
1974 pDataClusterAlloc->idxL1 = idxL1;
1975 pDataClusterAlloc->idxL2 = idxL2;
1976 pDataClusterAlloc->cbToWrite = cbToWrite;
1977 pDataClusterAlloc->pL2Entry = pL2Entry;
1978
1979 /* Write data. */
1980 rc = vdIfIoIntFileWriteUser(pImage->pIfIo, pImage->pStorage,
1981 offData, pIoCtx, cbToWrite,
1982 qcowAsyncClusterAllocUpdate, pDataClusterAlloc);
1983 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
1984 break;
1985 else if (RT_FAILURE(rc))
1986 {
1987 RTMemFree(pDataClusterAlloc);
1988 break;
1989 }
1990
1991 rc = qcowAsyncClusterAllocUpdate(pImage, pIoCtx, pDataClusterAlloc, rc);
1992 }
1993 }
1994
1995 } while (0);
1996
1997 *pcbPreRead = 0;
1998 *pcbPostRead = 0;
1999 }
2000 else
2001 {
2002 /* Trying to do a partial write to an unallocated cluster. Don't do
2003 * anything except letting the upper layer know what to do. */
2004 *pcbPreRead = offCluster;
2005 *pcbPostRead = pImage->cbCluster - cbToWrite - *pcbPreRead;
2006 }
2007 }
2008
2009 if (pcbWriteProcess)
2010 *pcbWriteProcess = cbToWrite;
2011
2012
2013out:
2014 LogFlowFunc(("returns %Rrc\n", rc));
2015 return rc;
2016}
2017
2018static DECLCALLBACK(int) qcowFlush(void *pBackendData, PVDIOCTX pIoCtx)
2019{
2020 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
2021 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2022 int rc = VINF_SUCCESS;
2023
2024 Assert(pImage);
2025
2026 if (VALID_PTR(pIoCtx))
2027 rc = qcowFlushImageAsync(pImage, pIoCtx);
2028 else
2029 rc = VERR_INVALID_PARAMETER;
2030
2031 LogFlowFunc(("returns %Rrc\n", rc));
2032 return rc;
2033}
2034
2035/** @copydoc VBOXHDDBACKEND::pfnGetVersion */
2036static DECLCALLBACK(unsigned) qcowGetVersion(void *pBackendData)
2037{
2038 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
2039 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2040
2041 AssertPtr(pImage);
2042
2043 if (pImage)
2044 return pImage->uVersion;
2045 else
2046 return 0;
2047}
2048
2049/** @copydoc VBOXHDDBACKEND::pfnGetSectorSize */
2050static DECLCALLBACK(uint32_t) qcowGetSectorSize(void *pBackendData)
2051{
2052 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
2053 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2054 uint32_t cb = 0;
2055
2056 AssertPtr(pImage);
2057
2058 if (pImage && pImage->pStorage)
2059 cb = 512;
2060
2061 LogFlowFunc(("returns %u\n", cb));
2062 return cb;
2063}
2064
2065/** @copydoc VBOXHDDBACKEND::pfnGetSize */
2066static DECLCALLBACK(uint64_t) qcowGetSize(void *pBackendData)
2067{
2068 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
2069 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2070 uint64_t cb = 0;
2071
2072 AssertPtr(pImage);
2073
2074 if (pImage && pImage->pStorage)
2075 cb = pImage->cbSize;
2076
2077 LogFlowFunc(("returns %llu\n", cb));
2078 return cb;
2079}
2080
2081/** @copydoc VBOXHDDBACKEND::pfnGetFileSize */
2082static DECLCALLBACK(uint64_t) qcowGetFileSize(void *pBackendData)
2083{
2084 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
2085 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2086 uint64_t cb = 0;
2087
2088 AssertPtr(pImage);
2089
2090 if (pImage)
2091 {
2092 uint64_t cbFile;
2093 if (pImage->pStorage)
2094 {
2095 int rc = vdIfIoIntFileGetSize(pImage->pIfIo, pImage->pStorage, &cbFile);
2096 if (RT_SUCCESS(rc))
2097 cb += cbFile;
2098 }
2099 }
2100
2101 LogFlowFunc(("returns %lld\n", cb));
2102 return cb;
2103}
2104
2105/** @copydoc VBOXHDDBACKEND::pfnGetPCHSGeometry */
2106static DECLCALLBACK(int) qcowGetPCHSGeometry(void *pBackendData,
2107 PVDGEOMETRY pPCHSGeometry)
2108{
2109 LogFlowFunc(("pBackendData=%#p pPCHSGeometry=%#p\n", pBackendData, pPCHSGeometry));
2110 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2111 int rc;
2112
2113 AssertPtr(pImage);
2114
2115 if (pImage)
2116 {
2117 if (pImage->PCHSGeometry.cCylinders)
2118 {
2119 *pPCHSGeometry = pImage->PCHSGeometry;
2120 rc = VINF_SUCCESS;
2121 }
2122 else
2123 rc = VERR_VD_GEOMETRY_NOT_SET;
2124 }
2125 else
2126 rc = VERR_VD_NOT_OPENED;
2127
2128 LogFlowFunc(("returns %Rrc (PCHS=%u/%u/%u)\n", rc, pPCHSGeometry->cCylinders, pPCHSGeometry->cHeads, pPCHSGeometry->cSectors));
2129 return rc;
2130}
2131
2132/** @copydoc VBOXHDDBACKEND::pfnSetPCHSGeometry */
2133static DECLCALLBACK(int) qcowSetPCHSGeometry(void *pBackendData,
2134 PCVDGEOMETRY pPCHSGeometry)
2135{
2136 LogFlowFunc(("pBackendData=%#p pPCHSGeometry=%#p PCHS=%u/%u/%u\n", pBackendData, pPCHSGeometry, pPCHSGeometry->cCylinders, pPCHSGeometry->cHeads, pPCHSGeometry->cSectors));
2137 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2138 int rc;
2139
2140 AssertPtr(pImage);
2141
2142 if (pImage)
2143 {
2144 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
2145 {
2146 rc = VERR_VD_IMAGE_READ_ONLY;
2147 goto out;
2148 }
2149
2150 pImage->PCHSGeometry = *pPCHSGeometry;
2151 rc = VINF_SUCCESS;
2152 }
2153 else
2154 rc = VERR_VD_NOT_OPENED;
2155
2156out:
2157 LogFlowFunc(("returns %Rrc\n", rc));
2158 return rc;
2159}
2160
2161/** @copydoc VBOXHDDBACKEND::pfnGetLCHSGeometry */
2162static DECLCALLBACK(int) qcowGetLCHSGeometry(void *pBackendData,
2163 PVDGEOMETRY pLCHSGeometry)
2164{
2165 LogFlowFunc(("pBackendData=%#p pLCHSGeometry=%#p\n", pBackendData, pLCHSGeometry));
2166 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2167 int rc;
2168
2169 AssertPtr(pImage);
2170
2171 if (pImage)
2172 {
2173 if (pImage->LCHSGeometry.cCylinders)
2174 {
2175 *pLCHSGeometry = pImage->LCHSGeometry;
2176 rc = VINF_SUCCESS;
2177 }
2178 else
2179 rc = VERR_VD_GEOMETRY_NOT_SET;
2180 }
2181 else
2182 rc = VERR_VD_NOT_OPENED;
2183
2184 LogFlowFunc(("returns %Rrc (LCHS=%u/%u/%u)\n", rc, pLCHSGeometry->cCylinders, pLCHSGeometry->cHeads, pLCHSGeometry->cSectors));
2185 return rc;
2186}
2187
2188/** @copydoc VBOXHDDBACKEND::pfnSetLCHSGeometry */
2189static DECLCALLBACK(int) qcowSetLCHSGeometry(void *pBackendData,
2190 PCVDGEOMETRY pLCHSGeometry)
2191{
2192 LogFlowFunc(("pBackendData=%#p pLCHSGeometry=%#p LCHS=%u/%u/%u\n", pBackendData, pLCHSGeometry, pLCHSGeometry->cCylinders, pLCHSGeometry->cHeads, pLCHSGeometry->cSectors));
2193 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2194 int rc;
2195
2196 AssertPtr(pImage);
2197
2198 if (pImage)
2199 {
2200 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
2201 {
2202 rc = VERR_VD_IMAGE_READ_ONLY;
2203 goto out;
2204 }
2205
2206 pImage->LCHSGeometry = *pLCHSGeometry;
2207 rc = VINF_SUCCESS;
2208 }
2209 else
2210 rc = VERR_VD_NOT_OPENED;
2211
2212out:
2213 LogFlowFunc(("returns %Rrc\n", rc));
2214 return rc;
2215}
2216
2217/** @copydoc VBOXHDDBACKEND::pfnGetImageFlags */
2218static DECLCALLBACK(unsigned) qcowGetImageFlags(void *pBackendData)
2219{
2220 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
2221 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2222 unsigned uImageFlags;
2223
2224 AssertPtr(pImage);
2225
2226 if (pImage)
2227 uImageFlags = pImage->uImageFlags;
2228 else
2229 uImageFlags = 0;
2230
2231 LogFlowFunc(("returns %#x\n", uImageFlags));
2232 return uImageFlags;
2233}
2234
2235/** @copydoc VBOXHDDBACKEND::pfnGetOpenFlags */
2236static DECLCALLBACK(unsigned) qcowGetOpenFlags(void *pBackendData)
2237{
2238 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
2239 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2240 unsigned uOpenFlags;
2241
2242 AssertPtr(pImage);
2243
2244 if (pImage)
2245 uOpenFlags = pImage->uOpenFlags;
2246 else
2247 uOpenFlags = 0;
2248
2249 LogFlowFunc(("returns %#x\n", uOpenFlags));
2250 return uOpenFlags;
2251}
2252
2253/** @copydoc VBOXHDDBACKEND::pfnSetOpenFlags */
2254static DECLCALLBACK(int) qcowSetOpenFlags(void *pBackendData, unsigned uOpenFlags)
2255{
2256 LogFlowFunc(("pBackendData=%#p\n uOpenFlags=%#x", pBackendData, uOpenFlags));
2257 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2258 int rc;
2259
2260 /* Image must be opened and the new flags must be valid. */
2261 if (!pImage || (uOpenFlags & ~( VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_INFO
2262 | VD_OPEN_FLAGS_ASYNC_IO | VD_OPEN_FLAGS_SKIP_CONSISTENCY_CHECKS)))
2263 {
2264 rc = VERR_INVALID_PARAMETER;
2265 goto out;
2266 }
2267
2268 /* Implement this operation via reopening the image. */
2269 rc = qcowFreeImage(pImage, false);
2270 if (RT_FAILURE(rc))
2271 goto out;
2272 rc = qcowOpenImage(pImage, uOpenFlags);
2273
2274out:
2275 LogFlowFunc(("returns %Rrc\n", rc));
2276 return rc;
2277}
2278
2279/** @copydoc VBOXHDDBACKEND::pfnGetComment */
2280static DECLCALLBACK(int) qcowGetComment(void *pBackendData, char *pszComment, size_t cbComment)
2281{
2282 RT_NOREF2(pszComment, cbComment);
2283 LogFlowFunc(("pBackendData=%#p pszComment=%#p cbComment=%zu\n", pBackendData, pszComment, cbComment));
2284 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2285 int rc;
2286
2287 AssertPtr(pImage);
2288
2289 if (pImage)
2290 rc = VERR_NOT_SUPPORTED;
2291 else
2292 rc = VERR_VD_NOT_OPENED;
2293
2294 LogFlowFunc(("returns %Rrc comment='%s'\n", rc, pszComment));
2295 return rc;
2296}
2297
2298/** @copydoc VBOXHDDBACKEND::pfnSetComment */
2299static DECLCALLBACK(int) qcowSetComment(void *pBackendData, const char *pszComment)
2300{
2301 RT_NOREF1(pszComment);
2302 LogFlowFunc(("pBackendData=%#p pszComment=\"%s\"\n", pBackendData, pszComment));
2303 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2304 int rc;
2305
2306 AssertPtr(pImage);
2307
2308 if (pImage)
2309 {
2310 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
2311 rc = VERR_VD_IMAGE_READ_ONLY;
2312 else
2313 rc = VERR_NOT_SUPPORTED;
2314 }
2315 else
2316 rc = VERR_VD_NOT_OPENED;
2317
2318 LogFlowFunc(("returns %Rrc\n", rc));
2319 return rc;
2320}
2321
2322/** @copydoc VBOXHDDBACKEND::pfnGetUuid */
2323static DECLCALLBACK(int) qcowGetUuid(void *pBackendData, PRTUUID pUuid)
2324{
2325 RT_NOREF1(pUuid);
2326 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
2327 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2328 int rc;
2329
2330 AssertPtr(pImage);
2331
2332 if (pImage)
2333 rc = VERR_NOT_SUPPORTED;
2334 else
2335 rc = VERR_VD_NOT_OPENED;
2336
2337 LogFlowFunc(("returns %Rrc (%RTuuid)\n", rc, pUuid));
2338 return rc;
2339}
2340
2341/** @copydoc VBOXHDDBACKEND::pfnSetUuid */
2342static DECLCALLBACK(int) qcowSetUuid(void *pBackendData, PCRTUUID pUuid)
2343{
2344 RT_NOREF1(pUuid);
2345 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
2346 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2347 int rc;
2348
2349 LogFlowFunc(("%RTuuid\n", pUuid));
2350 AssertPtr(pImage);
2351
2352 if (pImage)
2353 {
2354 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
2355 rc = VERR_NOT_SUPPORTED;
2356 else
2357 rc = VERR_VD_IMAGE_READ_ONLY;
2358 }
2359 else
2360 rc = VERR_VD_NOT_OPENED;
2361
2362 LogFlowFunc(("returns %Rrc\n", rc));
2363 return rc;
2364}
2365
2366/** @copydoc VBOXHDDBACKEND::pfnGetModificationUuid */
2367static DECLCALLBACK(int) qcowGetModificationUuid(void *pBackendData, PRTUUID pUuid)
2368{
2369 RT_NOREF1(pUuid);
2370 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
2371 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2372 int rc;
2373
2374 AssertPtr(pImage);
2375
2376 if (pImage)
2377 rc = VERR_NOT_SUPPORTED;
2378 else
2379 rc = VERR_VD_NOT_OPENED;
2380
2381 LogFlowFunc(("returns %Rrc (%RTuuid)\n", rc, pUuid));
2382 return rc;
2383}
2384
2385/** @copydoc VBOXHDDBACKEND::pfnSetModificationUuid */
2386static DECLCALLBACK(int) qcowSetModificationUuid(void *pBackendData, PCRTUUID pUuid)
2387{
2388 RT_NOREF1(pUuid);
2389 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
2390 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2391 int rc;
2392
2393 AssertPtr(pImage);
2394
2395 if (pImage)
2396 {
2397 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
2398 rc = VERR_NOT_SUPPORTED;
2399 else
2400 rc = VERR_VD_IMAGE_READ_ONLY;
2401 }
2402 else
2403 rc = VERR_VD_NOT_OPENED;
2404
2405 LogFlowFunc(("returns %Rrc\n", rc));
2406 return rc;
2407}
2408
2409/** @copydoc VBOXHDDBACKEND::pfnGetParentUuid */
2410static DECLCALLBACK(int) qcowGetParentUuid(void *pBackendData, PRTUUID pUuid)
2411{
2412 RT_NOREF1(pUuid);
2413 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
2414 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2415 int rc;
2416
2417 AssertPtr(pImage);
2418
2419 if (pImage)
2420 rc = VERR_NOT_SUPPORTED;
2421 else
2422 rc = VERR_VD_NOT_OPENED;
2423
2424 LogFlowFunc(("returns %Rrc (%RTuuid)\n", rc, pUuid));
2425 return rc;
2426}
2427
2428/** @copydoc VBOXHDDBACKEND::pfnSetParentUuid */
2429static DECLCALLBACK(int) qcowSetParentUuid(void *pBackendData, PCRTUUID pUuid)
2430{
2431 RT_NOREF1(pUuid);
2432 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
2433 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2434 int rc;
2435
2436 AssertPtr(pImage);
2437
2438 if (pImage)
2439 {
2440 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
2441 rc = VERR_NOT_SUPPORTED;
2442 else
2443 rc = VERR_VD_IMAGE_READ_ONLY;
2444 }
2445 else
2446 rc = VERR_VD_NOT_OPENED;
2447
2448 LogFlowFunc(("returns %Rrc\n", rc));
2449 return rc;
2450}
2451
2452/** @copydoc VBOXHDDBACKEND::pfnGetParentModificationUuid */
2453static DECLCALLBACK(int) qcowGetParentModificationUuid(void *pBackendData, PRTUUID pUuid)
2454{
2455 RT_NOREF1(pUuid);
2456 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
2457 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2458 int rc;
2459
2460 AssertPtr(pImage);
2461
2462 if (pImage)
2463 rc = VERR_NOT_SUPPORTED;
2464 else
2465 rc = VERR_VD_NOT_OPENED;
2466
2467 LogFlowFunc(("returns %Rrc (%RTuuid)\n", rc, pUuid));
2468 return rc;
2469}
2470
2471/** @copydoc VBOXHDDBACKEND::pfnSetParentModificationUuid */
2472static DECLCALLBACK(int) qcowSetParentModificationUuid(void *pBackendData, PCRTUUID pUuid)
2473{
2474 RT_NOREF1(pUuid);
2475 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
2476 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2477 int rc;
2478
2479 AssertPtr(pImage);
2480
2481 if (pImage)
2482 {
2483 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
2484 rc = VERR_NOT_SUPPORTED;
2485 else
2486 rc = VERR_VD_IMAGE_READ_ONLY;
2487 }
2488 else
2489 rc = VERR_VD_NOT_OPENED;
2490
2491 LogFlowFunc(("returns %Rrc\n", rc));
2492 return rc;
2493}
2494
2495/** @copydoc VBOXHDDBACKEND::pfnDump */
2496static DECLCALLBACK(void) qcowDump(void *pBackendData)
2497{
2498 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2499
2500 AssertPtr(pImage);
2501 if (pImage)
2502 {
2503 vdIfErrorMessage(pImage->pIfError, "Header: Geometry PCHS=%u/%u/%u LCHS=%u/%u/%u cSector=%llu\n",
2504 pImage->PCHSGeometry.cCylinders, pImage->PCHSGeometry.cHeads, pImage->PCHSGeometry.cSectors,
2505 pImage->LCHSGeometry.cCylinders, pImage->LCHSGeometry.cHeads, pImage->LCHSGeometry.cSectors,
2506 pImage->cbSize / 512);
2507 }
2508}
2509
2510/** @copydoc VBOXHDDBACKEND::pfnGetParentFilename */
2511static DECLCALLBACK(int) qcowGetParentFilename(void *pBackendData, char **ppszParentFilename)
2512{
2513 int rc = VINF_SUCCESS;
2514 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2515
2516 AssertPtr(pImage);
2517 if (pImage)
2518 if (pImage->pszBackingFilename)
2519 *ppszParentFilename = RTStrDup(pImage->pszBackingFilename);
2520 else
2521 rc = VERR_NOT_SUPPORTED;
2522 else
2523 rc = VERR_VD_NOT_OPENED;
2524
2525 LogFlowFunc(("returns %Rrc\n", rc));
2526 return rc;
2527}
2528
2529/** @copydoc VBOXHDDBACKEND::pfnSetParentFilename */
2530static DECLCALLBACK(int) qcowSetParentFilename(void *pBackendData, const char *pszParentFilename)
2531{
2532 int rc = VINF_SUCCESS;
2533 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2534
2535 AssertPtr(pImage);
2536 if (pImage)
2537 {
2538 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
2539 rc = VERR_VD_IMAGE_READ_ONLY;
2540 else if ( pImage->pszBackingFilename
2541 && (strlen(pszParentFilename) > pImage->cbBackingFilename))
2542 rc = VERR_NOT_SUPPORTED; /* The new filename is longer than the old one. */
2543 else
2544 {
2545 if (pImage->pszBackingFilename)
2546 RTStrFree(pImage->pszBackingFilename);
2547 pImage->pszBackingFilename = RTStrDup(pszParentFilename);
2548 if (!pImage->pszBackingFilename)
2549 rc = VERR_NO_MEMORY;
2550 else
2551 {
2552 if (!pImage->offBackingFilename)
2553 {
2554 /* Allocate new cluster. */
2555 uint64_t offData = qcowClusterAllocate(pImage, 1);
2556
2557 Assert((offData & UINT32_MAX) == offData);
2558 pImage->offBackingFilename = (uint32_t)offData;
2559 pImage->cbBackingFilename = (uint32_t)strlen(pszParentFilename);
2560 rc = vdIfIoIntFileSetSize(pImage->pIfIo, pImage->pStorage,
2561 offData + pImage->cbCluster);
2562 }
2563
2564 if (RT_SUCCESS(rc))
2565 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pImage->pStorage,
2566 pImage->offBackingFilename,
2567 pImage->pszBackingFilename,
2568 strlen(pImage->pszBackingFilename));
2569 }
2570 }
2571 }
2572 else
2573 rc = VERR_VD_NOT_OPENED;
2574
2575 LogFlowFunc(("returns %Rrc\n", rc));
2576 return rc;
2577}
2578
2579
2580
2581const VBOXHDDBACKEND g_QCowBackend =
2582{
2583 /* pszBackendName */
2584 "QCOW",
2585 /* cbSize */
2586 sizeof(VBOXHDDBACKEND),
2587 /* uBackendCaps */
2588 VD_CAP_FILE | VD_CAP_VFS | VD_CAP_CREATE_DYNAMIC | VD_CAP_DIFF | VD_CAP_ASYNC,
2589 /* paFileExtensions */
2590 s_aQCowFileExtensions,
2591 /* paConfigInfo */
2592 NULL,
2593 /* pfnCheckIfValid */
2594 qcowCheckIfValid,
2595 /* pfnOpen */
2596 qcowOpen,
2597 /* pfnCreate */
2598 qcowCreate,
2599 /* pfnRename */
2600 qcowRename,
2601 /* pfnClose */
2602 qcowClose,
2603 /* pfnRead */
2604 qcowRead,
2605 /* pfnWrite */
2606 qcowWrite,
2607 /* pfnFlush */
2608 qcowFlush,
2609 /* pfnDiscard */
2610 NULL,
2611 /* pfnGetVersion */
2612 qcowGetVersion,
2613 /* pfnGetSectorSize */
2614 qcowGetSectorSize,
2615 /* pfnGetSize */
2616 qcowGetSize,
2617 /* pfnGetFileSize */
2618 qcowGetFileSize,
2619 /* pfnGetPCHSGeometry */
2620 qcowGetPCHSGeometry,
2621 /* pfnSetPCHSGeometry */
2622 qcowSetPCHSGeometry,
2623 /* pfnGetLCHSGeometry */
2624 qcowGetLCHSGeometry,
2625 /* pfnSetLCHSGeometry */
2626 qcowSetLCHSGeometry,
2627 /* pfnGetImageFlags */
2628 qcowGetImageFlags,
2629 /* pfnGetOpenFlags */
2630 qcowGetOpenFlags,
2631 /* pfnSetOpenFlags */
2632 qcowSetOpenFlags,
2633 /* pfnGetComment */
2634 qcowGetComment,
2635 /* pfnSetComment */
2636 qcowSetComment,
2637 /* pfnGetUuid */
2638 qcowGetUuid,
2639 /* pfnSetUuid */
2640 qcowSetUuid,
2641 /* pfnGetModificationUuid */
2642 qcowGetModificationUuid,
2643 /* pfnSetModificationUuid */
2644 qcowSetModificationUuid,
2645 /* pfnGetParentUuid */
2646 qcowGetParentUuid,
2647 /* pfnSetParentUuid */
2648 qcowSetParentUuid,
2649 /* pfnGetParentModificationUuid */
2650 qcowGetParentModificationUuid,
2651 /* pfnSetParentModificationUuid */
2652 qcowSetParentModificationUuid,
2653 /* pfnDump */
2654 qcowDump,
2655 /* pfnGetTimestamp */
2656 NULL,
2657 /* pfnGetParentTimestamp */
2658 NULL,
2659 /* pfnSetParentTimestamp */
2660 NULL,
2661 /* pfnGetParentFilename */
2662 qcowGetParentFilename,
2663 /* pfnSetParentFilename */
2664 qcowSetParentFilename,
2665 /* pfnComposeLocation */
2666 genericFileComposeLocation,
2667 /* pfnComposeName */
2668 genericFileComposeName,
2669 /* pfnCompact */
2670 NULL,
2671 /* pfnResize */
2672 NULL,
2673 /* pfnRepair */
2674 NULL,
2675 /* pfnTraverseMetadata */
2676 NULL
2677};
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