VirtualBox

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

Last change on this file since 77847 was 77232, checked in by vboxsync, 6 years ago

Storage/QED+QCOW: It is not allowed to mix RTStrDup, RTMemAlloc and RTStrFree, you must stick to one allocator type. Strings must be sanitized or coverted after loading.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 88.8 KB
Line 
1/* $Id: QCOW.cpp 77232 2019-02-09 01:55:37Z 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
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 RTStrFree(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 = RTStrAlloc(pImage->cbBackingFilename + 1); /* +1 for \0 terminator. */
1156 if (pImage->pszBackingFilename)
1157 {
1158 RT_BZERO(pImage->pszBackingFilename, pImage->cbBackingFilename + 1);
1159 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pImage->pStorage,
1160 pImage->offBackingFilename, pImage->pszBackingFilename,
1161 pImage->cbBackingFilename);
1162 if (RT_SUCCESS(rc))
1163 rc = RTStrValidateEncoding(pImage->pszBackingFilename);
1164 }
1165 else
1166 rc = VERR_NO_STR_MEMORY;
1167 }
1168
1169 if ( RT_SUCCESS(rc)
1170 && pImage->cbRefcountTable
1171 && pImage->offRefcountTable)
1172 {
1173 /* Load refcount table. */
1174 Assert(pImage->cRefcountTableEntries);
1175 pImage->paRefcountTable = (uint64_t *)RTMemAllocZ(pImage->cbRefcountTable);
1176 if (RT_LIKELY(pImage->paRefcountTable))
1177 {
1178 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pImage->pStorage,
1179 pImage->offRefcountTable, pImage->paRefcountTable,
1180 pImage->cbRefcountTable);
1181 if (RT_SUCCESS(rc))
1182 qcowTableConvertToHostEndianess(pImage->paRefcountTable,
1183 pImage->cRefcountTableEntries);
1184 else
1185 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS,
1186 N_("QCow: Reading refcount table of image '%s' failed"),
1187 pImage->pszFilename);
1188 }
1189 else
1190 rc = vdIfError(pImage->pIfError, VERR_NO_MEMORY, RT_SRC_POS,
1191 N_("QCow: Allocating memory for refcount table of image '%s' failed"),
1192 pImage->pszFilename);
1193 }
1194
1195 if (RT_SUCCESS(rc))
1196 {
1197 qcowTableMasksInit(pImage);
1198
1199 /* Allocate L1 table. */
1200 pImage->paL1Table = (uint64_t *)RTMemAllocZ(pImage->cbL1Table);
1201 if (pImage->paL1Table)
1202 {
1203 /* Read from the image. */
1204 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pImage->pStorage,
1205 pImage->offL1Table, pImage->paL1Table,
1206 pImage->cbL1Table);
1207 if (RT_SUCCESS(rc))
1208 qcowTableConvertToHostEndianess(pImage->paL1Table, pImage->cL1TableEntries);
1209 else
1210 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS,
1211 N_("QCow: Reading the L1 table for image '%s' failed"),
1212 pImage->pszFilename);
1213 }
1214 else
1215 rc = vdIfError(pImage->pIfError, VERR_NO_MEMORY, RT_SRC_POS,
1216 N_("QCow: Out of memory allocating L1 table for image '%s'"),
1217 pImage->pszFilename);
1218 }
1219 }
1220 else if (RT_SUCCESS(rc))
1221 rc = VERR_VD_GEN_INVALID_HEADER;
1222 }
1223 else if (RT_SUCCESS(rc))
1224 rc = VERR_VD_GEN_INVALID_HEADER;
1225 }
1226 /* else: Do NOT signal an appropriate error here, as the VD layer has the
1227 * choice of retrying the open if it failed. */
1228 }
1229 else
1230 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS,
1231 N_("Qcow: Creating the L2 table cache for image '%s' failed"),
1232 pImage->pszFilename);
1233
1234 if (RT_SUCCESS(rc))
1235 {
1236 PVDREGIONDESC pRegion = &pImage->RegionList.aRegions[0];
1237 pImage->RegionList.fFlags = 0;
1238 pImage->RegionList.cRegions = 1;
1239
1240 pRegion->offRegion = 0; /* Disk start. */
1241 pRegion->cbBlock = 512;
1242 pRegion->enmDataForm = VDREGIONDATAFORM_RAW;
1243 pRegion->enmMetadataForm = VDREGIONMETADATAFORM_NONE;
1244 pRegion->cbData = 512;
1245 pRegion->cbMetadata = 0;
1246 pRegion->cRegionBlocksOrBytes = pImage->cbSize;
1247 }
1248 else
1249 qcowFreeImage(pImage, false);
1250 return rc;
1251}
1252
1253/**
1254 * Internal: Create a qcow image.
1255 */
1256static int qcowCreateImage(PQCOWIMAGE pImage, uint64_t cbSize,
1257 unsigned uImageFlags, const char *pszComment,
1258 PCVDGEOMETRY pPCHSGeometry,
1259 PCVDGEOMETRY pLCHSGeometry, unsigned uOpenFlags,
1260 PVDINTERFACEPROGRESS pIfProgress,
1261 unsigned uPercentStart, unsigned uPercentSpan)
1262{
1263 RT_NOREF1(pszComment);
1264 int rc;
1265 int32_t fOpen;
1266
1267 if (!(uImageFlags & VD_IMAGE_FLAGS_FIXED))
1268 {
1269 rc = qcowL2TblCacheCreate(pImage);
1270 if (RT_SUCCESS(rc))
1271 {
1272 pImage->uOpenFlags = uOpenFlags & ~VD_OPEN_FLAGS_READONLY;
1273 pImage->uImageFlags = uImageFlags;
1274 pImage->PCHSGeometry = *pPCHSGeometry;
1275 pImage->LCHSGeometry = *pLCHSGeometry;
1276 pImage->pIfError = VDIfErrorGet(pImage->pVDIfsDisk);
1277 pImage->pIfIo = VDIfIoIntGet(pImage->pVDIfsImage);
1278 AssertPtrReturn(pImage->pIfIo, VERR_INVALID_PARAMETER);
1279
1280 /* Create image file. */
1281 fOpen = VDOpenFlagsToFileOpenFlags(pImage->uOpenFlags, true /* fCreate */);
1282 rc = vdIfIoIntFileOpen(pImage->pIfIo, pImage->pszFilename, fOpen, &pImage->pStorage);
1283 if (RT_SUCCESS(rc))
1284 {
1285 /* Init image state. */
1286 pImage->uVersion = 1; /* We create only version 1 images at the moment. */
1287 pImage->cbSize = cbSize;
1288 pImage->cbCluster = QCOW_CLUSTER_SIZE_DEFAULT;
1289 pImage->cbL2Table = qcowCluster2Byte(pImage, QCOW_L2_CLUSTERS_DEFAULT);
1290 pImage->cL2TableEntries = pImage->cbL2Table / sizeof(uint64_t);
1291 pImage->cL1TableEntries = cbSize / (pImage->cbCluster * pImage->cL2TableEntries);
1292 if (cbSize % (pImage->cbCluster * pImage->cL2TableEntries))
1293 pImage->cL1TableEntries++;
1294 pImage->cbL1Table = RT_ALIGN_64(pImage->cL1TableEntries * sizeof(uint64_t), pImage->cbCluster);
1295 pImage->offL1Table = QCOW_V1_HDR_SIZE;
1296 pImage->cbBackingFilename = 0;
1297 pImage->offBackingFilename = 0;
1298 pImage->offNextCluster = RT_ALIGN_64(QCOW_V1_HDR_SIZE + pImage->cbL1Table, pImage->cbCluster);
1299 qcowTableMasksInit(pImage);
1300
1301 /* Init L1 table. */
1302 pImage->paL1Table = (uint64_t *)RTMemAllocZ(pImage->cbL1Table);
1303 if (RT_LIKELY(pImage->paL1Table))
1304 {
1305 if (RT_SUCCESS(rc))
1306 vdIfProgress(pIfProgress, uPercentStart + uPercentSpan * 98 / 100);
1307
1308 rc = qcowFlushImage(pImage);
1309 if (RT_SUCCESS(rc))
1310 rc = vdIfIoIntFileSetSize(pImage->pIfIo, pImage->pStorage, pImage->offNextCluster);
1311 }
1312 else
1313 rc = vdIfError(pImage->pIfError, VERR_NO_MEMORY, RT_SRC_POS, N_("QCow: cannot allocate memory for L1 table of image '%s'"),
1314 pImage->pszFilename);
1315 }
1316 else
1317 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("QCow: cannot create image '%s'"), pImage->pszFilename);
1318 }
1319 else
1320 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("QCow: Failed to create L2 cache for image '%s'"),
1321 pImage->pszFilename);
1322 }
1323 else
1324 rc = vdIfError(pImage->pIfError, VERR_VD_INVALID_TYPE, RT_SRC_POS, N_("QCow: cannot create fixed image '%s'"), pImage->pszFilename);
1325
1326 if (RT_SUCCESS(rc))
1327 vdIfProgress(pIfProgress, uPercentStart + uPercentSpan);
1328
1329 if (RT_SUCCESS(rc))
1330 {
1331 PVDREGIONDESC pRegion = &pImage->RegionList.aRegions[0];
1332 pImage->RegionList.fFlags = 0;
1333 pImage->RegionList.cRegions = 1;
1334
1335 pRegion->offRegion = 0; /* Disk start. */
1336 pRegion->cbBlock = 512;
1337 pRegion->enmDataForm = VDREGIONDATAFORM_RAW;
1338 pRegion->enmMetadataForm = VDREGIONMETADATAFORM_NONE;
1339 pRegion->cbData = 512;
1340 pRegion->cbMetadata = 0;
1341 pRegion->cRegionBlocksOrBytes = pImage->cbSize;
1342 }
1343 else
1344 qcowFreeImage(pImage, rc != VERR_ALREADY_EXISTS);
1345 return rc;
1346}
1347
1348/**
1349 * Rollback anything done during async cluster allocation.
1350 *
1351 * @returns VBox status code.
1352 * @param pImage The image instance data.
1353 * @param pIoCtx The I/O context.
1354 * @param pClusterAlloc The cluster allocation to rollback.
1355 */
1356static int qcowAsyncClusterAllocRollback(PQCOWIMAGE pImage, PVDIOCTX pIoCtx, PQCOWCLUSTERASYNCALLOC pClusterAlloc)
1357{
1358 RT_NOREF1(pIoCtx);
1359 int rc = VINF_SUCCESS;
1360
1361 switch (pClusterAlloc->enmAllocState)
1362 {
1363 case QCOWCLUSTERASYNCALLOCSTATE_L2_ALLOC:
1364 case QCOWCLUSTERASYNCALLOCSTATE_L2_LINK:
1365 {
1366 /* Revert the L1 table entry */
1367 pImage->paL1Table[pClusterAlloc->idxL1] = 0;
1368 pImage->pL2TblAlloc = NULL;
1369
1370 /* Assumption right now is that the L1 table is not modified on storage if the link fails. */
1371 rc = vdIfIoIntFileSetSize(pImage->pIfIo, pImage->pStorage, pClusterAlloc->offNextClusterOld);
1372 qcowL2TblCacheEntryRelease(pClusterAlloc->pL2Entry); /* Release L2 cache entry. */
1373 Assert(!pClusterAlloc->pL2Entry->cRefs);
1374 qcowL2TblCacheEntryFree(pImage, pClusterAlloc->pL2Entry); /* Free it, it is not in the cache yet. */
1375 break;
1376 }
1377 case QCOWCLUSTERASYNCALLOCSTATE_USER_ALLOC:
1378 case QCOWCLUSTERASYNCALLOCSTATE_USER_LINK:
1379 {
1380 /* Assumption right now is that the L2 table is not modified if the link fails. */
1381 pClusterAlloc->pL2Entry->paL2Tbl[pClusterAlloc->idxL2] = 0;
1382 rc = vdIfIoIntFileSetSize(pImage->pIfIo, pImage->pStorage, pClusterAlloc->offNextClusterOld);
1383 qcowL2TblCacheEntryRelease(pClusterAlloc->pL2Entry); /* Release L2 cache entry. */
1384 break;
1385 }
1386 default:
1387 AssertMsgFailed(("Invalid cluster allocation state %d\n", pClusterAlloc->enmAllocState));
1388 rc = VERR_INVALID_STATE;
1389 }
1390
1391 RTMemFree(pClusterAlloc);
1392 return rc;
1393}
1394
1395/**
1396 * Updates the state of the async cluster allocation.
1397 *
1398 * @returns VBox status code.
1399 * @param pBackendData The opaque backend data.
1400 * @param pIoCtx I/O context associated with this request.
1401 * @param pvUser Opaque user data passed during a read/write request.
1402 * @param rcReq Status code for the completed request.
1403 */
1404static DECLCALLBACK(int) qcowAsyncClusterAllocUpdate(void *pBackendData, PVDIOCTX pIoCtx, void *pvUser, int rcReq)
1405{
1406 int rc = VINF_SUCCESS;
1407 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
1408 PQCOWCLUSTERASYNCALLOC pClusterAlloc = (PQCOWCLUSTERASYNCALLOC)pvUser;
1409
1410 if (RT_FAILURE(rcReq))
1411 return qcowAsyncClusterAllocRollback(pImage, pIoCtx, pClusterAlloc);
1412
1413 AssertPtr(pClusterAlloc->pL2Entry);
1414
1415 switch (pClusterAlloc->enmAllocState)
1416 {
1417 case QCOWCLUSTERASYNCALLOCSTATE_L2_ALLOC:
1418 {
1419 /* Update the link in the in memory L1 table now. */
1420 pImage->paL1Table[pClusterAlloc->idxL1] = pClusterAlloc->pL2Entry->offL2Tbl;
1421
1422 /* Update the link in the on disk L1 table now. */
1423 pClusterAlloc->enmAllocState = QCOWCLUSTERASYNCALLOCSTATE_L2_LINK;
1424 rc = qcowTblWrite(pImage, pIoCtx, pImage->offL1Table, pImage->paL1Table,
1425 pImage->cbL1Table, pImage->cL1TableEntries,
1426 qcowAsyncClusterAllocUpdate, pClusterAlloc);
1427 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
1428 break;
1429 else if (RT_FAILURE(rc))
1430 {
1431 /* Rollback. */
1432 qcowAsyncClusterAllocRollback(pImage, pIoCtx, pClusterAlloc);
1433 break;
1434 }
1435 /* Success, fall through. */
1436 }
1437 RT_FALL_THRU();
1438 case QCOWCLUSTERASYNCALLOCSTATE_L2_LINK:
1439 {
1440 /* L2 link updated in L1 , save L2 entry in cache and allocate new user data cluster. */
1441 uint64_t offData = qcowClusterAllocate(pImage, 1);
1442
1443 pImage->pL2TblAlloc = NULL;
1444 qcowL2TblCacheEntryInsert(pImage, pClusterAlloc->pL2Entry);
1445
1446 pClusterAlloc->enmAllocState = QCOWCLUSTERASYNCALLOCSTATE_USER_ALLOC;
1447 pClusterAlloc->offNextClusterOld = offData;
1448 pClusterAlloc->offClusterNew = offData;
1449
1450 /* Write data. */
1451 rc = vdIfIoIntFileWriteUser(pImage->pIfIo, pImage->pStorage,
1452 offData, pIoCtx, pClusterAlloc->cbToWrite,
1453 qcowAsyncClusterAllocUpdate, pClusterAlloc);
1454 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
1455 break;
1456 else if (RT_FAILURE(rc))
1457 {
1458 qcowAsyncClusterAllocRollback(pImage, pIoCtx, pClusterAlloc);
1459 RTMemFree(pClusterAlloc);
1460 break;
1461 }
1462 }
1463 RT_FALL_THRU();
1464 case QCOWCLUSTERASYNCALLOCSTATE_USER_ALLOC:
1465 {
1466 pClusterAlloc->enmAllocState = QCOWCLUSTERASYNCALLOCSTATE_USER_LINK;
1467 pClusterAlloc->pL2Entry->paL2Tbl[pClusterAlloc->idxL2] = pClusterAlloc->offClusterNew;
1468
1469 /* Link L2 table and update it. */
1470 rc = qcowTblWrite(pImage, pIoCtx, pImage->paL1Table[pClusterAlloc->idxL1],
1471 pClusterAlloc->pL2Entry->paL2Tbl,
1472 pImage->cbL2Table, pImage->cL2TableEntries,
1473 qcowAsyncClusterAllocUpdate, pClusterAlloc);
1474 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
1475 break;
1476 else if (RT_FAILURE(rc))
1477 {
1478 qcowAsyncClusterAllocRollback(pImage, pIoCtx, pClusterAlloc);
1479 RTMemFree(pClusterAlloc);
1480 break;
1481 }
1482 }
1483 RT_FALL_THRU();
1484 case QCOWCLUSTERASYNCALLOCSTATE_USER_LINK:
1485 {
1486 /* Everything done without errors, signal completion. */
1487 qcowL2TblCacheEntryRelease(pClusterAlloc->pL2Entry);
1488 RTMemFree(pClusterAlloc);
1489 rc = VINF_SUCCESS;
1490 break;
1491 }
1492 default:
1493 AssertMsgFailed(("Invalid async cluster allocation state %d\n",
1494 pClusterAlloc->enmAllocState));
1495 }
1496
1497 return rc;
1498}
1499
1500/** @copydoc VDIMAGEBACKEND::pfnProbe */
1501static DECLCALLBACK(int) qcowProbe(const char *pszFilename, PVDINTERFACE pVDIfsDisk,
1502 PVDINTERFACE pVDIfsImage, VDTYPE *penmType)
1503{
1504 RT_NOREF1(pVDIfsDisk);
1505 LogFlowFunc(("pszFilename=\"%s\" pVDIfsDisk=%#p pVDIfsImage=%#p\n", pszFilename, pVDIfsDisk, pVDIfsImage));
1506 PVDIOSTORAGE pStorage = NULL;
1507 uint64_t cbFile;
1508 int rc = VINF_SUCCESS;
1509
1510 /* Get I/O interface. */
1511 PVDINTERFACEIOINT pIfIo = VDIfIoIntGet(pVDIfsImage);
1512 AssertPtrReturn(pIfIo, VERR_INVALID_PARAMETER);
1513 AssertReturn((VALID_PTR(pszFilename) && *pszFilename), VERR_INVALID_PARAMETER);
1514
1515 /*
1516 * Open the file and read the footer.
1517 */
1518 rc = vdIfIoIntFileOpen(pIfIo, pszFilename,
1519 VDOpenFlagsToFileOpenFlags(VD_OPEN_FLAGS_READONLY,
1520 false /* fCreate */),
1521 &pStorage);
1522 if (RT_SUCCESS(rc))
1523 {
1524 rc = vdIfIoIntFileGetSize(pIfIo, pStorage, &cbFile);
1525 if ( RT_SUCCESS(rc)
1526 && cbFile > sizeof(QCowHeader))
1527 {
1528 QCowHeader Header;
1529
1530 rc = vdIfIoIntFileReadSync(pIfIo, pStorage, 0, &Header, sizeof(Header));
1531 if ( RT_SUCCESS(rc)
1532 && qcowHdrConvertToHostEndianess(&Header))
1533 *penmType = VDTYPE_HDD;
1534 else
1535 rc = VERR_VD_GEN_INVALID_HEADER;
1536 }
1537 else
1538 rc = VERR_VD_GEN_INVALID_HEADER;
1539 }
1540
1541 if (pStorage)
1542 vdIfIoIntFileClose(pIfIo, pStorage);
1543
1544 LogFlowFunc(("returns %Rrc\n", rc));
1545 return rc;
1546}
1547
1548/** @copydoc VDIMAGEBACKEND::pfnOpen */
1549static DECLCALLBACK(int) qcowOpen(const char *pszFilename, unsigned uOpenFlags,
1550 PVDINTERFACE pVDIfsDisk, PVDINTERFACE pVDIfsImage,
1551 VDTYPE enmType, void **ppBackendData)
1552{
1553 RT_NOREF1(enmType); /**< @todo r=klaus make use of the type info. */
1554
1555 LogFlowFunc(("pszFilename=\"%s\" uOpenFlags=%#x pVDIfsDisk=%#p pVDIfsImage=%#p enmType=%u ppBackendData=%#p\n",
1556 pszFilename, uOpenFlags, pVDIfsDisk, pVDIfsImage, enmType, ppBackendData));
1557 int rc;
1558
1559 /* Check open flags. All valid flags are supported. */
1560 AssertReturn(!(uOpenFlags & ~VD_OPEN_FLAGS_MASK), VERR_INVALID_PARAMETER);
1561 AssertReturn((VALID_PTR(pszFilename) && *pszFilename), VERR_INVALID_PARAMETER);
1562
1563 PQCOWIMAGE pImage = (PQCOWIMAGE)RTMemAllocZ(RT_UOFFSETOF(QCOWIMAGE, RegionList.aRegions[1]));
1564 if (RT_LIKELY(pImage))
1565 {
1566 pImage->pszFilename = pszFilename;
1567 pImage->pStorage = NULL;
1568 pImage->pVDIfsDisk = pVDIfsDisk;
1569 pImage->pVDIfsImage = pVDIfsImage;
1570
1571 rc = qcowOpenImage(pImage, uOpenFlags);
1572 if (RT_SUCCESS(rc))
1573 *ppBackendData = pImage;
1574 else
1575 RTMemFree(pImage);
1576 }
1577 else
1578 rc = VERR_NO_MEMORY;
1579
1580 LogFlowFunc(("returns %Rrc (pBackendData=%#p)\n", rc, *ppBackendData));
1581 return rc;
1582}
1583
1584/** @copydoc VDIMAGEBACKEND::pfnCreate */
1585static DECLCALLBACK(int) qcowCreate(const char *pszFilename, uint64_t cbSize,
1586 unsigned uImageFlags, const char *pszComment,
1587 PCVDGEOMETRY pPCHSGeometry, PCVDGEOMETRY pLCHSGeometry,
1588 PCRTUUID pUuid, unsigned uOpenFlags,
1589 unsigned uPercentStart, unsigned uPercentSpan,
1590 PVDINTERFACE pVDIfsDisk, PVDINTERFACE pVDIfsImage,
1591 PVDINTERFACE pVDIfsOperation, VDTYPE enmType,
1592 void **ppBackendData)
1593{
1594 RT_NOREF1(pUuid);
1595 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",
1596 pszFilename, cbSize, uImageFlags, pszComment, pPCHSGeometry, pLCHSGeometry, pUuid, uOpenFlags, uPercentStart, uPercentSpan, pVDIfsDisk, pVDIfsImage, pVDIfsOperation, enmType, ppBackendData));
1597 int rc;
1598
1599 /* Check the VD container type. */
1600 if (enmType != VDTYPE_HDD)
1601 return VERR_VD_INVALID_TYPE;
1602
1603 /* Check open flags. All valid flags are supported. */
1604 AssertReturn(!(uOpenFlags & ~VD_OPEN_FLAGS_MASK), VERR_INVALID_PARAMETER);
1605 AssertReturn( VALID_PTR(pszFilename)
1606 && *pszFilename
1607 && VALID_PTR(pPCHSGeometry)
1608 && VALID_PTR(pLCHSGeometry), VERR_INVALID_PARAMETER);
1609
1610 PQCOWIMAGE pImage = (PQCOWIMAGE)RTMemAllocZ(RT_UOFFSETOF(QCOWIMAGE, RegionList.aRegions[1]));
1611 if (RT_LIKELY(pImage))
1612 {
1613 PVDINTERFACEPROGRESS pIfProgress = VDIfProgressGet(pVDIfsOperation);
1614
1615 pImage->pszFilename = pszFilename;
1616 pImage->pStorage = NULL;
1617 pImage->pVDIfsDisk = pVDIfsDisk;
1618 pImage->pVDIfsImage = pVDIfsImage;
1619
1620 rc = qcowCreateImage(pImage, cbSize, uImageFlags, pszComment,
1621 pPCHSGeometry, pLCHSGeometry, uOpenFlags,
1622 pIfProgress, uPercentStart, uPercentSpan);
1623 if (RT_SUCCESS(rc))
1624 {
1625 /* So far the image is opened in read/write mode. Make sure the
1626 * image is opened in read-only mode if the caller requested that. */
1627 if (uOpenFlags & VD_OPEN_FLAGS_READONLY)
1628 {
1629 qcowFreeImage(pImage, false);
1630 rc = qcowOpenImage(pImage, uOpenFlags);
1631 }
1632
1633 if (RT_SUCCESS(rc))
1634 *ppBackendData = pImage;
1635 }
1636
1637 if (RT_FAILURE(rc))
1638 RTMemFree(pImage);
1639 }
1640 else
1641 rc = VERR_NO_MEMORY;
1642
1643 LogFlowFunc(("returns %Rrc (pBackendData=%#p)\n", rc, *ppBackendData));
1644 return rc;
1645}
1646
1647/** @copydoc VDIMAGEBACKEND::pfnRename */
1648static DECLCALLBACK(int) qcowRename(void *pBackendData, const char *pszFilename)
1649{
1650 LogFlowFunc(("pBackendData=%#p pszFilename=%#p\n", pBackendData, pszFilename));
1651 int rc = VINF_SUCCESS;
1652 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
1653
1654 /* Check arguments. */
1655 AssertReturn((pImage && pszFilename && *pszFilename), VERR_INVALID_PARAMETER);
1656
1657 /* Close the image. */
1658 rc = qcowFreeImage(pImage, false);
1659 if (RT_SUCCESS(rc))
1660 {
1661 /* Rename the file. */
1662 rc = vdIfIoIntFileMove(pImage->pIfIo, pImage->pszFilename, pszFilename, 0);
1663 if (RT_SUCCESS(rc))
1664 {
1665 /* Update pImage with the new information. */
1666 pImage->pszFilename = pszFilename;
1667
1668 /* Open the old image with new name. */
1669 rc = qcowOpenImage(pImage, pImage->uOpenFlags);
1670 }
1671 else
1672 {
1673 /* The move failed, try to reopen the original image. */
1674 int rc2 = qcowOpenImage(pImage, pImage->uOpenFlags);
1675 if (RT_FAILURE(rc2))
1676 rc = rc2;
1677 }
1678 }
1679
1680 LogFlowFunc(("returns %Rrc\n", rc));
1681 return rc;
1682}
1683
1684/** @copydoc VDIMAGEBACKEND::pfnClose */
1685static DECLCALLBACK(int) qcowClose(void *pBackendData, bool fDelete)
1686{
1687 LogFlowFunc(("pBackendData=%#p fDelete=%d\n", pBackendData, fDelete));
1688 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
1689
1690 int rc = qcowFreeImage(pImage, fDelete);
1691 RTMemFree(pImage);
1692
1693 LogFlowFunc(("returns %Rrc\n", rc));
1694 return rc;
1695}
1696
1697static DECLCALLBACK(int) qcowRead(void *pBackendData, uint64_t uOffset, size_t cbToRead,
1698 PVDIOCTX pIoCtx, size_t *pcbActuallyRead)
1699{
1700 LogFlowFunc(("pBackendData=%#p uOffset=%llu pIoCtx=%#p cbToRead=%zu pcbActuallyRead=%#p\n",
1701 pBackendData, uOffset, pIoCtx, cbToRead, pcbActuallyRead));
1702 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
1703 uint32_t offCluster = 0;
1704 uint32_t idxL1 = 0;
1705 uint32_t idxL2 = 0;
1706 uint64_t offFile = 0;
1707 int rc;
1708
1709 AssertPtr(pImage);
1710 Assert(uOffset % 512 == 0);
1711 Assert(cbToRead % 512 == 0);
1712 AssertReturn((VALID_PTR(pIoCtx) && cbToRead), VERR_INVALID_PARAMETER);
1713 AssertReturn(uOffset + cbToRead <= pImage->cbSize, VERR_INVALID_PARAMETER);
1714
1715 qcowConvertLogicalOffset(pImage, uOffset, &idxL1, &idxL2, &offCluster);
1716
1717 /* Clip read size to remain in the cluster. */
1718 cbToRead = RT_MIN(cbToRead, pImage->cbCluster - offCluster);
1719
1720 /* Get offset in image. */
1721 rc = qcowConvertToImageOffset(pImage, pIoCtx, idxL1, idxL2, offCluster, &offFile);
1722 if (RT_SUCCESS(rc))
1723 rc = vdIfIoIntFileReadUser(pImage->pIfIo, pImage->pStorage, offFile,
1724 pIoCtx, cbToRead);
1725
1726 if ( ( RT_SUCCESS(rc)
1727 || rc == VERR_VD_BLOCK_FREE
1728 || rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
1729 && pcbActuallyRead)
1730 *pcbActuallyRead = cbToRead;
1731
1732 LogFlowFunc(("returns %Rrc\n", rc));
1733 return rc;
1734}
1735
1736static DECLCALLBACK(int) qcowWrite(void *pBackendData, uint64_t uOffset, size_t cbToWrite,
1737 PVDIOCTX pIoCtx, size_t *pcbWriteProcess, size_t *pcbPreRead,
1738 size_t *pcbPostRead, unsigned fWrite)
1739{
1740 LogFlowFunc(("pBackendData=%#p uOffset=%llu pIoCtx=%#p cbToWrite=%zu pcbWriteProcess=%#p pcbPreRead=%#p pcbPostRead=%#p\n",
1741 pBackendData, uOffset, pIoCtx, cbToWrite, pcbWriteProcess, pcbPreRead, pcbPostRead));
1742 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
1743 uint32_t offCluster = 0;
1744 uint32_t idxL1 = 0;
1745 uint32_t idxL2 = 0;
1746 uint64_t offImage = 0;
1747 int rc = VINF_SUCCESS;
1748
1749 AssertPtr(pImage);
1750 Assert(!(uOffset % 512));
1751 Assert(!(cbToWrite % 512));
1752 AssertReturn((VALID_PTR(pIoCtx) && cbToWrite), VERR_INVALID_PARAMETER);
1753 AssertReturn(uOffset + cbToWrite <= pImage->cbSize, VERR_INVALID_PARAMETER);
1754
1755 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
1756 {
1757 /* Convert offset to L1, L2 index and cluster offset. */
1758 qcowConvertLogicalOffset(pImage, uOffset, &idxL1, &idxL2, &offCluster);
1759
1760 /* Clip write size to remain in the cluster. */
1761 cbToWrite = RT_MIN(cbToWrite, pImage->cbCluster - offCluster);
1762 Assert(!(cbToWrite % 512));
1763
1764 /* Get offset in image. */
1765 rc = qcowConvertToImageOffset(pImage, pIoCtx, idxL1, idxL2, offCluster, &offImage);
1766 if (RT_SUCCESS(rc))
1767 rc = vdIfIoIntFileWriteUser(pImage->pIfIo, pImage->pStorage,
1768 offImage, pIoCtx, cbToWrite, NULL, NULL);
1769 else if (rc == VERR_VD_BLOCK_FREE)
1770 {
1771 if ( cbToWrite == pImage->cbCluster
1772 && !(fWrite & VD_WRITE_NO_ALLOC))
1773 {
1774 PQCOWL2CACHEENTRY pL2Entry = NULL;
1775
1776 /* Full cluster write to previously unallocated cluster.
1777 * Allocate cluster and write data. */
1778 Assert(!offCluster);
1779
1780 do
1781 {
1782 /* Check if we have to allocate a new cluster for L2 tables. */
1783 if (!pImage->paL1Table[idxL1])
1784 {
1785 uint64_t offL2Tbl;
1786 PQCOWCLUSTERASYNCALLOC pL2ClusterAlloc = NULL;
1787
1788 /* Allocate new async cluster allocation state. */
1789 pL2ClusterAlloc = (PQCOWCLUSTERASYNCALLOC)RTMemAllocZ(sizeof(QCOWCLUSTERASYNCALLOC));
1790 if (RT_UNLIKELY(!pL2ClusterAlloc))
1791 {
1792 rc = VERR_NO_MEMORY;
1793 break;
1794 }
1795
1796 pL2Entry = qcowL2TblCacheEntryAlloc(pImage);
1797 if (!pL2Entry)
1798 {
1799 rc = VERR_NO_MEMORY;
1800 RTMemFree(pL2ClusterAlloc);
1801 break;
1802 }
1803
1804 offL2Tbl = qcowClusterAllocate(pImage, qcowByte2Cluster(pImage, pImage->cbL2Table));
1805 pL2Entry->offL2Tbl = offL2Tbl;
1806 memset(pL2Entry->paL2Tbl, 0, pImage->cbL2Table);
1807
1808 pL2ClusterAlloc->enmAllocState = QCOWCLUSTERASYNCALLOCSTATE_L2_ALLOC;
1809 pL2ClusterAlloc->offNextClusterOld = offL2Tbl;
1810 pL2ClusterAlloc->offClusterNew = offL2Tbl;
1811 pL2ClusterAlloc->idxL1 = idxL1;
1812 pL2ClusterAlloc->idxL2 = idxL2;
1813 pL2ClusterAlloc->cbToWrite = cbToWrite;
1814 pL2ClusterAlloc->pL2Entry = pL2Entry;
1815
1816 pImage->pL2TblAlloc = pL2Entry;
1817
1818 LogFlowFunc(("Allocating new L2 table at cluster offset %llu\n", offL2Tbl));
1819
1820 /*
1821 * Write the L2 table first and link to the L1 table afterwards.
1822 * If something unexpected happens the worst case which can happen
1823 * is a leak of some clusters.
1824 */
1825 rc = vdIfIoIntFileWriteMeta(pImage->pIfIo, pImage->pStorage,
1826 offL2Tbl, pL2Entry->paL2Tbl, pImage->cbL2Table, pIoCtx,
1827 qcowAsyncClusterAllocUpdate, pL2ClusterAlloc);
1828 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
1829 break;
1830 else if (RT_FAILURE(rc))
1831 {
1832 RTMemFree(pL2ClusterAlloc);
1833 qcowL2TblCacheEntryFree(pImage, pL2Entry);
1834 break;
1835 }
1836
1837 rc = qcowAsyncClusterAllocUpdate(pImage, pIoCtx, pL2ClusterAlloc, rc);
1838 }
1839 else
1840 {
1841 LogFlowFunc(("Fetching L2 table at cluster offset %llu\n", pImage->paL1Table[idxL1]));
1842
1843 rc = qcowL2TblCacheFetch(pImage, pIoCtx, pImage->paL1Table[idxL1],
1844 &pL2Entry);
1845 if (RT_SUCCESS(rc))
1846 {
1847 PQCOWCLUSTERASYNCALLOC pDataClusterAlloc = NULL;
1848
1849 /* Allocate new async cluster allocation state. */
1850 pDataClusterAlloc = (PQCOWCLUSTERASYNCALLOC)RTMemAllocZ(sizeof(QCOWCLUSTERASYNCALLOC));
1851 if (RT_UNLIKELY(!pDataClusterAlloc))
1852 {
1853 rc = VERR_NO_MEMORY;
1854 break;
1855 }
1856
1857 /* Allocate new cluster for the data. */
1858 uint64_t offData = qcowClusterAllocate(pImage, 1);
1859
1860 pDataClusterAlloc->enmAllocState = QCOWCLUSTERASYNCALLOCSTATE_USER_ALLOC;
1861 pDataClusterAlloc->offNextClusterOld = offData;
1862 pDataClusterAlloc->offClusterNew = offData;
1863 pDataClusterAlloc->idxL1 = idxL1;
1864 pDataClusterAlloc->idxL2 = idxL2;
1865 pDataClusterAlloc->cbToWrite = cbToWrite;
1866 pDataClusterAlloc->pL2Entry = pL2Entry;
1867
1868 /* Write data. */
1869 rc = vdIfIoIntFileWriteUser(pImage->pIfIo, pImage->pStorage,
1870 offData, pIoCtx, cbToWrite,
1871 qcowAsyncClusterAllocUpdate, pDataClusterAlloc);
1872 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
1873 break;
1874 else if (RT_FAILURE(rc))
1875 {
1876 RTMemFree(pDataClusterAlloc);
1877 break;
1878 }
1879
1880 rc = qcowAsyncClusterAllocUpdate(pImage, pIoCtx, pDataClusterAlloc, rc);
1881 }
1882 }
1883
1884 } while (0);
1885
1886 *pcbPreRead = 0;
1887 *pcbPostRead = 0;
1888 }
1889 else
1890 {
1891 /* Trying to do a partial write to an unallocated cluster. Don't do
1892 * anything except letting the upper layer know what to do. */
1893 *pcbPreRead = offCluster;
1894 *pcbPostRead = pImage->cbCluster - cbToWrite - *pcbPreRead;
1895 }
1896 }
1897
1898 if (pcbWriteProcess)
1899 *pcbWriteProcess = cbToWrite;
1900 }
1901 else
1902 rc = VERR_VD_IMAGE_READ_ONLY;
1903
1904 LogFlowFunc(("returns %Rrc\n", rc));
1905 return rc;
1906}
1907
1908static DECLCALLBACK(int) qcowFlush(void *pBackendData, PVDIOCTX pIoCtx)
1909{
1910 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
1911 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
1912 int rc = VINF_SUCCESS;
1913
1914 AssertPtr(pImage);
1915 AssertPtrReturn(pIoCtx, VERR_INVALID_PARAMETER);
1916
1917 if ( pImage->pStorage
1918 && !(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
1919 {
1920 QCowHeader Header;
1921
1922 rc = qcowTblWrite(pImage, pIoCtx, pImage->offL1Table, pImage->paL1Table,
1923 pImage->cbL1Table, pImage->cL1TableEntries, NULL, NULL);
1924 if (RT_SUCCESS(rc) || rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
1925 {
1926 /* Write header. */
1927 size_t cbHeader = 0;
1928 qcowHdrConvertFromHostEndianess(pImage, &Header, &cbHeader);
1929 rc = vdIfIoIntFileWriteMeta(pImage->pIfIo, pImage->pStorage,
1930 0, &Header, cbHeader,
1931 pIoCtx, NULL, NULL);
1932 if (RT_SUCCESS(rc) || rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
1933 rc = vdIfIoIntFileFlush(pImage->pIfIo, pImage->pStorage,
1934 pIoCtx, NULL, NULL);
1935 }
1936 }
1937
1938 LogFlowFunc(("returns %Rrc\n", rc));
1939 return rc;
1940}
1941
1942/** @copydoc VDIMAGEBACKEND::pfnGetVersion */
1943static DECLCALLBACK(unsigned) qcowGetVersion(void *pBackendData)
1944{
1945 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
1946 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
1947
1948 AssertPtrReturn(pImage, 0);
1949
1950 return pImage->uVersion;
1951}
1952
1953/** @copydoc VDIMAGEBACKEND::pfnGetFileSize */
1954static DECLCALLBACK(uint64_t) qcowGetFileSize(void *pBackendData)
1955{
1956 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
1957 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
1958 uint64_t cb = 0;
1959
1960 AssertPtrReturn(pImage, 0);
1961
1962 uint64_t cbFile;
1963 if (pImage->pStorage)
1964 {
1965 int rc = vdIfIoIntFileGetSize(pImage->pIfIo, pImage->pStorage, &cbFile);
1966 if (RT_SUCCESS(rc))
1967 cb += cbFile;
1968 }
1969
1970 LogFlowFunc(("returns %lld\n", cb));
1971 return cb;
1972}
1973
1974/** @copydoc VDIMAGEBACKEND::pfnGetPCHSGeometry */
1975static DECLCALLBACK(int) qcowGetPCHSGeometry(void *pBackendData, PVDGEOMETRY pPCHSGeometry)
1976{
1977 LogFlowFunc(("pBackendData=%#p pPCHSGeometry=%#p\n", pBackendData, pPCHSGeometry));
1978 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
1979 int rc = VINF_SUCCESS;
1980
1981 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
1982
1983 if (pImage->PCHSGeometry.cCylinders)
1984 *pPCHSGeometry = pImage->PCHSGeometry;
1985 else
1986 rc = VERR_VD_GEOMETRY_NOT_SET;
1987
1988 LogFlowFunc(("returns %Rrc (PCHS=%u/%u/%u)\n", rc, pPCHSGeometry->cCylinders, pPCHSGeometry->cHeads, pPCHSGeometry->cSectors));
1989 return rc;
1990}
1991
1992/** @copydoc VDIMAGEBACKEND::pfnSetPCHSGeometry */
1993static DECLCALLBACK(int) qcowSetPCHSGeometry(void *pBackendData, PCVDGEOMETRY pPCHSGeometry)
1994{
1995 LogFlowFunc(("pBackendData=%#p pPCHSGeometry=%#p PCHS=%u/%u/%u\n",
1996 pBackendData, pPCHSGeometry, pPCHSGeometry->cCylinders, pPCHSGeometry->cHeads, pPCHSGeometry->cSectors));
1997 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
1998 int rc = VINF_SUCCESS;
1999
2000 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
2001
2002 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
2003 rc = VERR_VD_IMAGE_READ_ONLY;
2004 else
2005 pImage->PCHSGeometry = *pPCHSGeometry;
2006
2007 LogFlowFunc(("returns %Rrc\n", rc));
2008 return rc;
2009}
2010
2011/** @copydoc VDIMAGEBACKEND::pfnGetLCHSGeometry */
2012static DECLCALLBACK(int) qcowGetLCHSGeometry(void *pBackendData, PVDGEOMETRY pLCHSGeometry)
2013{
2014 LogFlowFunc(("pBackendData=%#p pLCHSGeometry=%#p\n", pBackendData, pLCHSGeometry));
2015 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2016 int rc = VINF_SUCCESS;
2017
2018 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
2019
2020 if (pImage->LCHSGeometry.cCylinders)
2021 *pLCHSGeometry = pImage->LCHSGeometry;
2022 else
2023 rc = VERR_VD_GEOMETRY_NOT_SET;
2024
2025 LogFlowFunc(("returns %Rrc (LCHS=%u/%u/%u)\n", rc, pLCHSGeometry->cCylinders,
2026 pLCHSGeometry->cHeads, pLCHSGeometry->cSectors));
2027 return rc;
2028}
2029
2030/** @copydoc VDIMAGEBACKEND::pfnSetLCHSGeometry */
2031static DECLCALLBACK(int) qcowSetLCHSGeometry(void *pBackendData, PCVDGEOMETRY pLCHSGeometry)
2032{
2033 LogFlowFunc(("pBackendData=%#p pLCHSGeometry=%#p LCHS=%u/%u/%u\n", pBackendData,
2034 pLCHSGeometry, pLCHSGeometry->cCylinders, pLCHSGeometry->cHeads, pLCHSGeometry->cSectors));
2035 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2036 int rc = VINF_SUCCESS;
2037
2038 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
2039
2040 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
2041 rc = VERR_VD_IMAGE_READ_ONLY;
2042 else
2043 pImage->LCHSGeometry = *pLCHSGeometry;
2044
2045 LogFlowFunc(("returns %Rrc\n", rc));
2046 return rc;
2047}
2048
2049/** @copydoc VDIMAGEBACKEND::pfnQueryRegions */
2050static DECLCALLBACK(int) qcowQueryRegions(void *pBackendData, PCVDREGIONLIST *ppRegionList)
2051{
2052 LogFlowFunc(("pBackendData=%#p ppRegionList=%#p\n", pBackendData, ppRegionList));
2053 PQCOWIMAGE pThis = (PQCOWIMAGE)pBackendData;
2054
2055 AssertPtrReturn(pThis, VERR_VD_NOT_OPENED);
2056
2057 *ppRegionList = &pThis->RegionList;
2058 LogFlowFunc(("returns %Rrc\n", VINF_SUCCESS));
2059 return VINF_SUCCESS;
2060}
2061
2062/** @copydoc VDIMAGEBACKEND::pfnRegionListRelease */
2063static DECLCALLBACK(void) qcowRegionListRelease(void *pBackendData, PCVDREGIONLIST pRegionList)
2064{
2065 RT_NOREF1(pRegionList);
2066 LogFlowFunc(("pBackendData=%#p pRegionList=%#p\n", pBackendData, pRegionList));
2067 PQCOWIMAGE pThis = (PQCOWIMAGE)pBackendData;
2068 AssertPtr(pThis); RT_NOREF(pThis);
2069
2070 /* Nothing to do here. */
2071}
2072
2073/** @copydoc VDIMAGEBACKEND::pfnGetImageFlags */
2074static DECLCALLBACK(unsigned) qcowGetImageFlags(void *pBackendData)
2075{
2076 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
2077 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2078
2079 AssertPtrReturn(pImage, 0);
2080
2081 LogFlowFunc(("returns %#x\n", pImage->uImageFlags));
2082 return pImage->uImageFlags;
2083}
2084
2085/** @copydoc VDIMAGEBACKEND::pfnGetOpenFlags */
2086static DECLCALLBACK(unsigned) qcowGetOpenFlags(void *pBackendData)
2087{
2088 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
2089 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2090
2091 AssertPtrReturn(pImage, 0);
2092
2093 LogFlowFunc(("returns %#x\n", pImage->uOpenFlags));
2094 return pImage->uOpenFlags;
2095}
2096
2097/** @copydoc VDIMAGEBACKEND::pfnSetOpenFlags */
2098static DECLCALLBACK(int) qcowSetOpenFlags(void *pBackendData, unsigned uOpenFlags)
2099{
2100 LogFlowFunc(("pBackendData=%#p\n uOpenFlags=%#x", pBackendData, uOpenFlags));
2101 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2102 int rc = VINF_SUCCESS;
2103
2104 /* Image must be opened and the new flags must be valid. */
2105 if (!pImage || (uOpenFlags & ~( VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_INFO
2106 | VD_OPEN_FLAGS_ASYNC_IO | VD_OPEN_FLAGS_SHAREABLE
2107 | VD_OPEN_FLAGS_SEQUENTIAL | VD_OPEN_FLAGS_SKIP_CONSISTENCY_CHECKS)))
2108 rc = VERR_INVALID_PARAMETER;
2109 else
2110 {
2111 /* Implement this operation via reopening the image. */
2112 rc = qcowFreeImage(pImage, false);
2113 if (RT_SUCCESS(rc))
2114 rc = qcowOpenImage(pImage, uOpenFlags);
2115 }
2116
2117 LogFlowFunc(("returns %Rrc\n", rc));
2118 return rc;
2119}
2120
2121/** @copydoc VDIMAGEBACKEND::pfnGetComment */
2122VD_BACKEND_CALLBACK_GET_COMMENT_DEF_NOT_SUPPORTED(qcowGetComment);
2123
2124/** @copydoc VDIMAGEBACKEND::pfnSetComment */
2125VD_BACKEND_CALLBACK_SET_COMMENT_DEF_NOT_SUPPORTED(qcowSetComment, PQCOWIMAGE);
2126
2127/** @copydoc VDIMAGEBACKEND::pfnGetUuid */
2128VD_BACKEND_CALLBACK_GET_UUID_DEF_NOT_SUPPORTED(qcowGetUuid);
2129
2130/** @copydoc VDIMAGEBACKEND::pfnSetUuid */
2131VD_BACKEND_CALLBACK_SET_UUID_DEF_NOT_SUPPORTED(qcowSetUuid, PQCOWIMAGE);
2132
2133/** @copydoc VDIMAGEBACKEND::pfnGetModificationUuid */
2134VD_BACKEND_CALLBACK_GET_UUID_DEF_NOT_SUPPORTED(qcowGetModificationUuid);
2135
2136/** @copydoc VDIMAGEBACKEND::pfnSetModificationUuid */
2137VD_BACKEND_CALLBACK_SET_UUID_DEF_NOT_SUPPORTED(qcowSetModificationUuid, PQCOWIMAGE);
2138
2139/** @copydoc VDIMAGEBACKEND::pfnGetParentUuid */
2140VD_BACKEND_CALLBACK_GET_UUID_DEF_NOT_SUPPORTED(qcowGetParentUuid);
2141
2142/** @copydoc VDIMAGEBACKEND::pfnSetParentUuid */
2143VD_BACKEND_CALLBACK_SET_UUID_DEF_NOT_SUPPORTED(qcowSetParentUuid, PQCOWIMAGE);
2144
2145/** @copydoc VDIMAGEBACKEND::pfnGetParentModificationUuid */
2146VD_BACKEND_CALLBACK_GET_UUID_DEF_NOT_SUPPORTED(qcowGetParentModificationUuid);
2147
2148/** @copydoc VDIMAGEBACKEND::pfnSetParentModificationUuid */
2149VD_BACKEND_CALLBACK_SET_UUID_DEF_NOT_SUPPORTED(qcowSetParentModificationUuid, PQCOWIMAGE);
2150
2151/** @copydoc VDIMAGEBACKEND::pfnDump */
2152static DECLCALLBACK(void) qcowDump(void *pBackendData)
2153{
2154 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2155
2156 AssertPtrReturnVoid(pImage);
2157 vdIfErrorMessage(pImage->pIfError, "Header: Geometry PCHS=%u/%u/%u LCHS=%u/%u/%u cbSector=%llu\n",
2158 pImage->PCHSGeometry.cCylinders, pImage->PCHSGeometry.cHeads, pImage->PCHSGeometry.cSectors,
2159 pImage->LCHSGeometry.cCylinders, pImage->LCHSGeometry.cHeads, pImage->LCHSGeometry.cSectors,
2160 pImage->cbSize / 512);
2161}
2162
2163/** @copydoc VDIMAGEBACKEND::pfnGetParentFilename */
2164static DECLCALLBACK(int) qcowGetParentFilename(void *pBackendData, char **ppszParentFilename)
2165{
2166 int rc = VINF_SUCCESS;
2167 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2168
2169 AssertPtr(pImage);
2170 if (pImage)
2171 if (pImage->pszBackingFilename)
2172 *ppszParentFilename = RTStrDup(pImage->pszBackingFilename);
2173 else
2174 rc = VERR_NOT_SUPPORTED;
2175 else
2176 rc = VERR_VD_NOT_OPENED;
2177
2178 LogFlowFunc(("returns %Rrc\n", rc));
2179 return rc;
2180}
2181
2182/** @copydoc VDIMAGEBACKEND::pfnSetParentFilename */
2183static DECLCALLBACK(int) qcowSetParentFilename(void *pBackendData, const char *pszParentFilename)
2184{
2185 int rc = VINF_SUCCESS;
2186 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2187
2188 AssertPtr(pImage);
2189 if (pImage)
2190 {
2191 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
2192 rc = VERR_VD_IMAGE_READ_ONLY;
2193 else if ( pImage->pszBackingFilename
2194 && (strlen(pszParentFilename) > pImage->cbBackingFilename))
2195 rc = VERR_NOT_SUPPORTED; /* The new filename is longer than the old one. */
2196 else
2197 {
2198 if (pImage->pszBackingFilename)
2199 RTStrFree(pImage->pszBackingFilename);
2200 pImage->pszBackingFilename = RTStrDup(pszParentFilename);
2201 if (!pImage->pszBackingFilename)
2202 rc = VERR_NO_STR_MEMORY;
2203 else
2204 {
2205 if (!pImage->offBackingFilename)
2206 {
2207 /* Allocate new cluster. */
2208 uint64_t offData = qcowClusterAllocate(pImage, 1);
2209
2210 Assert((offData & UINT32_MAX) == offData);
2211 pImage->offBackingFilename = (uint32_t)offData;
2212 pImage->cbBackingFilename = (uint32_t)strlen(pszParentFilename);
2213 rc = vdIfIoIntFileSetSize(pImage->pIfIo, pImage->pStorage,
2214 offData + pImage->cbCluster);
2215 }
2216
2217 if (RT_SUCCESS(rc))
2218 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pImage->pStorage,
2219 pImage->offBackingFilename,
2220 pImage->pszBackingFilename,
2221 strlen(pImage->pszBackingFilename));
2222 }
2223 }
2224 }
2225 else
2226 rc = VERR_VD_NOT_OPENED;
2227
2228 LogFlowFunc(("returns %Rrc\n", rc));
2229 return rc;
2230}
2231
2232
2233
2234const VDIMAGEBACKEND g_QCowBackend =
2235{
2236 /* u32Version */
2237 VD_IMGBACKEND_VERSION,
2238 /* pszBackendName */
2239 "QCOW",
2240 /* uBackendCaps */
2241 VD_CAP_FILE | VD_CAP_VFS | VD_CAP_CREATE_DYNAMIC | VD_CAP_DIFF | VD_CAP_ASYNC,
2242 /* paFileExtensions */
2243 s_aQCowFileExtensions,
2244 /* paConfigInfo */
2245 NULL,
2246 /* pfnProbe */
2247 qcowProbe,
2248 /* pfnOpen */
2249 qcowOpen,
2250 /* pfnCreate */
2251 qcowCreate,
2252 /* pfnRename */
2253 qcowRename,
2254 /* pfnClose */
2255 qcowClose,
2256 /* pfnRead */
2257 qcowRead,
2258 /* pfnWrite */
2259 qcowWrite,
2260 /* pfnFlush */
2261 qcowFlush,
2262 /* pfnDiscard */
2263 NULL,
2264 /* pfnGetVersion */
2265 qcowGetVersion,
2266 /* pfnGetFileSize */
2267 qcowGetFileSize,
2268 /* pfnGetPCHSGeometry */
2269 qcowGetPCHSGeometry,
2270 /* pfnSetPCHSGeometry */
2271 qcowSetPCHSGeometry,
2272 /* pfnGetLCHSGeometry */
2273 qcowGetLCHSGeometry,
2274 /* pfnSetLCHSGeometry */
2275 qcowSetLCHSGeometry,
2276 /* pfnQueryRegions */
2277 qcowQueryRegions,
2278 /* pfnRegionListRelease */
2279 qcowRegionListRelease,
2280 /* pfnGetImageFlags */
2281 qcowGetImageFlags,
2282 /* pfnGetOpenFlags */
2283 qcowGetOpenFlags,
2284 /* pfnSetOpenFlags */
2285 qcowSetOpenFlags,
2286 /* pfnGetComment */
2287 qcowGetComment,
2288 /* pfnSetComment */
2289 qcowSetComment,
2290 /* pfnGetUuid */
2291 qcowGetUuid,
2292 /* pfnSetUuid */
2293 qcowSetUuid,
2294 /* pfnGetModificationUuid */
2295 qcowGetModificationUuid,
2296 /* pfnSetModificationUuid */
2297 qcowSetModificationUuid,
2298 /* pfnGetParentUuid */
2299 qcowGetParentUuid,
2300 /* pfnSetParentUuid */
2301 qcowSetParentUuid,
2302 /* pfnGetParentModificationUuid */
2303 qcowGetParentModificationUuid,
2304 /* pfnSetParentModificationUuid */
2305 qcowSetParentModificationUuid,
2306 /* pfnDump */
2307 qcowDump,
2308 /* pfnGetTimestamp */
2309 NULL,
2310 /* pfnGetParentTimestamp */
2311 NULL,
2312 /* pfnSetParentTimestamp */
2313 NULL,
2314 /* pfnGetParentFilename */
2315 qcowGetParentFilename,
2316 /* pfnSetParentFilename */
2317 qcowSetParentFilename,
2318 /* pfnComposeLocation */
2319 genericFileComposeLocation,
2320 /* pfnComposeName */
2321 genericFileComposeName,
2322 /* pfnCompact */
2323 NULL,
2324 /* pfnResize */
2325 NULL,
2326 /* pfnRepair */
2327 NULL,
2328 /* pfnTraverseMetadata */
2329 NULL,
2330 /* u32VersionEnd */
2331 VD_IMGBACKEND_VERSION
2332};
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