VirtualBox

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

Last change on this file since 77921 was 77921, checked in by vboxsync, 5 years ago

Storage/QCOW: Fix extracting offsets from the L1 and L2 table for v2 images and pplug a small memory leak when freeing the image

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