VirtualBox

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

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

QCOW: Initialize the L2 cache always, fixes a crash if opening the image file fails

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