VirtualBox

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

Last change on this file since 67072 was 66494, checked in by vboxsync, 8 years ago

Storage: Get rid of duplicated code in the backends for unsupported features

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