VirtualBox

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

Last change on this file since 63714 was 63635, checked in by vboxsync, 8 years ago

Storage/QCOW,Parallels: Fix a few possible crashes possible when opening corrupted image files

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 90.4 KB
Line 
1/* $Id: QCOW.cpp 63635 2016-08-25 13:44:59Z 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/**
892 * Internal. Flush image data to disk.
893 */
894static int qcowFlushImage(PQCOWIMAGE pImage)
895{
896 int rc = VINF_SUCCESS;
897
898 if ( pImage->pStorage
899 && !(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
900 && pImage->cbL1Table)
901 {
902 QCowHeader Header;
903
904#if defined(RT_LITTLE_ENDIAN)
905 uint64_t *paL1TblImg = (uint64_t *)RTMemAllocZ(pImage->cbL1Table);
906 if (paL1TblImg)
907 {
908 qcowTableConvertFromHostEndianess(paL1TblImg, pImage->paL1Table,
909 pImage->cL1TableEntries);
910 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pImage->pStorage,
911 pImage->offL1Table, paL1TblImg,
912 pImage->cbL1Table);
913 RTMemFree(paL1TblImg);
914 }
915 else
916 rc = VERR_NO_MEMORY;
917#else
918 /* Write L1 table directly. */
919 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pImage->pStorage, pImage->offL1Table,
920 pImage->paL1Table, pImage->cbL1Table);
921#endif
922 if (RT_SUCCESS(rc))
923 {
924 /* Write header. */
925 size_t cbHeader = 0;
926 qcowHdrConvertFromHostEndianess(pImage, &Header, &cbHeader);
927 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pImage->pStorage, 0, &Header,
928 cbHeader);
929 if (RT_SUCCESS(rc))
930 rc = vdIfIoIntFileFlushSync(pImage->pIfIo, pImage->pStorage);
931 }
932 }
933
934 return rc;
935}
936
937/**
938 * Flush image data to disk - version for async I/O.
939 *
940 * @returns VBox status code.
941 * @param pImage The image instance data.
942 * @param pIoCtx The I/o context
943 */
944static int qcowFlushImageAsync(PQCOWIMAGE pImage, PVDIOCTX pIoCtx)
945{
946 int rc = VINF_SUCCESS;
947
948 if ( pImage->pStorage
949 && !(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
950 {
951 QCowHeader Header;
952
953#if defined(RT_LITTLE_ENDIAN)
954 uint64_t *paL1TblImg = (uint64_t *)RTMemAllocZ(pImage->cbL1Table);
955 if (paL1TblImg)
956 {
957 qcowTableConvertFromHostEndianess(paL1TblImg, pImage->paL1Table,
958 pImage->cL1TableEntries);
959 rc = vdIfIoIntFileWriteMeta(pImage->pIfIo, pImage->pStorage,
960 pImage->offL1Table, paL1TblImg,
961 pImage->cbL1Table, pIoCtx, NULL, NULL);
962 RTMemFree(paL1TblImg);
963 }
964 else
965 rc = VERR_NO_MEMORY;
966#else
967 /* Write L1 table directly. */
968 rc = vdIfIoIntFileWriteMeta(pImage->pIfIo, pImage->pStorage,
969 pImage->offL1Table, pImage->paL1Table,
970 pImage->cbL1Table, pIoCtx, NULL, NULL);
971#endif
972 if (RT_SUCCESS(rc) || rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
973 {
974 /* Write header. */
975 size_t cbHeader = 0;
976 qcowHdrConvertFromHostEndianess(pImage, &Header, &cbHeader);
977 rc = vdIfIoIntFileWriteMeta(pImage->pIfIo, pImage->pStorage,
978 0, &Header, cbHeader,
979 pIoCtx, NULL, NULL);
980 if (RT_SUCCESS(rc) || rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
981 rc = vdIfIoIntFileFlush(pImage->pIfIo, pImage->pStorage,
982 pIoCtx, NULL, NULL);
983 }
984 }
985
986 return rc;
987}
988
989/**
990 * Internal. Free all allocated space for representing an image except pImage,
991 * and optionally delete the image from disk.
992 */
993static int qcowFreeImage(PQCOWIMAGE pImage, bool fDelete)
994{
995 int rc = VINF_SUCCESS;
996
997 /* Freeing a never allocated image (e.g. because the open failed) is
998 * not signalled as an error. After all nothing bad happens. */
999 if (pImage)
1000 {
1001 if (pImage->pStorage)
1002 {
1003 /* No point updating the file that is deleted anyway. */
1004 if (!fDelete)
1005 qcowFlushImage(pImage);
1006
1007 rc = vdIfIoIntFileClose(pImage->pIfIo, pImage->pStorage);
1008 pImage->pStorage = NULL;
1009 }
1010
1011 if (pImage->paL1Table)
1012 RTMemFree(pImage->paL1Table);
1013
1014 if (pImage->pszBackingFilename)
1015 {
1016 RTMemFree(pImage->pszBackingFilename);
1017 pImage->pszBackingFilename = NULL;
1018 }
1019
1020 qcowL2TblCacheDestroy(pImage);
1021
1022 if (fDelete && pImage->pszFilename)
1023 vdIfIoIntFileDelete(pImage->pIfIo, pImage->pszFilename);
1024 }
1025
1026 LogFlowFunc(("returns %Rrc\n", rc));
1027 return rc;
1028}
1029
1030/**
1031 * Validates the header.
1032 *
1033 * @returns VBox status code.
1034 * @param pImage Image backend instance data.
1035 * @param pHdr The header to validate.
1036 * @param cbFile The image file size in bytes.
1037 */
1038static int qcowHdrValidate(PQCOWIMAGE pImage, PQCowHeader pHdr, uint64_t cbFile)
1039{
1040 if (pHdr->u32Version == 1)
1041 {
1042 /* Check that the backing filename is contained in the file. */
1043 if (pHdr->Version.v1.u64BackingFileOffset + pHdr->Version.v1.u32BackingFileSize > cbFile)
1044 return vdIfError(pImage->pIfError, VERR_INVALID_STATE, RT_SRC_POS,
1045 N_("QCOW: Backing file offset and size exceed size of image '%s' (%u vs %u)"),
1046 pImage->pszFilename, pHdr->Version.v1.u64BackingFileOffset + pHdr->Version.v1.u32BackingFileSize,
1047 cbFile);
1048
1049 /* Check that the cluster bits indicate at least a 512byte sector size. */
1050 if (RT_BIT_32(pHdr->Version.v1.u8ClusterBits) < 512)
1051 return vdIfError(pImage->pIfError, VERR_INVALID_STATE, RT_SRC_POS,
1052 N_("QCOW: Cluster size is too small for image '%s' (%u vs %u)"),
1053 pImage->pszFilename, RT_BIT_32(pHdr->Version.v1.u8ClusterBits), 512);
1054
1055 /*
1056 * Check for possible overflow when multiplying cluster size and L2 entry count because it is used
1057 * to calculate the number of L1 table entries later on.
1058 */
1059 if (RT_BIT_32(pHdr->Version.v1.u8L2Bits) * RT_BIT_32(pHdr->Version.v1.u8ClusterBits) == 0)
1060 return vdIfError(pImage->pIfError, VERR_INVALID_STATE, RT_SRC_POS,
1061 N_("QCOW: Overflow during L1 table size calculation for image '%s'"),
1062 pImage->pszFilename);
1063 }
1064 else if (pHdr->u32Version == 2)
1065 {
1066 /* Check that the backing filename is contained in the file. */
1067 if (pHdr->Version.v2.u64BackingFileOffset + pHdr->Version.v2.u32BackingFileSize > cbFile)
1068 return vdIfError(pImage->pIfError, VERR_INVALID_STATE, RT_SRC_POS,
1069 N_("QCOW: Backing file offset and size exceed size of image '%s' (%u vs %u)"),
1070 pImage->pszFilename, pHdr->Version.v2.u64BackingFileOffset + pHdr->Version.v2.u32BackingFileSize,
1071 cbFile);
1072
1073 /* Check that the cluster bits indicate at least a 512byte sector size. */
1074 if (RT_BIT_32(pHdr->Version.v2.u32ClusterBits) < 512)
1075 return vdIfError(pImage->pIfError, VERR_INVALID_STATE, RT_SRC_POS,
1076 N_("QCOW: Cluster size is too small for image '%s' (%u vs %u)"),
1077 pImage->pszFilename, RT_BIT_32(pHdr->Version.v2.u32ClusterBits), 512);
1078 }
1079 else
1080 return vdIfError(pImage->pIfError, VERR_NOT_SUPPORTED, RT_SRC_POS,
1081 N_("QCOW: Version %u in image '%s' is not supported"),
1082 pHdr->u32Version, pImage->pszFilename);
1083
1084 return VINF_SUCCESS;
1085}
1086
1087/**
1088 * Internal: Open an image, constructing all necessary data structures.
1089 */
1090static int qcowOpenImage(PQCOWIMAGE pImage, unsigned uOpenFlags)
1091{
1092 int rc;
1093
1094 pImage->uOpenFlags = uOpenFlags;
1095
1096 pImage->pIfError = VDIfErrorGet(pImage->pVDIfsDisk);
1097 pImage->pIfIo = VDIfIoIntGet(pImage->pVDIfsImage);
1098 AssertPtrReturn(pImage->pIfIo, VERR_INVALID_PARAMETER);
1099
1100 rc = qcowL2TblCacheCreate(pImage);
1101 AssertRC(rc);
1102
1103 /*
1104 * Open the image.
1105 */
1106 rc = vdIfIoIntFileOpen(pImage->pIfIo, pImage->pszFilename,
1107 VDOpenFlagsToFileOpenFlags(uOpenFlags,
1108 false /* fCreate */),
1109 &pImage->pStorage);
1110 if (RT_FAILURE(rc))
1111 {
1112 /* Do NOT signal an appropriate error here, as the VD layer has the
1113 * choice of retrying the open if it failed. */
1114 goto out;
1115 }
1116
1117 uint64_t cbFile;
1118 QCowHeader Header;
1119 rc = vdIfIoIntFileGetSize(pImage->pIfIo, pImage->pStorage, &cbFile);
1120 if (RT_FAILURE(rc))
1121 goto out;
1122 if (cbFile > sizeof(Header))
1123 {
1124 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pImage->pStorage, 0, &Header, sizeof(Header));
1125 if ( RT_SUCCESS(rc)
1126 && qcowHdrConvertToHostEndianess(&Header))
1127 {
1128 pImage->offNextCluster = RT_ALIGN_64(cbFile, 512); /* Align image to sector boundary. */
1129 Assert(pImage->offNextCluster >= cbFile);
1130
1131 rc = qcowHdrValidate(pImage, &Header, cbFile);
1132 if (RT_SUCCESS(rc))
1133 {
1134 if (Header.u32Version == 1)
1135 {
1136 if (!Header.Version.v1.u32CryptMethod)
1137 {
1138 pImage->uVersion = 1;
1139 pImage->offBackingFilename = Header.Version.v1.u64BackingFileOffset;
1140 pImage->cbBackingFilename = Header.Version.v1.u32BackingFileSize;
1141 pImage->MTime = Header.Version.v1.u32MTime;
1142 pImage->cbSize = Header.Version.v1.u64Size;
1143 pImage->cbCluster = RT_BIT_32(Header.Version.v1.u8ClusterBits);
1144 pImage->cL2TableEntries = RT_BIT_32(Header.Version.v1.u8L2Bits);
1145 pImage->cbL2Table = RT_ALIGN_64(pImage->cL2TableEntries * sizeof(uint64_t), pImage->cbCluster);
1146 pImage->offL1Table = Header.Version.v1.u64L1TableOffset;
1147 pImage->cL1TableEntries = pImage->cbSize / (pImage->cbCluster * pImage->cL2TableEntries);
1148 if (pImage->cbSize % (pImage->cbCluster * pImage->cL2TableEntries))
1149 pImage->cL1TableEntries++;
1150 }
1151 else
1152 rc = vdIfError(pImage->pIfError, VERR_NOT_SUPPORTED, RT_SRC_POS,
1153 N_("QCow: Encrypted image '%s' is not supported"),
1154 pImage->pszFilename);
1155 }
1156 else if (Header.u32Version == 2)
1157 {
1158 if (Header.Version.v2.u32CryptMethod)
1159 rc = vdIfError(pImage->pIfError, VERR_NOT_SUPPORTED, RT_SRC_POS,
1160 N_("QCow: Encrypted image '%s' is not supported"),
1161 pImage->pszFilename);
1162 else if (Header.Version.v2.u32NbSnapshots)
1163 rc = vdIfError(pImage->pIfError, VERR_NOT_SUPPORTED, RT_SRC_POS,
1164 N_("QCow: Image '%s' contains snapshots which is not supported"),
1165 pImage->pszFilename);
1166 else
1167 {
1168 pImage->uVersion = 2;
1169 pImage->offBackingFilename = Header.Version.v2.u64BackingFileOffset;
1170 pImage->cbBackingFilename = Header.Version.v2.u32BackingFileSize;
1171 pImage->cbSize = Header.Version.v2.u64Size;
1172 pImage->cbCluster = RT_BIT_32(Header.Version.v2.u32ClusterBits);
1173 pImage->cL2TableEntries = pImage->cbCluster / sizeof(uint64_t);
1174 pImage->cbL2Table = pImage->cbCluster;
1175 pImage->offL1Table = Header.Version.v2.u64L1TableOffset;
1176 pImage->cL1TableEntries = Header.Version.v2.u32L1Size;
1177 pImage->offRefcountTable = Header.Version.v2.u64RefcountTableOffset;
1178 pImage->cbRefcountTable = qcowCluster2Byte(pImage, Header.Version.v2.u32RefcountTableClusters);
1179 pImage->cRefcountTableEntries = pImage->cbRefcountTable / sizeof(uint64_t);
1180 }
1181 }
1182 else
1183 rc = vdIfError(pImage->pIfError, VERR_NOT_SUPPORTED, RT_SRC_POS,
1184 N_("QCow: Image '%s' uses version %u which is not supported"),
1185 pImage->pszFilename, Header.u32Version);
1186
1187 pImage->cbL1Table = RT_ALIGN_64(pImage->cL1TableEntries * sizeof(uint64_t), pImage->cbCluster);
1188 if ((uint64_t)pImage->cbL1Table != RT_ALIGN_64(pImage->cL1TableEntries * sizeof(uint64_t), pImage->cbCluster))
1189 rc = vdIfError(pImage->pIfError, VERR_INVALID_STATE, RT_SRC_POS,
1190 N_("QCOW: L1 table size overflow in image '%s'"),
1191 pImage->pszFilename);
1192 }
1193
1194 /** @todo Check that there are no compressed clusters in the image
1195 * (by traversing the L2 tables and checking each offset).
1196 * Refuse to open such images.
1197 */
1198
1199 if ( RT_SUCCESS(rc)
1200 && pImage->cbBackingFilename
1201 && pImage->offBackingFilename)
1202 {
1203 /* Load backing filename from image. */
1204 pImage->pszBackingFilename = (char *)RTMemAllocZ(pImage->cbBackingFilename + 1); /* +1 for \0 terminator. */
1205 if (pImage->pszBackingFilename)
1206 {
1207 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pImage->pStorage,
1208 pImage->offBackingFilename, pImage->pszBackingFilename,
1209 pImage->cbBackingFilename);
1210 }
1211 else
1212 rc = VERR_NO_MEMORY;
1213 }
1214
1215 if ( RT_SUCCESS(rc)
1216 && pImage->cbRefcountTable
1217 && pImage->offRefcountTable)
1218 {
1219 /* Load refcount table. */
1220 Assert(pImage->cRefcountTableEntries);
1221 pImage->paRefcountTable = (uint64_t *)RTMemAllocZ(pImage->cbRefcountTable);
1222 if (RT_LIKELY(pImage->paRefcountTable))
1223 {
1224 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pImage->pStorage,
1225 pImage->offRefcountTable, pImage->paRefcountTable,
1226 pImage->cbRefcountTable);
1227 if (RT_SUCCESS(rc))
1228 qcowTableConvertToHostEndianess(pImage->paRefcountTable,
1229 pImage->cRefcountTableEntries);
1230 else
1231 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS,
1232 N_("QCow: Reading refcount table of image '%s' failed"),
1233 pImage->pszFilename);
1234 }
1235 else
1236 rc = vdIfError(pImage->pIfError, VERR_NO_MEMORY, RT_SRC_POS,
1237 N_("QCow: Allocating memory for refcount table of image '%s' failed"),
1238 pImage->pszFilename);
1239 }
1240
1241 if (RT_SUCCESS(rc))
1242 {
1243 qcowTableMasksInit(pImage);
1244
1245 /* Allocate L1 table. */
1246 pImage->paL1Table = (uint64_t *)RTMemAllocZ(pImage->cbL1Table);
1247 if (pImage->paL1Table)
1248 {
1249 /* Read from the image. */
1250 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pImage->pStorage,
1251 pImage->offL1Table, pImage->paL1Table,
1252 pImage->cbL1Table);
1253 if (RT_SUCCESS(rc))
1254 qcowTableConvertToHostEndianess(pImage->paL1Table, pImage->cL1TableEntries);
1255 else
1256 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS,
1257 N_("QCow: Reading the L1 table for image '%s' failed"),
1258 pImage->pszFilename);
1259 }
1260 else
1261 rc = vdIfError(pImage->pIfError, VERR_NO_MEMORY, RT_SRC_POS,
1262 N_("QCow: Out of memory allocating L1 table for image '%s'"),
1263 pImage->pszFilename);
1264 }
1265 }
1266 else if (RT_SUCCESS(rc))
1267 rc = VERR_VD_GEN_INVALID_HEADER;
1268 }
1269 else
1270 rc = VERR_VD_GEN_INVALID_HEADER;
1271
1272out:
1273 if (RT_FAILURE(rc))
1274 qcowFreeImage(pImage, false);
1275 return rc;
1276}
1277
1278/**
1279 * Internal: Create a qcow image.
1280 */
1281static int qcowCreateImage(PQCOWIMAGE pImage, uint64_t cbSize,
1282 unsigned uImageFlags, const char *pszComment,
1283 PCVDGEOMETRY pPCHSGeometry,
1284 PCVDGEOMETRY pLCHSGeometry, unsigned uOpenFlags,
1285 PFNVDPROGRESS pfnProgress, void *pvUser,
1286 unsigned uPercentStart, unsigned uPercentSpan)
1287{
1288 RT_NOREF1(pszComment);
1289 int rc;
1290 int32_t fOpen;
1291
1292 if (uImageFlags & VD_IMAGE_FLAGS_FIXED)
1293 {
1294 rc = vdIfError(pImage->pIfError, VERR_VD_INVALID_TYPE, RT_SRC_POS, N_("QCow: cannot create fixed image '%s'"), pImage->pszFilename);
1295 goto out;
1296 }
1297
1298 pImage->uOpenFlags = uOpenFlags & ~VD_OPEN_FLAGS_READONLY;
1299 pImage->uImageFlags = uImageFlags;
1300 pImage->PCHSGeometry = *pPCHSGeometry;
1301 pImage->LCHSGeometry = *pLCHSGeometry;
1302
1303 pImage->pIfError = VDIfErrorGet(pImage->pVDIfsDisk);
1304 pImage->pIfIo = VDIfIoIntGet(pImage->pVDIfsImage);
1305 AssertPtrReturn(pImage->pIfIo, VERR_INVALID_PARAMETER);
1306
1307 /* Create image file. */
1308 fOpen = VDOpenFlagsToFileOpenFlags(pImage->uOpenFlags, true /* fCreate */);
1309 rc = vdIfIoIntFileOpen(pImage->pIfIo, pImage->pszFilename, fOpen, &pImage->pStorage);
1310 if (RT_FAILURE(rc))
1311 {
1312 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("QCow: cannot create image '%s'"), pImage->pszFilename);
1313 goto out;
1314 }
1315
1316 /* Init image state. */
1317 pImage->uVersion = 1; /* We create only version 1 images at the moment. */
1318 pImage->cbSize = cbSize;
1319 pImage->cbCluster = QCOW_CLUSTER_SIZE_DEFAULT;
1320 pImage->cbL2Table = qcowCluster2Byte(pImage, QCOW_L2_CLUSTERS_DEFAULT);
1321 pImage->cL2TableEntries = pImage->cbL2Table / sizeof(uint64_t);
1322 pImage->cL1TableEntries = cbSize / (pImage->cbCluster * pImage->cL2TableEntries);
1323 if (cbSize % (pImage->cbCluster * pImage->cL2TableEntries))
1324 pImage->cL1TableEntries++;
1325 pImage->cbL1Table = pImage->cL1TableEntries * sizeof(uint64_t);
1326 pImage->offL1Table = QCOW_V1_HDR_SIZE;
1327 pImage->cbBackingFilename = 0;
1328 pImage->offBackingFilename = 0;
1329 pImage->offNextCluster = RT_ALIGN_64(QCOW_V1_HDR_SIZE + pImage->cbL1Table, pImage->cbCluster);
1330 qcowTableMasksInit(pImage);
1331
1332 /* Init L1 table. */
1333 pImage->paL1Table = (uint64_t *)RTMemAllocZ(pImage->cbL1Table);
1334 if (!pImage->paL1Table)
1335 {
1336 rc = vdIfError(pImage->pIfError, VERR_NO_MEMORY, RT_SRC_POS, N_("QCow: cannot allocate memory for L1 table of image '%s'"),
1337 pImage->pszFilename);
1338 goto out;
1339 }
1340
1341 rc = qcowL2TblCacheCreate(pImage);
1342 if (RT_FAILURE(rc))
1343 {
1344 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("QCow: Failed to create L2 cache for image '%s'"),
1345 pImage->pszFilename);
1346 goto out;
1347 }
1348
1349 if (RT_SUCCESS(rc) && pfnProgress)
1350 pfnProgress(pvUser, uPercentStart + uPercentSpan * 98 / 100);
1351
1352 rc = qcowFlushImage(pImage);
1353 if (RT_SUCCESS(rc))
1354 rc = vdIfIoIntFileSetSize(pImage->pIfIo, pImage->pStorage, pImage->offNextCluster);
1355
1356out:
1357 if (RT_SUCCESS(rc) && pfnProgress)
1358 pfnProgress(pvUser, uPercentStart + uPercentSpan);
1359
1360 if (RT_FAILURE(rc))
1361 qcowFreeImage(pImage, rc != VERR_ALREADY_EXISTS);
1362 return rc;
1363}
1364
1365/**
1366 * Rollback anything done during async cluster allocation.
1367 *
1368 * @returns VBox status code.
1369 * @param pImage The image instance data.
1370 * @param pIoCtx The I/O context.
1371 * @param pClusterAlloc The cluster allocation to rollback.
1372 */
1373static int qcowAsyncClusterAllocRollback(PQCOWIMAGE pImage, PVDIOCTX pIoCtx, PQCOWCLUSTERASYNCALLOC pClusterAlloc)
1374{
1375 RT_NOREF1(pIoCtx);
1376 int rc = VINF_SUCCESS;
1377
1378 switch (pClusterAlloc->enmAllocState)
1379 {
1380 case QCOWCLUSTERASYNCALLOCSTATE_L2_ALLOC:
1381 case QCOWCLUSTERASYNCALLOCSTATE_L2_LINK:
1382 {
1383 /* Assumption right now is that the L1 table is not modified if the link fails. */
1384 rc = vdIfIoIntFileSetSize(pImage->pIfIo, pImage->pStorage, pClusterAlloc->offNextClusterOld);
1385 qcowL2TblCacheEntryRelease(pClusterAlloc->pL2Entry); /* Release L2 cache entry. */
1386 qcowL2TblCacheEntryFree(pImage, pClusterAlloc->pL2Entry); /* Free it, it is not in the cache yet. */
1387 break;
1388 }
1389 case QCOWCLUSTERASYNCALLOCSTATE_USER_ALLOC:
1390 case QCOWCLUSTERASYNCALLOCSTATE_USER_LINK:
1391 {
1392 /* Assumption right now is that the L2 table is not modified if the link fails. */
1393 rc = vdIfIoIntFileSetSize(pImage->pIfIo, pImage->pStorage, pClusterAlloc->offNextClusterOld);
1394 qcowL2TblCacheEntryRelease(pClusterAlloc->pL2Entry); /* Release L2 cache entry. */
1395 break;
1396 }
1397 default:
1398 AssertMsgFailed(("Invalid cluster allocation state %d\n", pClusterAlloc->enmAllocState));
1399 rc = VERR_INVALID_STATE;
1400 }
1401
1402 RTMemFree(pClusterAlloc);
1403 return rc;
1404}
1405
1406/**
1407 * Updates the state of the async cluster allocation.
1408 *
1409 * @returns VBox status code.
1410 * @param pBackendData The opaque backend data.
1411 * @param pIoCtx I/O context associated with this request.
1412 * @param pvUser Opaque user data passed during a read/write request.
1413 * @param rcReq Status code for the completed request.
1414 */
1415static DECLCALLBACK(int) qcowAsyncClusterAllocUpdate(void *pBackendData, PVDIOCTX pIoCtx, void *pvUser, int rcReq)
1416{
1417 int rc = VINF_SUCCESS;
1418 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
1419 PQCOWCLUSTERASYNCALLOC pClusterAlloc = (PQCOWCLUSTERASYNCALLOC)pvUser;
1420
1421 if (RT_FAILURE(rcReq))
1422 return qcowAsyncClusterAllocRollback(pImage, pIoCtx, pClusterAlloc);
1423
1424 AssertPtr(pClusterAlloc->pL2Entry);
1425
1426 switch (pClusterAlloc->enmAllocState)
1427 {
1428 case QCOWCLUSTERASYNCALLOCSTATE_L2_ALLOC:
1429 {
1430 uint64_t offUpdateLe = RT_H2BE_U64(pClusterAlloc->pL2Entry->offL2Tbl);
1431
1432 /* Update the link in the on disk L1 table now. */
1433 pClusterAlloc->enmAllocState = QCOWCLUSTERASYNCALLOCSTATE_L2_LINK;
1434 rc = vdIfIoIntFileWriteMeta(pImage->pIfIo, pImage->pStorage,
1435 pImage->offL1Table + pClusterAlloc->idxL1*sizeof(uint64_t),
1436 &offUpdateLe, sizeof(uint64_t), pIoCtx,
1437 qcowAsyncClusterAllocUpdate, pClusterAlloc);
1438 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
1439 break;
1440 else if (RT_FAILURE(rc))
1441 {
1442 /* Rollback. */
1443 qcowAsyncClusterAllocRollback(pImage, pIoCtx, pClusterAlloc);
1444 break;
1445 }
1446 /* Success, fall through. */
1447 }
1448 case QCOWCLUSTERASYNCALLOCSTATE_L2_LINK:
1449 {
1450 /* L2 link updated in L1 , save L2 entry in cache and allocate new user data cluster. */
1451 uint64_t offData = qcowClusterAllocate(pImage, 1);
1452
1453 /* Update the link in the in memory L1 table now. */
1454 pImage->paL1Table[pClusterAlloc->idxL1] = pClusterAlloc->pL2Entry->offL2Tbl;
1455 qcowL2TblCacheEntryInsert(pImage, pClusterAlloc->pL2Entry);
1456
1457 pClusterAlloc->enmAllocState = QCOWCLUSTERASYNCALLOCSTATE_USER_ALLOC;
1458 pClusterAlloc->offNextClusterOld = offData;
1459 pClusterAlloc->offClusterNew = offData;
1460
1461 /* Write data. */
1462 rc = vdIfIoIntFileWriteUser(pImage->pIfIo, pImage->pStorage,
1463 offData, pIoCtx, pClusterAlloc->cbToWrite,
1464 qcowAsyncClusterAllocUpdate, pClusterAlloc);
1465 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
1466 break;
1467 else if (RT_FAILURE(rc))
1468 {
1469 qcowAsyncClusterAllocRollback(pImage, pIoCtx, pClusterAlloc);
1470 RTMemFree(pClusterAlloc);
1471 break;
1472 }
1473 }
1474 case QCOWCLUSTERASYNCALLOCSTATE_USER_ALLOC:
1475 {
1476 uint64_t offUpdateLe = RT_H2BE_U64(pClusterAlloc->offClusterNew);
1477
1478 pClusterAlloc->enmAllocState = QCOWCLUSTERASYNCALLOCSTATE_USER_LINK;
1479
1480 /* Link L2 table and update it. */
1481 rc = vdIfIoIntFileWriteMeta(pImage->pIfIo, pImage->pStorage,
1482 pImage->paL1Table[pClusterAlloc->idxL1] + pClusterAlloc->idxL2*sizeof(uint64_t),
1483 &offUpdateLe, sizeof(uint64_t), pIoCtx,
1484 qcowAsyncClusterAllocUpdate, pClusterAlloc);
1485 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
1486 break;
1487 else if (RT_FAILURE(rc))
1488 {
1489 qcowAsyncClusterAllocRollback(pImage, pIoCtx, pClusterAlloc);
1490 RTMemFree(pClusterAlloc);
1491 break;
1492 }
1493 }
1494 case QCOWCLUSTERASYNCALLOCSTATE_USER_LINK:
1495 {
1496 /* Everything done without errors, signal completion. */
1497 pClusterAlloc->pL2Entry->paL2Tbl[pClusterAlloc->idxL2] = pClusterAlloc->offClusterNew;
1498 qcowL2TblCacheEntryRelease(pClusterAlloc->pL2Entry);
1499 RTMemFree(pClusterAlloc);
1500 rc = VINF_SUCCESS;
1501 break;
1502 }
1503 default:
1504 AssertMsgFailed(("Invalid async cluster allocation state %d\n",
1505 pClusterAlloc->enmAllocState));
1506 }
1507
1508 return rc;
1509}
1510
1511/** @copydoc VBOXHDDBACKEND::pfnCheckIfValid */
1512static DECLCALLBACK(int) qcowCheckIfValid(const char *pszFilename, PVDINTERFACE pVDIfsDisk,
1513 PVDINTERFACE pVDIfsImage, VDTYPE *penmType)
1514{
1515 RT_NOREF1(pVDIfsDisk);
1516 LogFlowFunc(("pszFilename=\"%s\" pVDIfsDisk=%#p pVDIfsImage=%#p\n", pszFilename, pVDIfsDisk, pVDIfsImage));
1517 PVDIOSTORAGE pStorage = NULL;
1518 uint64_t cbFile;
1519 int rc = VINF_SUCCESS;
1520
1521 /* Get I/O interface. */
1522 PVDINTERFACEIOINT pIfIo = VDIfIoIntGet(pVDIfsImage);
1523 AssertPtrReturn(pIfIo, VERR_INVALID_PARAMETER);
1524
1525 if ( !VALID_PTR(pszFilename)
1526 || !*pszFilename)
1527 {
1528 rc = VERR_INVALID_PARAMETER;
1529 goto out;
1530 }
1531
1532 /*
1533 * Open the file and read the footer.
1534 */
1535 rc = vdIfIoIntFileOpen(pIfIo, pszFilename,
1536 VDOpenFlagsToFileOpenFlags(VD_OPEN_FLAGS_READONLY,
1537 false /* fCreate */),
1538 &pStorage);
1539 if (RT_SUCCESS(rc))
1540 {
1541 rc = vdIfIoIntFileGetSize(pIfIo, pStorage, &cbFile);
1542 if ( RT_SUCCESS(rc)
1543 && cbFile > sizeof(QCowHeader))
1544 {
1545 QCowHeader Header;
1546
1547 rc = vdIfIoIntFileReadSync(pIfIo, pStorage, 0, &Header, sizeof(Header));
1548 if ( RT_SUCCESS(rc)
1549 && qcowHdrConvertToHostEndianess(&Header))
1550 {
1551 *penmType = VDTYPE_HDD;
1552 rc = VINF_SUCCESS;
1553 }
1554 else
1555 rc = VERR_VD_GEN_INVALID_HEADER;
1556 }
1557 else
1558 rc = VERR_VD_GEN_INVALID_HEADER;
1559 }
1560
1561 if (pStorage)
1562 vdIfIoIntFileClose(pIfIo, pStorage);
1563
1564out:
1565 LogFlowFunc(("returns %Rrc\n", rc));
1566 return rc;
1567}
1568
1569/** @copydoc VBOXHDDBACKEND::pfnOpen */
1570static DECLCALLBACK(int) qcowOpen(const char *pszFilename, unsigned uOpenFlags,
1571 PVDINTERFACE pVDIfsDisk, PVDINTERFACE pVDIfsImage,
1572 VDTYPE enmType, void **ppBackendData)
1573{
1574 LogFlowFunc(("pszFilename=\"%s\" uOpenFlags=%#x pVDIfsDisk=%#p pVDIfsImage=%#p enmType=%u ppBackendData=%#p\n", pszFilename, uOpenFlags, pVDIfsDisk, pVDIfsImage, enmType, ppBackendData));
1575 int rc;
1576 PQCOWIMAGE pImage;
1577
1578 NOREF(enmType); /**< @todo r=klaus make use of the type info. */
1579
1580 /* Check open flags. All valid flags are supported. */
1581 if (uOpenFlags & ~VD_OPEN_FLAGS_MASK)
1582 {
1583 rc = VERR_INVALID_PARAMETER;
1584 goto out;
1585 }
1586
1587 /* Check remaining arguments. */
1588 if ( !VALID_PTR(pszFilename)
1589 || !*pszFilename)
1590 {
1591 rc = VERR_INVALID_PARAMETER;
1592 goto out;
1593 }
1594
1595
1596 pImage = (PQCOWIMAGE)RTMemAllocZ(sizeof(QCOWIMAGE));
1597 if (!pImage)
1598 {
1599 rc = VERR_NO_MEMORY;
1600 goto out;
1601 }
1602 pImage->pszFilename = pszFilename;
1603 pImage->pStorage = NULL;
1604 pImage->pVDIfsDisk = pVDIfsDisk;
1605 pImage->pVDIfsImage = pVDIfsImage;
1606
1607 rc = qcowOpenImage(pImage, uOpenFlags);
1608 if (RT_SUCCESS(rc))
1609 *ppBackendData = pImage;
1610 else
1611 RTMemFree(pImage);
1612
1613out:
1614 LogFlowFunc(("returns %Rrc (pBackendData=%#p)\n", rc, *ppBackendData));
1615 return rc;
1616}
1617
1618/** @copydoc VBOXHDDBACKEND::pfnCreate */
1619static DECLCALLBACK(int) qcowCreate(const char *pszFilename, uint64_t cbSize,
1620 unsigned uImageFlags, const char *pszComment,
1621 PCVDGEOMETRY pPCHSGeometry, PCVDGEOMETRY pLCHSGeometry,
1622 PCRTUUID pUuid, unsigned uOpenFlags,
1623 unsigned uPercentStart, unsigned uPercentSpan,
1624 PVDINTERFACE pVDIfsDisk, PVDINTERFACE pVDIfsImage,
1625 PVDINTERFACE pVDIfsOperation, VDTYPE enmType,
1626 void **ppBackendData)
1627{
1628 RT_NOREF1(pUuid);
1629 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",
1630 pszFilename, cbSize, uImageFlags, pszComment, pPCHSGeometry, pLCHSGeometry, pUuid, uOpenFlags, uPercentStart, uPercentSpan, pVDIfsDisk, pVDIfsImage, pVDIfsOperation, enmType, ppBackendData));
1631 int rc;
1632 PQCOWIMAGE pImage;
1633
1634 PFNVDPROGRESS pfnProgress = NULL;
1635 void *pvUser = NULL;
1636 PVDINTERFACEPROGRESS pIfProgress = VDIfProgressGet(pVDIfsOperation);
1637 if (pIfProgress)
1638 {
1639 pfnProgress = pIfProgress->pfnProgress;
1640 pvUser = pIfProgress->Core.pvUser;
1641 }
1642
1643 /* Check the VD container type. */
1644 if (enmType != VDTYPE_HDD)
1645 {
1646 rc = VERR_VD_INVALID_TYPE;
1647 goto out;
1648 }
1649
1650 /* Check open flags. All valid flags are supported. */
1651 if (uOpenFlags & ~VD_OPEN_FLAGS_MASK)
1652 {
1653 rc = VERR_INVALID_PARAMETER;
1654 goto out;
1655 }
1656
1657 /* Check remaining arguments. */
1658 if ( !VALID_PTR(pszFilename)
1659 || !*pszFilename
1660 || !VALID_PTR(pPCHSGeometry)
1661 || !VALID_PTR(pLCHSGeometry))
1662 {
1663 rc = VERR_INVALID_PARAMETER;
1664 goto out;
1665 }
1666
1667 pImage = (PQCOWIMAGE)RTMemAllocZ(sizeof(QCOWIMAGE));
1668 if (!pImage)
1669 {
1670 rc = VERR_NO_MEMORY;
1671 goto out;
1672 }
1673 pImage->pszFilename = pszFilename;
1674 pImage->pStorage = NULL;
1675 pImage->pVDIfsDisk = pVDIfsDisk;
1676 pImage->pVDIfsImage = pVDIfsImage;
1677
1678 rc = qcowCreateImage(pImage, cbSize, uImageFlags, pszComment,
1679 pPCHSGeometry, pLCHSGeometry, uOpenFlags,
1680 pfnProgress, pvUser, uPercentStart, uPercentSpan);
1681 if (RT_SUCCESS(rc))
1682 {
1683 /* So far the image is opened in read/write mode. Make sure the
1684 * image is opened in read-only mode if the caller requested that. */
1685 if (uOpenFlags & VD_OPEN_FLAGS_READONLY)
1686 {
1687 qcowFreeImage(pImage, false);
1688 rc = qcowOpenImage(pImage, uOpenFlags);
1689 if (RT_FAILURE(rc))
1690 {
1691 RTMemFree(pImage);
1692 goto out;
1693 }
1694 }
1695 *ppBackendData = pImage;
1696 }
1697 else
1698 RTMemFree(pImage);
1699
1700out:
1701 LogFlowFunc(("returns %Rrc (pBackendData=%#p)\n", rc, *ppBackendData));
1702 return rc;
1703}
1704
1705/** @copydoc VBOXHDDBACKEND::pfnRename */
1706static DECLCALLBACK(int) qcowRename(void *pBackendData, const char *pszFilename)
1707{
1708 LogFlowFunc(("pBackendData=%#p pszFilename=%#p\n", pBackendData, pszFilename));
1709 int rc = VINF_SUCCESS;
1710 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
1711
1712 /* Check arguments. */
1713 if ( !pImage
1714 || !pszFilename
1715 || !*pszFilename)
1716 {
1717 rc = VERR_INVALID_PARAMETER;
1718 goto out;
1719 }
1720
1721 /* Close the image. */
1722 rc = qcowFreeImage(pImage, false);
1723 if (RT_FAILURE(rc))
1724 goto out;
1725
1726 /* Rename the file. */
1727 rc = vdIfIoIntFileMove(pImage->pIfIo, pImage->pszFilename, pszFilename, 0);
1728 if (RT_FAILURE(rc))
1729 {
1730 /* The move failed, try to reopen the original image. */
1731 int rc2 = qcowOpenImage(pImage, pImage->uOpenFlags);
1732 if (RT_FAILURE(rc2))
1733 rc = rc2;
1734
1735 goto out;
1736 }
1737
1738 /* Update pImage with the new information. */
1739 pImage->pszFilename = pszFilename;
1740
1741 /* Open the old image with new name. */
1742 rc = qcowOpenImage(pImage, pImage->uOpenFlags);
1743 if (RT_FAILURE(rc))
1744 goto out;
1745
1746out:
1747 LogFlowFunc(("returns %Rrc\n", rc));
1748 return rc;
1749}
1750
1751/** @copydoc VBOXHDDBACKEND::pfnClose */
1752static DECLCALLBACK(int) qcowClose(void *pBackendData, bool fDelete)
1753{
1754 LogFlowFunc(("pBackendData=%#p fDelete=%d\n", pBackendData, fDelete));
1755 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
1756 int rc;
1757
1758 rc = qcowFreeImage(pImage, fDelete);
1759 RTMemFree(pImage);
1760
1761 LogFlowFunc(("returns %Rrc\n", rc));
1762 return rc;
1763}
1764
1765static DECLCALLBACK(int) qcowRead(void *pBackendData, uint64_t uOffset, size_t cbToRead,
1766 PVDIOCTX pIoCtx, size_t *pcbActuallyRead)
1767{
1768 LogFlowFunc(("pBackendData=%#p uOffset=%llu pIoCtx=%#p cbToRead=%zu pcbActuallyRead=%#p\n",
1769 pBackendData, uOffset, pIoCtx, cbToRead, pcbActuallyRead));
1770 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
1771 uint32_t offCluster = 0;
1772 uint32_t idxL1 = 0;
1773 uint32_t idxL2 = 0;
1774 uint64_t offFile = 0;
1775 int rc;
1776
1777 AssertPtr(pImage);
1778 Assert(uOffset % 512 == 0);
1779 Assert(cbToRead % 512 == 0);
1780
1781 if (!VALID_PTR(pIoCtx) || !cbToRead)
1782 {
1783 rc = VERR_INVALID_PARAMETER;
1784 goto out;
1785 }
1786
1787 if ( uOffset + cbToRead > pImage->cbSize
1788 || cbToRead == 0)
1789 {
1790 rc = VERR_INVALID_PARAMETER;
1791 goto out;
1792 }
1793
1794 qcowConvertLogicalOffset(pImage, uOffset, &idxL1, &idxL2, &offCluster);
1795
1796 /* Clip read size to remain in the cluster. */
1797 cbToRead = RT_MIN(cbToRead, pImage->cbCluster - offCluster);
1798
1799 /* Get offset in image. */
1800 rc = qcowConvertToImageOffset(pImage, pIoCtx, idxL1, idxL2, offCluster, &offFile);
1801 if (RT_SUCCESS(rc))
1802 rc = vdIfIoIntFileReadUser(pImage->pIfIo, pImage->pStorage, offFile,
1803 pIoCtx, cbToRead);
1804
1805 if ( ( RT_SUCCESS(rc)
1806 || rc == VERR_VD_BLOCK_FREE
1807 || rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
1808 && pcbActuallyRead)
1809 *pcbActuallyRead = cbToRead;
1810
1811out:
1812 LogFlowFunc(("returns %Rrc\n", rc));
1813 return rc;
1814}
1815
1816static DECLCALLBACK(int) qcowWrite(void *pBackendData, uint64_t uOffset, size_t cbToWrite,
1817 PVDIOCTX pIoCtx, size_t *pcbWriteProcess, size_t *pcbPreRead,
1818 size_t *pcbPostRead, unsigned fWrite)
1819{
1820 LogFlowFunc(("pBackendData=%#p uOffset=%llu pIoCtx=%#p cbToWrite=%zu pcbWriteProcess=%#p pcbPreRead=%#p pcbPostRead=%#p\n",
1821 pBackendData, uOffset, pIoCtx, cbToWrite, pcbWriteProcess, pcbPreRead, pcbPostRead));
1822 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
1823 uint32_t offCluster = 0;
1824 uint32_t idxL1 = 0;
1825 uint32_t idxL2 = 0;
1826 uint64_t offImage = 0;
1827 int rc = VINF_SUCCESS;
1828
1829 AssertPtr(pImage);
1830 Assert(!(uOffset % 512));
1831 Assert(!(cbToWrite % 512));
1832
1833 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
1834 {
1835 rc = VERR_VD_IMAGE_READ_ONLY;
1836 goto out;
1837 }
1838
1839 if (!VALID_PTR(pIoCtx) || !cbToWrite)
1840 {
1841 rc = VERR_INVALID_PARAMETER;
1842 goto out;
1843 }
1844
1845 if ( uOffset + cbToWrite > pImage->cbSize
1846 || cbToWrite == 0)
1847 {
1848 rc = VERR_INVALID_PARAMETER;
1849 goto out;
1850 }
1851
1852 /* Convert offset to L1, L2 index and cluster offset. */
1853 qcowConvertLogicalOffset(pImage, uOffset, &idxL1, &idxL2, &offCluster);
1854
1855 /* Clip write size to remain in the cluster. */
1856 cbToWrite = RT_MIN(cbToWrite, pImage->cbCluster - offCluster);
1857 Assert(!(cbToWrite % 512));
1858
1859 /* Get offset in image. */
1860 rc = qcowConvertToImageOffset(pImage, pIoCtx, idxL1, idxL2, offCluster, &offImage);
1861 if (RT_SUCCESS(rc))
1862 rc = vdIfIoIntFileWriteUser(pImage->pIfIo, pImage->pStorage,
1863 offImage, pIoCtx, cbToWrite, NULL, NULL);
1864 else if (rc == VERR_VD_BLOCK_FREE)
1865 {
1866 if ( cbToWrite == pImage->cbCluster
1867 && !(fWrite & VD_WRITE_NO_ALLOC))
1868 {
1869 PQCOWL2CACHEENTRY pL2Entry = NULL;
1870
1871 /* Full cluster write to previously unallocated cluster.
1872 * Allocate cluster and write data. */
1873 Assert(!offCluster);
1874
1875 do
1876 {
1877 /* Check if we have to allocate a new cluster for L2 tables. */
1878 if (!pImage->paL1Table[idxL1])
1879 {
1880 uint64_t offL2Tbl;
1881 PQCOWCLUSTERASYNCALLOC pL2ClusterAlloc = NULL;
1882
1883 /* Allocate new async cluster allocation state. */
1884 pL2ClusterAlloc = (PQCOWCLUSTERASYNCALLOC)RTMemAllocZ(sizeof(QCOWCLUSTERASYNCALLOC));
1885 if (RT_UNLIKELY(!pL2ClusterAlloc))
1886 {
1887 rc = VERR_NO_MEMORY;
1888 break;
1889 }
1890
1891 pL2Entry = qcowL2TblCacheEntryAlloc(pImage);
1892 if (!pL2Entry)
1893 {
1894 rc = VERR_NO_MEMORY;
1895 RTMemFree(pL2ClusterAlloc);
1896 break;
1897 }
1898
1899 offL2Tbl = qcowClusterAllocate(pImage, qcowByte2Cluster(pImage, pImage->cbL2Table));
1900 pL2Entry->offL2Tbl = offL2Tbl;
1901 memset(pL2Entry->paL2Tbl, 0, pImage->cbL2Table);
1902
1903 pL2ClusterAlloc->enmAllocState = QCOWCLUSTERASYNCALLOCSTATE_L2_ALLOC;
1904 pL2ClusterAlloc->offNextClusterOld = offL2Tbl;
1905 pL2ClusterAlloc->offClusterNew = offL2Tbl;
1906 pL2ClusterAlloc->idxL1 = idxL1;
1907 pL2ClusterAlloc->idxL2 = idxL2;
1908 pL2ClusterAlloc->cbToWrite = cbToWrite;
1909 pL2ClusterAlloc->pL2Entry = pL2Entry;
1910
1911 /*
1912 * Write the L2 table first and link to the L1 table afterwards.
1913 * If something unexpected happens the worst case which can happen
1914 * is a leak of some clusters.
1915 */
1916 rc = vdIfIoIntFileWriteMeta(pImage->pIfIo, pImage->pStorage,
1917 offL2Tbl, pL2Entry->paL2Tbl, pImage->cbL2Table, pIoCtx,
1918 qcowAsyncClusterAllocUpdate, pL2ClusterAlloc);
1919 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
1920 break;
1921 else if (RT_FAILURE(rc))
1922 {
1923 RTMemFree(pL2ClusterAlloc);
1924 qcowL2TblCacheEntryFree(pImage, pL2Entry);
1925 break;
1926 }
1927
1928 rc = qcowAsyncClusterAllocUpdate(pImage, pIoCtx, pL2ClusterAlloc, rc);
1929 }
1930 else
1931 {
1932 rc = qcowL2TblCacheFetch(pImage, pIoCtx, pImage->paL1Table[idxL1],
1933 &pL2Entry);
1934 if (RT_SUCCESS(rc))
1935 {
1936 PQCOWCLUSTERASYNCALLOC pDataClusterAlloc = NULL;
1937
1938 /* Allocate new async cluster allocation state. */
1939 pDataClusterAlloc = (PQCOWCLUSTERASYNCALLOC)RTMemAllocZ(sizeof(QCOWCLUSTERASYNCALLOC));
1940 if (RT_UNLIKELY(!pDataClusterAlloc))
1941 {
1942 rc = VERR_NO_MEMORY;
1943 break;
1944 }
1945
1946 /* Allocate new cluster for the data. */
1947 uint64_t offData = qcowClusterAllocate(pImage, 1);
1948
1949 pDataClusterAlloc->enmAllocState = QCOWCLUSTERASYNCALLOCSTATE_USER_ALLOC;
1950 pDataClusterAlloc->offNextClusterOld = offData;
1951 pDataClusterAlloc->offClusterNew = offData;
1952 pDataClusterAlloc->idxL1 = idxL1;
1953 pDataClusterAlloc->idxL2 = idxL2;
1954 pDataClusterAlloc->cbToWrite = cbToWrite;
1955 pDataClusterAlloc->pL2Entry = pL2Entry;
1956
1957 /* Write data. */
1958 rc = vdIfIoIntFileWriteUser(pImage->pIfIo, pImage->pStorage,
1959 offData, pIoCtx, cbToWrite,
1960 qcowAsyncClusterAllocUpdate, pDataClusterAlloc);
1961 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
1962 break;
1963 else if (RT_FAILURE(rc))
1964 {
1965 RTMemFree(pDataClusterAlloc);
1966 break;
1967 }
1968
1969 rc = qcowAsyncClusterAllocUpdate(pImage, pIoCtx, pDataClusterAlloc, rc);
1970 }
1971 }
1972
1973 } while (0);
1974
1975 *pcbPreRead = 0;
1976 *pcbPostRead = 0;
1977 }
1978 else
1979 {
1980 /* Trying to do a partial write to an unallocated cluster. Don't do
1981 * anything except letting the upper layer know what to do. */
1982 *pcbPreRead = offCluster;
1983 *pcbPostRead = pImage->cbCluster - cbToWrite - *pcbPreRead;
1984 }
1985 }
1986
1987 if (pcbWriteProcess)
1988 *pcbWriteProcess = cbToWrite;
1989
1990
1991out:
1992 LogFlowFunc(("returns %Rrc\n", rc));
1993 return rc;
1994}
1995
1996static DECLCALLBACK(int) qcowFlush(void *pBackendData, PVDIOCTX pIoCtx)
1997{
1998 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
1999 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2000 int rc = VINF_SUCCESS;
2001
2002 Assert(pImage);
2003
2004 if (VALID_PTR(pIoCtx))
2005 rc = qcowFlushImageAsync(pImage, pIoCtx);
2006 else
2007 rc = VERR_INVALID_PARAMETER;
2008
2009 LogFlowFunc(("returns %Rrc\n", rc));
2010 return rc;
2011}
2012
2013/** @copydoc VBOXHDDBACKEND::pfnGetVersion */
2014static DECLCALLBACK(unsigned) qcowGetVersion(void *pBackendData)
2015{
2016 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
2017 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2018
2019 AssertPtr(pImage);
2020
2021 if (pImage)
2022 return pImage->uVersion;
2023 else
2024 return 0;
2025}
2026
2027/** @copydoc VBOXHDDBACKEND::pfnGetSectorSize */
2028static DECLCALLBACK(uint32_t) qcowGetSectorSize(void *pBackendData)
2029{
2030 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
2031 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2032 uint32_t cb = 0;
2033
2034 AssertPtr(pImage);
2035
2036 if (pImage && pImage->pStorage)
2037 cb = 512;
2038
2039 LogFlowFunc(("returns %u\n", cb));
2040 return cb;
2041}
2042
2043/** @copydoc VBOXHDDBACKEND::pfnGetSize */
2044static DECLCALLBACK(uint64_t) qcowGetSize(void *pBackendData)
2045{
2046 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
2047 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2048 uint64_t cb = 0;
2049
2050 AssertPtr(pImage);
2051
2052 if (pImage && pImage->pStorage)
2053 cb = pImage->cbSize;
2054
2055 LogFlowFunc(("returns %llu\n", cb));
2056 return cb;
2057}
2058
2059/** @copydoc VBOXHDDBACKEND::pfnGetFileSize */
2060static DECLCALLBACK(uint64_t) qcowGetFileSize(void *pBackendData)
2061{
2062 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
2063 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2064 uint64_t cb = 0;
2065
2066 AssertPtr(pImage);
2067
2068 if (pImage)
2069 {
2070 uint64_t cbFile;
2071 if (pImage->pStorage)
2072 {
2073 int rc = vdIfIoIntFileGetSize(pImage->pIfIo, pImage->pStorage, &cbFile);
2074 if (RT_SUCCESS(rc))
2075 cb += cbFile;
2076 }
2077 }
2078
2079 LogFlowFunc(("returns %lld\n", cb));
2080 return cb;
2081}
2082
2083/** @copydoc VBOXHDDBACKEND::pfnGetPCHSGeometry */
2084static DECLCALLBACK(int) qcowGetPCHSGeometry(void *pBackendData,
2085 PVDGEOMETRY pPCHSGeometry)
2086{
2087 LogFlowFunc(("pBackendData=%#p pPCHSGeometry=%#p\n", pBackendData, pPCHSGeometry));
2088 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2089 int rc;
2090
2091 AssertPtr(pImage);
2092
2093 if (pImage)
2094 {
2095 if (pImage->PCHSGeometry.cCylinders)
2096 {
2097 *pPCHSGeometry = pImage->PCHSGeometry;
2098 rc = VINF_SUCCESS;
2099 }
2100 else
2101 rc = VERR_VD_GEOMETRY_NOT_SET;
2102 }
2103 else
2104 rc = VERR_VD_NOT_OPENED;
2105
2106 LogFlowFunc(("returns %Rrc (PCHS=%u/%u/%u)\n", rc, pPCHSGeometry->cCylinders, pPCHSGeometry->cHeads, pPCHSGeometry->cSectors));
2107 return rc;
2108}
2109
2110/** @copydoc VBOXHDDBACKEND::pfnSetPCHSGeometry */
2111static DECLCALLBACK(int) qcowSetPCHSGeometry(void *pBackendData,
2112 PCVDGEOMETRY pPCHSGeometry)
2113{
2114 LogFlowFunc(("pBackendData=%#p pPCHSGeometry=%#p PCHS=%u/%u/%u\n", pBackendData, pPCHSGeometry, pPCHSGeometry->cCylinders, pPCHSGeometry->cHeads, pPCHSGeometry->cSectors));
2115 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2116 int rc;
2117
2118 AssertPtr(pImage);
2119
2120 if (pImage)
2121 {
2122 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
2123 {
2124 rc = VERR_VD_IMAGE_READ_ONLY;
2125 goto out;
2126 }
2127
2128 pImage->PCHSGeometry = *pPCHSGeometry;
2129 rc = VINF_SUCCESS;
2130 }
2131 else
2132 rc = VERR_VD_NOT_OPENED;
2133
2134out:
2135 LogFlowFunc(("returns %Rrc\n", rc));
2136 return rc;
2137}
2138
2139/** @copydoc VBOXHDDBACKEND::pfnGetLCHSGeometry */
2140static DECLCALLBACK(int) qcowGetLCHSGeometry(void *pBackendData,
2141 PVDGEOMETRY pLCHSGeometry)
2142{
2143 LogFlowFunc(("pBackendData=%#p pLCHSGeometry=%#p\n", pBackendData, pLCHSGeometry));
2144 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2145 int rc;
2146
2147 AssertPtr(pImage);
2148
2149 if (pImage)
2150 {
2151 if (pImage->LCHSGeometry.cCylinders)
2152 {
2153 *pLCHSGeometry = pImage->LCHSGeometry;
2154 rc = VINF_SUCCESS;
2155 }
2156 else
2157 rc = VERR_VD_GEOMETRY_NOT_SET;
2158 }
2159 else
2160 rc = VERR_VD_NOT_OPENED;
2161
2162 LogFlowFunc(("returns %Rrc (LCHS=%u/%u/%u)\n", rc, pLCHSGeometry->cCylinders, pLCHSGeometry->cHeads, pLCHSGeometry->cSectors));
2163 return rc;
2164}
2165
2166/** @copydoc VBOXHDDBACKEND::pfnSetLCHSGeometry */
2167static DECLCALLBACK(int) qcowSetLCHSGeometry(void *pBackendData,
2168 PCVDGEOMETRY pLCHSGeometry)
2169{
2170 LogFlowFunc(("pBackendData=%#p pLCHSGeometry=%#p LCHS=%u/%u/%u\n", pBackendData, pLCHSGeometry, pLCHSGeometry->cCylinders, pLCHSGeometry->cHeads, pLCHSGeometry->cSectors));
2171 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2172 int rc;
2173
2174 AssertPtr(pImage);
2175
2176 if (pImage)
2177 {
2178 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
2179 {
2180 rc = VERR_VD_IMAGE_READ_ONLY;
2181 goto out;
2182 }
2183
2184 pImage->LCHSGeometry = *pLCHSGeometry;
2185 rc = VINF_SUCCESS;
2186 }
2187 else
2188 rc = VERR_VD_NOT_OPENED;
2189
2190out:
2191 LogFlowFunc(("returns %Rrc\n", rc));
2192 return rc;
2193}
2194
2195/** @copydoc VBOXHDDBACKEND::pfnGetImageFlags */
2196static DECLCALLBACK(unsigned) qcowGetImageFlags(void *pBackendData)
2197{
2198 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
2199 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2200 unsigned uImageFlags;
2201
2202 AssertPtr(pImage);
2203
2204 if (pImage)
2205 uImageFlags = pImage->uImageFlags;
2206 else
2207 uImageFlags = 0;
2208
2209 LogFlowFunc(("returns %#x\n", uImageFlags));
2210 return uImageFlags;
2211}
2212
2213/** @copydoc VBOXHDDBACKEND::pfnGetOpenFlags */
2214static DECLCALLBACK(unsigned) qcowGetOpenFlags(void *pBackendData)
2215{
2216 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
2217 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2218 unsigned uOpenFlags;
2219
2220 AssertPtr(pImage);
2221
2222 if (pImage)
2223 uOpenFlags = pImage->uOpenFlags;
2224 else
2225 uOpenFlags = 0;
2226
2227 LogFlowFunc(("returns %#x\n", uOpenFlags));
2228 return uOpenFlags;
2229}
2230
2231/** @copydoc VBOXHDDBACKEND::pfnSetOpenFlags */
2232static DECLCALLBACK(int) qcowSetOpenFlags(void *pBackendData, unsigned uOpenFlags)
2233{
2234 LogFlowFunc(("pBackendData=%#p\n uOpenFlags=%#x", pBackendData, uOpenFlags));
2235 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2236 int rc;
2237
2238 /* Image must be opened and the new flags must be valid. */
2239 if (!pImage || (uOpenFlags & ~( VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_INFO
2240 | VD_OPEN_FLAGS_ASYNC_IO | VD_OPEN_FLAGS_SKIP_CONSISTENCY_CHECKS)))
2241 {
2242 rc = VERR_INVALID_PARAMETER;
2243 goto out;
2244 }
2245
2246 /* Implement this operation via reopening the image. */
2247 rc = qcowFreeImage(pImage, false);
2248 if (RT_FAILURE(rc))
2249 goto out;
2250 rc = qcowOpenImage(pImage, uOpenFlags);
2251
2252out:
2253 LogFlowFunc(("returns %Rrc\n", rc));
2254 return rc;
2255}
2256
2257/** @copydoc VBOXHDDBACKEND::pfnGetComment */
2258static DECLCALLBACK(int) qcowGetComment(void *pBackendData, char *pszComment, size_t cbComment)
2259{
2260 RT_NOREF2(pszComment, cbComment);
2261 LogFlowFunc(("pBackendData=%#p pszComment=%#p cbComment=%zu\n", pBackendData, pszComment, cbComment));
2262 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2263 int rc;
2264
2265 AssertPtr(pImage);
2266
2267 if (pImage)
2268 rc = VERR_NOT_SUPPORTED;
2269 else
2270 rc = VERR_VD_NOT_OPENED;
2271
2272 LogFlowFunc(("returns %Rrc comment='%s'\n", rc, pszComment));
2273 return rc;
2274}
2275
2276/** @copydoc VBOXHDDBACKEND::pfnSetComment */
2277static DECLCALLBACK(int) qcowSetComment(void *pBackendData, const char *pszComment)
2278{
2279 RT_NOREF1(pszComment);
2280 LogFlowFunc(("pBackendData=%#p pszComment=\"%s\"\n", pBackendData, pszComment));
2281 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2282 int rc;
2283
2284 AssertPtr(pImage);
2285
2286 if (pImage)
2287 {
2288 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
2289 rc = VERR_VD_IMAGE_READ_ONLY;
2290 else
2291 rc = VERR_NOT_SUPPORTED;
2292 }
2293 else
2294 rc = VERR_VD_NOT_OPENED;
2295
2296 LogFlowFunc(("returns %Rrc\n", rc));
2297 return rc;
2298}
2299
2300/** @copydoc VBOXHDDBACKEND::pfnGetUuid */
2301static DECLCALLBACK(int) qcowGetUuid(void *pBackendData, PRTUUID pUuid)
2302{
2303 RT_NOREF1(pUuid);
2304 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
2305 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2306 int rc;
2307
2308 AssertPtr(pImage);
2309
2310 if (pImage)
2311 rc = VERR_NOT_SUPPORTED;
2312 else
2313 rc = VERR_VD_NOT_OPENED;
2314
2315 LogFlowFunc(("returns %Rrc (%RTuuid)\n", rc, pUuid));
2316 return rc;
2317}
2318
2319/** @copydoc VBOXHDDBACKEND::pfnSetUuid */
2320static DECLCALLBACK(int) qcowSetUuid(void *pBackendData, PCRTUUID pUuid)
2321{
2322 RT_NOREF1(pUuid);
2323 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
2324 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2325 int rc;
2326
2327 LogFlowFunc(("%RTuuid\n", pUuid));
2328 AssertPtr(pImage);
2329
2330 if (pImage)
2331 {
2332 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
2333 rc = VERR_NOT_SUPPORTED;
2334 else
2335 rc = VERR_VD_IMAGE_READ_ONLY;
2336 }
2337 else
2338 rc = VERR_VD_NOT_OPENED;
2339
2340 LogFlowFunc(("returns %Rrc\n", rc));
2341 return rc;
2342}
2343
2344/** @copydoc VBOXHDDBACKEND::pfnGetModificationUuid */
2345static DECLCALLBACK(int) qcowGetModificationUuid(void *pBackendData, PRTUUID pUuid)
2346{
2347 RT_NOREF1(pUuid);
2348 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
2349 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2350 int rc;
2351
2352 AssertPtr(pImage);
2353
2354 if (pImage)
2355 rc = VERR_NOT_SUPPORTED;
2356 else
2357 rc = VERR_VD_NOT_OPENED;
2358
2359 LogFlowFunc(("returns %Rrc (%RTuuid)\n", rc, pUuid));
2360 return rc;
2361}
2362
2363/** @copydoc VBOXHDDBACKEND::pfnSetModificationUuid */
2364static DECLCALLBACK(int) qcowSetModificationUuid(void *pBackendData, PCRTUUID pUuid)
2365{
2366 RT_NOREF1(pUuid);
2367 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
2368 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2369 int rc;
2370
2371 AssertPtr(pImage);
2372
2373 if (pImage)
2374 {
2375 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
2376 rc = VERR_NOT_SUPPORTED;
2377 else
2378 rc = VERR_VD_IMAGE_READ_ONLY;
2379 }
2380 else
2381 rc = VERR_VD_NOT_OPENED;
2382
2383 LogFlowFunc(("returns %Rrc\n", rc));
2384 return rc;
2385}
2386
2387/** @copydoc VBOXHDDBACKEND::pfnGetParentUuid */
2388static DECLCALLBACK(int) qcowGetParentUuid(void *pBackendData, PRTUUID pUuid)
2389{
2390 RT_NOREF1(pUuid);
2391 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
2392 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2393 int rc;
2394
2395 AssertPtr(pImage);
2396
2397 if (pImage)
2398 rc = VERR_NOT_SUPPORTED;
2399 else
2400 rc = VERR_VD_NOT_OPENED;
2401
2402 LogFlowFunc(("returns %Rrc (%RTuuid)\n", rc, pUuid));
2403 return rc;
2404}
2405
2406/** @copydoc VBOXHDDBACKEND::pfnSetParentUuid */
2407static DECLCALLBACK(int) qcowSetParentUuid(void *pBackendData, PCRTUUID pUuid)
2408{
2409 RT_NOREF1(pUuid);
2410 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
2411 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2412 int rc;
2413
2414 AssertPtr(pImage);
2415
2416 if (pImage)
2417 {
2418 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
2419 rc = VERR_NOT_SUPPORTED;
2420 else
2421 rc = VERR_VD_IMAGE_READ_ONLY;
2422 }
2423 else
2424 rc = VERR_VD_NOT_OPENED;
2425
2426 LogFlowFunc(("returns %Rrc\n", rc));
2427 return rc;
2428}
2429
2430/** @copydoc VBOXHDDBACKEND::pfnGetParentModificationUuid */
2431static DECLCALLBACK(int) qcowGetParentModificationUuid(void *pBackendData, PRTUUID pUuid)
2432{
2433 RT_NOREF1(pUuid);
2434 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
2435 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2436 int rc;
2437
2438 AssertPtr(pImage);
2439
2440 if (pImage)
2441 rc = VERR_NOT_SUPPORTED;
2442 else
2443 rc = VERR_VD_NOT_OPENED;
2444
2445 LogFlowFunc(("returns %Rrc (%RTuuid)\n", rc, pUuid));
2446 return rc;
2447}
2448
2449/** @copydoc VBOXHDDBACKEND::pfnSetParentModificationUuid */
2450static DECLCALLBACK(int) qcowSetParentModificationUuid(void *pBackendData, PCRTUUID pUuid)
2451{
2452 RT_NOREF1(pUuid);
2453 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
2454 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2455 int rc;
2456
2457 AssertPtr(pImage);
2458
2459 if (pImage)
2460 {
2461 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
2462 rc = VERR_NOT_SUPPORTED;
2463 else
2464 rc = VERR_VD_IMAGE_READ_ONLY;
2465 }
2466 else
2467 rc = VERR_VD_NOT_OPENED;
2468
2469 LogFlowFunc(("returns %Rrc\n", rc));
2470 return rc;
2471}
2472
2473/** @copydoc VBOXHDDBACKEND::pfnDump */
2474static DECLCALLBACK(void) qcowDump(void *pBackendData)
2475{
2476 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2477
2478 AssertPtr(pImage);
2479 if (pImage)
2480 {
2481 vdIfErrorMessage(pImage->pIfError, "Header: Geometry PCHS=%u/%u/%u LCHS=%u/%u/%u cSector=%llu\n",
2482 pImage->PCHSGeometry.cCylinders, pImage->PCHSGeometry.cHeads, pImage->PCHSGeometry.cSectors,
2483 pImage->LCHSGeometry.cCylinders, pImage->LCHSGeometry.cHeads, pImage->LCHSGeometry.cSectors,
2484 pImage->cbSize / 512);
2485 }
2486}
2487
2488/** @copydoc VBOXHDDBACKEND::pfnGetParentFilename */
2489static DECLCALLBACK(int) qcowGetParentFilename(void *pBackendData, char **ppszParentFilename)
2490{
2491 int rc = VINF_SUCCESS;
2492 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2493
2494 AssertPtr(pImage);
2495 if (pImage)
2496 if (pImage->pszBackingFilename)
2497 *ppszParentFilename = RTStrDup(pImage->pszBackingFilename);
2498 else
2499 rc = VERR_NOT_SUPPORTED;
2500 else
2501 rc = VERR_VD_NOT_OPENED;
2502
2503 LogFlowFunc(("returns %Rrc\n", rc));
2504 return rc;
2505}
2506
2507/** @copydoc VBOXHDDBACKEND::pfnSetParentFilename */
2508static DECLCALLBACK(int) qcowSetParentFilename(void *pBackendData, const char *pszParentFilename)
2509{
2510 int rc = VINF_SUCCESS;
2511 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2512
2513 AssertPtr(pImage);
2514 if (pImage)
2515 {
2516 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
2517 rc = VERR_VD_IMAGE_READ_ONLY;
2518 else if ( pImage->pszBackingFilename
2519 && (strlen(pszParentFilename) > pImage->cbBackingFilename))
2520 rc = VERR_NOT_SUPPORTED; /* The new filename is longer than the old one. */
2521 else
2522 {
2523 if (pImage->pszBackingFilename)
2524 RTStrFree(pImage->pszBackingFilename);
2525 pImage->pszBackingFilename = RTStrDup(pszParentFilename);
2526 if (!pImage->pszBackingFilename)
2527 rc = VERR_NO_MEMORY;
2528 else
2529 {
2530 if (!pImage->offBackingFilename)
2531 {
2532 /* Allocate new cluster. */
2533 uint64_t offData = qcowClusterAllocate(pImage, 1);
2534
2535 Assert((offData & UINT32_MAX) == offData);
2536 pImage->offBackingFilename = (uint32_t)offData;
2537 pImage->cbBackingFilename = (uint32_t)strlen(pszParentFilename);
2538 rc = vdIfIoIntFileSetSize(pImage->pIfIo, pImage->pStorage,
2539 offData + pImage->cbCluster);
2540 }
2541
2542 if (RT_SUCCESS(rc))
2543 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pImage->pStorage,
2544 pImage->offBackingFilename,
2545 pImage->pszBackingFilename,
2546 strlen(pImage->pszBackingFilename));
2547 }
2548 }
2549 }
2550 else
2551 rc = VERR_VD_NOT_OPENED;
2552
2553 LogFlowFunc(("returns %Rrc\n", rc));
2554 return rc;
2555}
2556
2557
2558
2559const VBOXHDDBACKEND g_QCowBackend =
2560{
2561 /* pszBackendName */
2562 "QCOW",
2563 /* cbSize */
2564 sizeof(VBOXHDDBACKEND),
2565 /* uBackendCaps */
2566 VD_CAP_FILE | VD_CAP_VFS | VD_CAP_CREATE_DYNAMIC | VD_CAP_DIFF | VD_CAP_ASYNC,
2567 /* paFileExtensions */
2568 s_aQCowFileExtensions,
2569 /* paConfigInfo */
2570 NULL,
2571 /* pfnCheckIfValid */
2572 qcowCheckIfValid,
2573 /* pfnOpen */
2574 qcowOpen,
2575 /* pfnCreate */
2576 qcowCreate,
2577 /* pfnRename */
2578 qcowRename,
2579 /* pfnClose */
2580 qcowClose,
2581 /* pfnRead */
2582 qcowRead,
2583 /* pfnWrite */
2584 qcowWrite,
2585 /* pfnFlush */
2586 qcowFlush,
2587 /* pfnDiscard */
2588 NULL,
2589 /* pfnGetVersion */
2590 qcowGetVersion,
2591 /* pfnGetSectorSize */
2592 qcowGetSectorSize,
2593 /* pfnGetSize */
2594 qcowGetSize,
2595 /* pfnGetFileSize */
2596 qcowGetFileSize,
2597 /* pfnGetPCHSGeometry */
2598 qcowGetPCHSGeometry,
2599 /* pfnSetPCHSGeometry */
2600 qcowSetPCHSGeometry,
2601 /* pfnGetLCHSGeometry */
2602 qcowGetLCHSGeometry,
2603 /* pfnSetLCHSGeometry */
2604 qcowSetLCHSGeometry,
2605 /* pfnGetImageFlags */
2606 qcowGetImageFlags,
2607 /* pfnGetOpenFlags */
2608 qcowGetOpenFlags,
2609 /* pfnSetOpenFlags */
2610 qcowSetOpenFlags,
2611 /* pfnGetComment */
2612 qcowGetComment,
2613 /* pfnSetComment */
2614 qcowSetComment,
2615 /* pfnGetUuid */
2616 qcowGetUuid,
2617 /* pfnSetUuid */
2618 qcowSetUuid,
2619 /* pfnGetModificationUuid */
2620 qcowGetModificationUuid,
2621 /* pfnSetModificationUuid */
2622 qcowSetModificationUuid,
2623 /* pfnGetParentUuid */
2624 qcowGetParentUuid,
2625 /* pfnSetParentUuid */
2626 qcowSetParentUuid,
2627 /* pfnGetParentModificationUuid */
2628 qcowGetParentModificationUuid,
2629 /* pfnSetParentModificationUuid */
2630 qcowSetParentModificationUuid,
2631 /* pfnDump */
2632 qcowDump,
2633 /* pfnGetTimestamp */
2634 NULL,
2635 /* pfnGetParentTimestamp */
2636 NULL,
2637 /* pfnSetParentTimestamp */
2638 NULL,
2639 /* pfnGetParentFilename */
2640 qcowGetParentFilename,
2641 /* pfnSetParentFilename */
2642 qcowSetParentFilename,
2643 /* pfnComposeLocation */
2644 genericFileComposeLocation,
2645 /* pfnComposeName */
2646 genericFileComposeName,
2647 /* pfnCompact */
2648 NULL,
2649 /* pfnResize */
2650 NULL,
2651 /* pfnRepair */
2652 NULL,
2653 /* pfnTraverseMetadata */
2654 NULL
2655};
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