VirtualBox

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

Last change on this file since 48851 was 48851, checked in by vboxsync, 11 years ago

Storage: Addressing 64-bit windows warnings.

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