VirtualBox

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

Last change on this file since 62534 was 62482, checked in by vboxsync, 8 years ago

(C) 2016

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