VirtualBox

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

Last change on this file since 56918 was 56862, checked in by vboxsync, 10 years ago

Storage/QCOW: Missing break, found by Fortify

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 85.2 KB
Line 
1/* $Id: QCOW.cpp 56862 2015-07-08 12:44:33Z vboxsync $ */
2/** @file
3 * QCOW - QCOW Disk image.
4 */
5
6/*
7 * Copyright (C) 2011-2015 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 break;
1314 }
1315 case QCOWCLUSTERASYNCALLOCSTATE_USER_ALLOC:
1316 case QCOWCLUSTERASYNCALLOCSTATE_USER_LINK:
1317 {
1318 /* Assumption right now is that the L2 table is not modified if the link fails. */
1319 rc = vdIfIoIntFileSetSize(pImage->pIfIo, pImage->pStorage, pClusterAlloc->offNextClusterOld);
1320 qcowL2TblCacheEntryRelease(pClusterAlloc->pL2Entry); /* Release L2 cache entry. */
1321 break;
1322 }
1323 default:
1324 AssertMsgFailed(("Invalid cluster allocation state %d\n", pClusterAlloc->enmAllocState));
1325 rc = VERR_INVALID_STATE;
1326 }
1327
1328 RTMemFree(pClusterAlloc);
1329 return rc;
1330}
1331
1332/**
1333 * Updates the state of the async cluster allocation.
1334 *
1335 * @returns VBox status code.
1336 * @param pBackendData The opaque backend data.
1337 * @param pIoCtx I/O context associated with this request.
1338 * @param pvUser Opaque user data passed during a read/write request.
1339 * @param rcReq Status code for the completed request.
1340 */
1341static DECLCALLBACK(int) qcowAsyncClusterAllocUpdate(void *pBackendData, PVDIOCTX pIoCtx, void *pvUser, int rcReq)
1342{
1343 int rc = VINF_SUCCESS;
1344 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
1345 PQCOWCLUSTERASYNCALLOC pClusterAlloc = (PQCOWCLUSTERASYNCALLOC)pvUser;
1346
1347 if (RT_FAILURE(rcReq))
1348 return qcowAsyncClusterAllocRollback(pImage, pIoCtx, pClusterAlloc);
1349
1350 AssertPtr(pClusterAlloc->pL2Entry);
1351
1352 switch (pClusterAlloc->enmAllocState)
1353 {
1354 case QCOWCLUSTERASYNCALLOCSTATE_L2_ALLOC:
1355 {
1356 uint64_t offUpdateLe = RT_H2BE_U64(pClusterAlloc->pL2Entry->offL2Tbl);
1357
1358 /* Update the link in the on disk L1 table now. */
1359 pClusterAlloc->enmAllocState = QCOWCLUSTERASYNCALLOCSTATE_L2_LINK;
1360 rc = vdIfIoIntFileWriteMeta(pImage->pIfIo, pImage->pStorage,
1361 pImage->offL1Table + pClusterAlloc->idxL1*sizeof(uint64_t),
1362 &offUpdateLe, sizeof(uint64_t), pIoCtx,
1363 qcowAsyncClusterAllocUpdate, pClusterAlloc);
1364 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
1365 break;
1366 else if (RT_FAILURE(rc))
1367 {
1368 /* Rollback. */
1369 qcowAsyncClusterAllocRollback(pImage, pIoCtx, pClusterAlloc);
1370 break;
1371 }
1372 /* Success, fall through. */
1373 }
1374 case QCOWCLUSTERASYNCALLOCSTATE_L2_LINK:
1375 {
1376 /* L2 link updated in L1 , save L2 entry in cache and allocate new user data cluster. */
1377 uint64_t offData = qcowClusterAllocate(pImage, 1);
1378
1379 /* Update the link in the in memory L1 table now. */
1380 pImage->paL1Table[pClusterAlloc->idxL1] = pClusterAlloc->pL2Entry->offL2Tbl;
1381 qcowL2TblCacheEntryInsert(pImage, pClusterAlloc->pL2Entry);
1382
1383 pClusterAlloc->enmAllocState = QCOWCLUSTERASYNCALLOCSTATE_USER_ALLOC;
1384 pClusterAlloc->offNextClusterOld = offData;
1385 pClusterAlloc->offClusterNew = offData;
1386
1387 /* Write data. */
1388 rc = vdIfIoIntFileWriteUser(pImage->pIfIo, pImage->pStorage,
1389 offData, pIoCtx, pClusterAlloc->cbToWrite,
1390 qcowAsyncClusterAllocUpdate, pClusterAlloc);
1391 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
1392 break;
1393 else if (RT_FAILURE(rc))
1394 {
1395 qcowAsyncClusterAllocRollback(pImage, pIoCtx, pClusterAlloc);
1396 RTMemFree(pClusterAlloc);
1397 break;
1398 }
1399 }
1400 case QCOWCLUSTERASYNCALLOCSTATE_USER_ALLOC:
1401 {
1402 uint64_t offUpdateLe = RT_H2BE_U64(pClusterAlloc->offClusterNew);
1403
1404 pClusterAlloc->enmAllocState = QCOWCLUSTERASYNCALLOCSTATE_USER_LINK;
1405
1406 /* Link L2 table and update it. */
1407 rc = vdIfIoIntFileWriteMeta(pImage->pIfIo, pImage->pStorage,
1408 pImage->paL1Table[pClusterAlloc->idxL1] + pClusterAlloc->idxL2*sizeof(uint64_t),
1409 &offUpdateLe, sizeof(uint64_t), pIoCtx,
1410 qcowAsyncClusterAllocUpdate, pClusterAlloc);
1411 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
1412 break;
1413 else if (RT_FAILURE(rc))
1414 {
1415 qcowAsyncClusterAllocRollback(pImage, pIoCtx, pClusterAlloc);
1416 RTMemFree(pClusterAlloc);
1417 break;
1418 }
1419 }
1420 case QCOWCLUSTERASYNCALLOCSTATE_USER_LINK:
1421 {
1422 /* Everything done without errors, signal completion. */
1423 pClusterAlloc->pL2Entry->paL2Tbl[pClusterAlloc->idxL2] = pClusterAlloc->offClusterNew;
1424 qcowL2TblCacheEntryRelease(pClusterAlloc->pL2Entry);
1425 RTMemFree(pClusterAlloc);
1426 rc = VINF_SUCCESS;
1427 break;
1428 }
1429 default:
1430 AssertMsgFailed(("Invalid async cluster allocation state %d\n",
1431 pClusterAlloc->enmAllocState));
1432 }
1433
1434 return rc;
1435}
1436
1437/** @copydoc VBOXHDDBACKEND::pfnCheckIfValid */
1438static int qcowCheckIfValid(const char *pszFilename, PVDINTERFACE pVDIfsDisk,
1439 PVDINTERFACE pVDIfsImage, VDTYPE *penmType)
1440{
1441 LogFlowFunc(("pszFilename=\"%s\" pVDIfsDisk=%#p pVDIfsImage=%#p\n", pszFilename, pVDIfsDisk, pVDIfsImage));
1442 PVDIOSTORAGE pStorage = NULL;
1443 uint64_t cbFile;
1444 int rc = VINF_SUCCESS;
1445
1446 /* Get I/O interface. */
1447 PVDINTERFACEIOINT pIfIo = VDIfIoIntGet(pVDIfsImage);
1448 AssertPtrReturn(pIfIo, VERR_INVALID_PARAMETER);
1449
1450 if ( !VALID_PTR(pszFilename)
1451 || !*pszFilename)
1452 {
1453 rc = VERR_INVALID_PARAMETER;
1454 goto out;
1455 }
1456
1457 /*
1458 * Open the file and read the footer.
1459 */
1460 rc = vdIfIoIntFileOpen(pIfIo, pszFilename,
1461 VDOpenFlagsToFileOpenFlags(VD_OPEN_FLAGS_READONLY,
1462 false /* fCreate */),
1463 &pStorage);
1464 if (RT_SUCCESS(rc))
1465 rc = vdIfIoIntFileGetSize(pIfIo, pStorage, &cbFile);
1466
1467 if ( RT_SUCCESS(rc)
1468 && cbFile > sizeof(QCowHeader))
1469 {
1470 QCowHeader Header;
1471
1472 rc = vdIfIoIntFileReadSync(pIfIo, pStorage, 0, &Header, sizeof(Header));
1473 if ( RT_SUCCESS(rc)
1474 && qcowHdrConvertToHostEndianess(&Header))
1475 {
1476 *penmType = VDTYPE_HDD;
1477 rc = VINF_SUCCESS;
1478 }
1479 else
1480 rc = VERR_VD_GEN_INVALID_HEADER;
1481 }
1482 else
1483 rc = VERR_VD_GEN_INVALID_HEADER;
1484
1485 if (pStorage)
1486 vdIfIoIntFileClose(pIfIo, pStorage);
1487
1488out:
1489 LogFlowFunc(("returns %Rrc\n", rc));
1490 return rc;
1491}
1492
1493/** @copydoc VBOXHDDBACKEND::pfnOpen */
1494static int qcowOpen(const char *pszFilename, unsigned uOpenFlags,
1495 PVDINTERFACE pVDIfsDisk, PVDINTERFACE pVDIfsImage,
1496 VDTYPE enmType, void **ppBackendData)
1497{
1498 LogFlowFunc(("pszFilename=\"%s\" uOpenFlags=%#x pVDIfsDisk=%#p pVDIfsImage=%#p enmType=%u ppBackendData=%#p\n", pszFilename, uOpenFlags, pVDIfsDisk, pVDIfsImage, enmType, ppBackendData));
1499 int rc;
1500 PQCOWIMAGE pImage;
1501
1502 NOREF(enmType); /**< @todo r=klaus make use of the type info. */
1503
1504 /* Check open flags. All valid flags are supported. */
1505 if (uOpenFlags & ~VD_OPEN_FLAGS_MASK)
1506 {
1507 rc = VERR_INVALID_PARAMETER;
1508 goto out;
1509 }
1510
1511 /* Check remaining arguments. */
1512 if ( !VALID_PTR(pszFilename)
1513 || !*pszFilename)
1514 {
1515 rc = VERR_INVALID_PARAMETER;
1516 goto out;
1517 }
1518
1519
1520 pImage = (PQCOWIMAGE)RTMemAllocZ(sizeof(QCOWIMAGE));
1521 if (!pImage)
1522 {
1523 rc = VERR_NO_MEMORY;
1524 goto out;
1525 }
1526 pImage->pszFilename = pszFilename;
1527 pImage->pStorage = NULL;
1528 pImage->pVDIfsDisk = pVDIfsDisk;
1529 pImage->pVDIfsImage = pVDIfsImage;
1530
1531 rc = qcowOpenImage(pImage, uOpenFlags);
1532 if (RT_SUCCESS(rc))
1533 *ppBackendData = pImage;
1534 else
1535 RTMemFree(pImage);
1536
1537out:
1538 LogFlowFunc(("returns %Rrc (pBackendData=%#p)\n", rc, *ppBackendData));
1539 return rc;
1540}
1541
1542/** @copydoc VBOXHDDBACKEND::pfnCreate */
1543static int qcowCreate(const char *pszFilename, uint64_t cbSize,
1544 unsigned uImageFlags, const char *pszComment,
1545 PCVDGEOMETRY pPCHSGeometry, PCVDGEOMETRY pLCHSGeometry,
1546 PCRTUUID pUuid, unsigned uOpenFlags,
1547 unsigned uPercentStart, unsigned uPercentSpan,
1548 PVDINTERFACE pVDIfsDisk, PVDINTERFACE pVDIfsImage,
1549 PVDINTERFACE pVDIfsOperation, VDTYPE enmType,
1550 void **ppBackendData)
1551{
1552 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",
1553 pszFilename, cbSize, uImageFlags, pszComment, pPCHSGeometry, pLCHSGeometry, pUuid, uOpenFlags, uPercentStart, uPercentSpan, pVDIfsDisk, pVDIfsImage, pVDIfsOperation, enmType, ppBackendData));
1554 int rc;
1555 PQCOWIMAGE pImage;
1556
1557 PFNVDPROGRESS pfnProgress = NULL;
1558 void *pvUser = NULL;
1559 PVDINTERFACEPROGRESS pIfProgress = VDIfProgressGet(pVDIfsOperation);
1560 if (pIfProgress)
1561 {
1562 pfnProgress = pIfProgress->pfnProgress;
1563 pvUser = pIfProgress->Core.pvUser;
1564 }
1565
1566 /* Check the VD container type. */
1567 if (enmType != VDTYPE_HDD)
1568 {
1569 rc = VERR_VD_INVALID_TYPE;
1570 goto out;
1571 }
1572
1573 /* Check open flags. All valid flags are supported. */
1574 if (uOpenFlags & ~VD_OPEN_FLAGS_MASK)
1575 {
1576 rc = VERR_INVALID_PARAMETER;
1577 goto out;
1578 }
1579
1580 /* Check remaining arguments. */
1581 if ( !VALID_PTR(pszFilename)
1582 || !*pszFilename
1583 || !VALID_PTR(pPCHSGeometry)
1584 || !VALID_PTR(pLCHSGeometry))
1585 {
1586 rc = VERR_INVALID_PARAMETER;
1587 goto out;
1588 }
1589
1590 pImage = (PQCOWIMAGE)RTMemAllocZ(sizeof(QCOWIMAGE));
1591 if (!pImage)
1592 {
1593 rc = VERR_NO_MEMORY;
1594 goto out;
1595 }
1596 pImage->pszFilename = pszFilename;
1597 pImage->pStorage = NULL;
1598 pImage->pVDIfsDisk = pVDIfsDisk;
1599 pImage->pVDIfsImage = pVDIfsImage;
1600
1601 rc = qcowCreateImage(pImage, cbSize, uImageFlags, pszComment,
1602 pPCHSGeometry, pLCHSGeometry, uOpenFlags,
1603 pfnProgress, pvUser, uPercentStart, uPercentSpan);
1604 if (RT_SUCCESS(rc))
1605 {
1606 /* So far the image is opened in read/write mode. Make sure the
1607 * image is opened in read-only mode if the caller requested that. */
1608 if (uOpenFlags & VD_OPEN_FLAGS_READONLY)
1609 {
1610 qcowFreeImage(pImage, false);
1611 rc = qcowOpenImage(pImage, uOpenFlags);
1612 if (RT_FAILURE(rc))
1613 {
1614 RTMemFree(pImage);
1615 goto out;
1616 }
1617 }
1618 *ppBackendData = pImage;
1619 }
1620 else
1621 RTMemFree(pImage);
1622
1623out:
1624 LogFlowFunc(("returns %Rrc (pBackendData=%#p)\n", rc, *ppBackendData));
1625 return rc;
1626}
1627
1628/** @copydoc VBOXHDDBACKEND::pfnRename */
1629static int qcowRename(void *pBackendData, const char *pszFilename)
1630{
1631 LogFlowFunc(("pBackendData=%#p pszFilename=%#p\n", pBackendData, pszFilename));
1632 int rc = VINF_SUCCESS;
1633 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
1634
1635 /* Check arguments. */
1636 if ( !pImage
1637 || !pszFilename
1638 || !*pszFilename)
1639 {
1640 rc = VERR_INVALID_PARAMETER;
1641 goto out;
1642 }
1643
1644 /* Close the image. */
1645 rc = qcowFreeImage(pImage, false);
1646 if (RT_FAILURE(rc))
1647 goto out;
1648
1649 /* Rename the file. */
1650 rc = vdIfIoIntFileMove(pImage->pIfIo, pImage->pszFilename, pszFilename, 0);
1651 if (RT_FAILURE(rc))
1652 {
1653 /* The move failed, try to reopen the original image. */
1654 int rc2 = qcowOpenImage(pImage, pImage->uOpenFlags);
1655 if (RT_FAILURE(rc2))
1656 rc = rc2;
1657
1658 goto out;
1659 }
1660
1661 /* Update pImage with the new information. */
1662 pImage->pszFilename = pszFilename;
1663
1664 /* Open the old image with new name. */
1665 rc = qcowOpenImage(pImage, pImage->uOpenFlags);
1666 if (RT_FAILURE(rc))
1667 goto out;
1668
1669out:
1670 LogFlowFunc(("returns %Rrc\n", rc));
1671 return rc;
1672}
1673
1674/** @copydoc VBOXHDDBACKEND::pfnClose */
1675static int qcowClose(void *pBackendData, bool fDelete)
1676{
1677 LogFlowFunc(("pBackendData=%#p fDelete=%d\n", pBackendData, fDelete));
1678 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
1679 int rc;
1680
1681 rc = qcowFreeImage(pImage, fDelete);
1682 RTMemFree(pImage);
1683
1684 LogFlowFunc(("returns %Rrc\n", rc));
1685 return rc;
1686}
1687
1688static int qcowRead(void *pBackendData, uint64_t uOffset, size_t cbToRead,
1689 PVDIOCTX pIoCtx, size_t *pcbActuallyRead)
1690{
1691 LogFlowFunc(("pBackendData=%#p uOffset=%llu pIoCtx=%#p cbToRead=%zu pcbActuallyRead=%#p\n",
1692 pBackendData, uOffset, pIoCtx, cbToRead, pcbActuallyRead));
1693 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
1694 uint32_t offCluster = 0;
1695 uint32_t idxL1 = 0;
1696 uint32_t idxL2 = 0;
1697 uint64_t offFile = 0;
1698 int rc;
1699
1700 AssertPtr(pImage);
1701 Assert(uOffset % 512 == 0);
1702 Assert(cbToRead % 512 == 0);
1703
1704 if (!VALID_PTR(pIoCtx) || !cbToRead)
1705 {
1706 rc = VERR_INVALID_PARAMETER;
1707 goto out;
1708 }
1709
1710 if ( uOffset + cbToRead > pImage->cbSize
1711 || cbToRead == 0)
1712 {
1713 rc = VERR_INVALID_PARAMETER;
1714 goto out;
1715 }
1716
1717 qcowConvertLogicalOffset(pImage, uOffset, &idxL1, &idxL2, &offCluster);
1718
1719 /* Clip read size to remain in the cluster. */
1720 cbToRead = RT_MIN(cbToRead, pImage->cbCluster - offCluster);
1721
1722 /* Get offset in image. */
1723 rc = qcowConvertToImageOffset(pImage, pIoCtx, idxL1, idxL2, offCluster, &offFile);
1724 if (RT_SUCCESS(rc))
1725 rc = vdIfIoIntFileReadUser(pImage->pIfIo, pImage->pStorage, offFile,
1726 pIoCtx, cbToRead);
1727
1728 if ( ( RT_SUCCESS(rc)
1729 || rc == VERR_VD_BLOCK_FREE
1730 || rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
1731 && pcbActuallyRead)
1732 *pcbActuallyRead = cbToRead;
1733
1734out:
1735 LogFlowFunc(("returns %Rrc\n", rc));
1736 return rc;
1737}
1738
1739static int qcowWrite(void *pBackendData, uint64_t uOffset, size_t cbToWrite,
1740 PVDIOCTX pIoCtx, size_t *pcbWriteProcess, size_t *pcbPreRead,
1741 size_t *pcbPostRead, unsigned fWrite)
1742{
1743 LogFlowFunc(("pBackendData=%#p uOffset=%llu pIoCtx=%#p cbToWrite=%zu pcbWriteProcess=%#p pcbPreRead=%#p pcbPostRead=%#p\n",
1744 pBackendData, uOffset, pIoCtx, cbToWrite, pcbWriteProcess, pcbPreRead, pcbPostRead));
1745 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
1746 uint32_t offCluster = 0;
1747 uint32_t idxL1 = 0;
1748 uint32_t idxL2 = 0;
1749 uint64_t offImage = 0;
1750 int rc = VINF_SUCCESS;
1751
1752 AssertPtr(pImage);
1753 Assert(!(uOffset % 512));
1754 Assert(!(cbToWrite % 512));
1755
1756 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
1757 {
1758 rc = VERR_VD_IMAGE_READ_ONLY;
1759 goto out;
1760 }
1761
1762 if (!VALID_PTR(pIoCtx) || !cbToWrite)
1763 {
1764 rc = VERR_INVALID_PARAMETER;
1765 goto out;
1766 }
1767
1768 if ( uOffset + cbToWrite > pImage->cbSize
1769 || cbToWrite == 0)
1770 {
1771 rc = VERR_INVALID_PARAMETER;
1772 goto out;
1773 }
1774
1775 /* Convert offset to L1, L2 index and cluster offset. */
1776 qcowConvertLogicalOffset(pImage, uOffset, &idxL1, &idxL2, &offCluster);
1777
1778 /* Clip write size to remain in the cluster. */
1779 cbToWrite = RT_MIN(cbToWrite, pImage->cbCluster - offCluster);
1780 Assert(!(cbToWrite % 512));
1781
1782 /* Get offset in image. */
1783 rc = qcowConvertToImageOffset(pImage, pIoCtx, idxL1, idxL2, offCluster, &offImage);
1784 if (RT_SUCCESS(rc))
1785 rc = vdIfIoIntFileWriteUser(pImage->pIfIo, pImage->pStorage,
1786 offImage, pIoCtx, cbToWrite, NULL, NULL);
1787 else if (rc == VERR_VD_BLOCK_FREE)
1788 {
1789 if ( cbToWrite == pImage->cbCluster
1790 && !(fWrite & VD_WRITE_NO_ALLOC))
1791 {
1792 PQCOWL2CACHEENTRY pL2Entry = NULL;
1793
1794 /* Full cluster write to previously unallocated cluster.
1795 * Allocate cluster and write data. */
1796 Assert(!offCluster);
1797
1798 do
1799 {
1800 uint64_t idxUpdateLe = 0;
1801
1802 /* Check if we have to allocate a new cluster for L2 tables. */
1803 if (!pImage->paL1Table[idxL1])
1804 {
1805 uint64_t offL2Tbl;
1806 PQCOWCLUSTERASYNCALLOC pL2ClusterAlloc = NULL;
1807
1808 /* Allocate new async cluster allocation state. */
1809 pL2ClusterAlloc = (PQCOWCLUSTERASYNCALLOC)RTMemAllocZ(sizeof(QCOWCLUSTERASYNCALLOC));
1810 if (RT_UNLIKELY(!pL2ClusterAlloc))
1811 {
1812 rc = VERR_NO_MEMORY;
1813 break;
1814 }
1815
1816 pL2Entry = qcowL2TblCacheEntryAlloc(pImage);
1817 if (!pL2Entry)
1818 {
1819 rc = VERR_NO_MEMORY;
1820 RTMemFree(pL2ClusterAlloc);
1821 break;
1822 }
1823
1824 offL2Tbl = qcowClusterAllocate(pImage, qcowByte2Cluster(pImage, pImage->cbL2Table));
1825 pL2Entry->offL2Tbl = offL2Tbl;
1826 memset(pL2Entry->paL2Tbl, 0, pImage->cbL2Table);
1827
1828 pL2ClusterAlloc->enmAllocState = QCOWCLUSTERASYNCALLOCSTATE_L2_ALLOC;
1829 pL2ClusterAlloc->offNextClusterOld = offL2Tbl;
1830 pL2ClusterAlloc->offClusterNew = offL2Tbl;
1831 pL2ClusterAlloc->idxL1 = idxL1;
1832 pL2ClusterAlloc->idxL2 = idxL2;
1833 pL2ClusterAlloc->cbToWrite = cbToWrite;
1834 pL2ClusterAlloc->pL2Entry = pL2Entry;
1835
1836 /*
1837 * Write the L2 table first and link to the L1 table afterwards.
1838 * If something unexpected happens the worst case which can happen
1839 * is a leak of some clusters.
1840 */
1841 rc = vdIfIoIntFileWriteMeta(pImage->pIfIo, pImage->pStorage,
1842 offL2Tbl, pL2Entry->paL2Tbl, pImage->cbL2Table, pIoCtx,
1843 qcowAsyncClusterAllocUpdate, pL2ClusterAlloc);
1844 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
1845 break;
1846 else if (RT_FAILURE(rc))
1847 {
1848 RTMemFree(pL2ClusterAlloc);
1849 qcowL2TblCacheEntryFree(pImage, pL2Entry);
1850 break;
1851 }
1852
1853 rc = qcowAsyncClusterAllocUpdate(pImage, pIoCtx, pL2ClusterAlloc, rc);
1854 }
1855 else
1856 {
1857 rc = qcowL2TblCacheFetch(pImage, pIoCtx, pImage->paL1Table[idxL1],
1858 &pL2Entry);
1859 if (RT_SUCCESS(rc))
1860 {
1861 PQCOWCLUSTERASYNCALLOC pDataClusterAlloc = NULL;
1862
1863 /* Allocate new async cluster allocation state. */
1864 pDataClusterAlloc = (PQCOWCLUSTERASYNCALLOC)RTMemAllocZ(sizeof(QCOWCLUSTERASYNCALLOC));
1865 if (RT_UNLIKELY(!pDataClusterAlloc))
1866 {
1867 rc = VERR_NO_MEMORY;
1868 break;
1869 }
1870
1871 /* Allocate new cluster for the data. */
1872 uint64_t offData = qcowClusterAllocate(pImage, 1);
1873
1874 pDataClusterAlloc->enmAllocState = QCOWCLUSTERASYNCALLOCSTATE_USER_ALLOC;
1875 pDataClusterAlloc->offNextClusterOld = offData;
1876 pDataClusterAlloc->offClusterNew = offData;
1877 pDataClusterAlloc->idxL1 = idxL1;
1878 pDataClusterAlloc->idxL2 = idxL2;
1879 pDataClusterAlloc->cbToWrite = cbToWrite;
1880 pDataClusterAlloc->pL2Entry = pL2Entry;
1881
1882 /* Write data. */
1883 rc = vdIfIoIntFileWriteUser(pImage->pIfIo, pImage->pStorage,
1884 offData, pIoCtx, cbToWrite,
1885 qcowAsyncClusterAllocUpdate, pDataClusterAlloc);
1886 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
1887 break;
1888 else if (RT_FAILURE(rc))
1889 {
1890 RTMemFree(pDataClusterAlloc);
1891 break;
1892 }
1893
1894 rc = qcowAsyncClusterAllocUpdate(pImage, pIoCtx, pDataClusterAlloc, rc);
1895 }
1896 }
1897
1898 } while (0);
1899
1900 *pcbPreRead = 0;
1901 *pcbPostRead = 0;
1902 }
1903 else
1904 {
1905 /* Trying to do a partial write to an unallocated cluster. Don't do
1906 * anything except letting the upper layer know what to do. */
1907 *pcbPreRead = offCluster;
1908 *pcbPostRead = pImage->cbCluster - cbToWrite - *pcbPreRead;
1909 }
1910 }
1911
1912 if (pcbWriteProcess)
1913 *pcbWriteProcess = cbToWrite;
1914
1915
1916out:
1917 LogFlowFunc(("returns %Rrc\n", rc));
1918 return rc;
1919}
1920
1921static int qcowFlush(void *pBackendData, PVDIOCTX pIoCtx)
1922{
1923 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
1924 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
1925 int rc = VINF_SUCCESS;
1926
1927 Assert(pImage);
1928
1929 if (VALID_PTR(pIoCtx))
1930 rc = qcowFlushImageAsync(pImage, pIoCtx);
1931 else
1932 rc = VERR_INVALID_PARAMETER;
1933
1934 LogFlowFunc(("returns %Rrc\n", rc));
1935 return rc;
1936}
1937
1938/** @copydoc VBOXHDDBACKEND::pfnGetVersion */
1939static unsigned qcowGetVersion(void *pBackendData)
1940{
1941 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
1942 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
1943
1944 AssertPtr(pImage);
1945
1946 if (pImage)
1947 return pImage->uVersion;
1948 else
1949 return 0;
1950}
1951
1952/** @copydoc VBOXHDDBACKEND::pfnGetSectorSize */
1953static uint32_t qcowGetSectorSize(void *pBackendData)
1954{
1955 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
1956 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
1957 uint32_t cb = 0;
1958
1959 AssertPtr(pImage);
1960
1961 if (pImage && pImage->pStorage)
1962 cb = 512;
1963
1964 LogFlowFunc(("returns %u\n", cb));
1965 return cb;
1966}
1967
1968/** @copydoc VBOXHDDBACKEND::pfnGetSize */
1969static uint64_t qcowGetSize(void *pBackendData)
1970{
1971 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
1972 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
1973 uint64_t cb = 0;
1974
1975 AssertPtr(pImage);
1976
1977 if (pImage && pImage->pStorage)
1978 cb = pImage->cbSize;
1979
1980 LogFlowFunc(("returns %llu\n", cb));
1981 return cb;
1982}
1983
1984/** @copydoc VBOXHDDBACKEND::pfnGetFileSize */
1985static uint64_t qcowGetFileSize(void *pBackendData)
1986{
1987 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
1988 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
1989 uint64_t cb = 0;
1990
1991 AssertPtr(pImage);
1992
1993 if (pImage)
1994 {
1995 uint64_t cbFile;
1996 if (pImage->pStorage)
1997 {
1998 int rc = vdIfIoIntFileGetSize(pImage->pIfIo, pImage->pStorage, &cbFile);
1999 if (RT_SUCCESS(rc))
2000 cb += cbFile;
2001 }
2002 }
2003
2004 LogFlowFunc(("returns %lld\n", cb));
2005 return cb;
2006}
2007
2008/** @copydoc VBOXHDDBACKEND::pfnGetPCHSGeometry */
2009static int qcowGetPCHSGeometry(void *pBackendData,
2010 PVDGEOMETRY pPCHSGeometry)
2011{
2012 LogFlowFunc(("pBackendData=%#p pPCHSGeometry=%#p\n", pBackendData, pPCHSGeometry));
2013 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2014 int rc;
2015
2016 AssertPtr(pImage);
2017
2018 if (pImage)
2019 {
2020 if (pImage->PCHSGeometry.cCylinders)
2021 {
2022 *pPCHSGeometry = pImage->PCHSGeometry;
2023 rc = VINF_SUCCESS;
2024 }
2025 else
2026 rc = VERR_VD_GEOMETRY_NOT_SET;
2027 }
2028 else
2029 rc = VERR_VD_NOT_OPENED;
2030
2031 LogFlowFunc(("returns %Rrc (PCHS=%u/%u/%u)\n", rc, pPCHSGeometry->cCylinders, pPCHSGeometry->cHeads, pPCHSGeometry->cSectors));
2032 return rc;
2033}
2034
2035/** @copydoc VBOXHDDBACKEND::pfnSetPCHSGeometry */
2036static int qcowSetPCHSGeometry(void *pBackendData,
2037 PCVDGEOMETRY pPCHSGeometry)
2038{
2039 LogFlowFunc(("pBackendData=%#p pPCHSGeometry=%#p PCHS=%u/%u/%u\n", pBackendData, pPCHSGeometry, pPCHSGeometry->cCylinders, pPCHSGeometry->cHeads, pPCHSGeometry->cSectors));
2040 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2041 int rc;
2042
2043 AssertPtr(pImage);
2044
2045 if (pImage)
2046 {
2047 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
2048 {
2049 rc = VERR_VD_IMAGE_READ_ONLY;
2050 goto out;
2051 }
2052
2053 pImage->PCHSGeometry = *pPCHSGeometry;
2054 rc = VINF_SUCCESS;
2055 }
2056 else
2057 rc = VERR_VD_NOT_OPENED;
2058
2059out:
2060 LogFlowFunc(("returns %Rrc\n", rc));
2061 return rc;
2062}
2063
2064/** @copydoc VBOXHDDBACKEND::pfnGetLCHSGeometry */
2065static int qcowGetLCHSGeometry(void *pBackendData,
2066 PVDGEOMETRY pLCHSGeometry)
2067{
2068 LogFlowFunc(("pBackendData=%#p pLCHSGeometry=%#p\n", pBackendData, pLCHSGeometry));
2069 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2070 int rc;
2071
2072 AssertPtr(pImage);
2073
2074 if (pImage)
2075 {
2076 if (pImage->LCHSGeometry.cCylinders)
2077 {
2078 *pLCHSGeometry = pImage->LCHSGeometry;
2079 rc = VINF_SUCCESS;
2080 }
2081 else
2082 rc = VERR_VD_GEOMETRY_NOT_SET;
2083 }
2084 else
2085 rc = VERR_VD_NOT_OPENED;
2086
2087 LogFlowFunc(("returns %Rrc (LCHS=%u/%u/%u)\n", rc, pLCHSGeometry->cCylinders, pLCHSGeometry->cHeads, pLCHSGeometry->cSectors));
2088 return rc;
2089}
2090
2091/** @copydoc VBOXHDDBACKEND::pfnSetLCHSGeometry */
2092static int qcowSetLCHSGeometry(void *pBackendData,
2093 PCVDGEOMETRY pLCHSGeometry)
2094{
2095 LogFlowFunc(("pBackendData=%#p pLCHSGeometry=%#p LCHS=%u/%u/%u\n", pBackendData, pLCHSGeometry, pLCHSGeometry->cCylinders, pLCHSGeometry->cHeads, pLCHSGeometry->cSectors));
2096 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2097 int rc;
2098
2099 AssertPtr(pImage);
2100
2101 if (pImage)
2102 {
2103 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
2104 {
2105 rc = VERR_VD_IMAGE_READ_ONLY;
2106 goto out;
2107 }
2108
2109 pImage->LCHSGeometry = *pLCHSGeometry;
2110 rc = VINF_SUCCESS;
2111 }
2112 else
2113 rc = VERR_VD_NOT_OPENED;
2114
2115out:
2116 LogFlowFunc(("returns %Rrc\n", rc));
2117 return rc;
2118}
2119
2120/** @copydoc VBOXHDDBACKEND::pfnGetImageFlags */
2121static unsigned qcowGetImageFlags(void *pBackendData)
2122{
2123 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
2124 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2125 unsigned uImageFlags;
2126
2127 AssertPtr(pImage);
2128
2129 if (pImage)
2130 uImageFlags = pImage->uImageFlags;
2131 else
2132 uImageFlags = 0;
2133
2134 LogFlowFunc(("returns %#x\n", uImageFlags));
2135 return uImageFlags;
2136}
2137
2138/** @copydoc VBOXHDDBACKEND::pfnGetOpenFlags */
2139static unsigned qcowGetOpenFlags(void *pBackendData)
2140{
2141 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
2142 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2143 unsigned uOpenFlags;
2144
2145 AssertPtr(pImage);
2146
2147 if (pImage)
2148 uOpenFlags = pImage->uOpenFlags;
2149 else
2150 uOpenFlags = 0;
2151
2152 LogFlowFunc(("returns %#x\n", uOpenFlags));
2153 return uOpenFlags;
2154}
2155
2156/** @copydoc VBOXHDDBACKEND::pfnSetOpenFlags */
2157static int qcowSetOpenFlags(void *pBackendData, unsigned uOpenFlags)
2158{
2159 LogFlowFunc(("pBackendData=%#p\n uOpenFlags=%#x", pBackendData, uOpenFlags));
2160 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2161 int rc;
2162
2163 /* Image must be opened and the new flags must be valid. */
2164 if (!pImage || (uOpenFlags & ~( VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_INFO
2165 | VD_OPEN_FLAGS_ASYNC_IO | VD_OPEN_FLAGS_SKIP_CONSISTENCY_CHECKS)))
2166 {
2167 rc = VERR_INVALID_PARAMETER;
2168 goto out;
2169 }
2170
2171 /* Implement this operation via reopening the image. */
2172 rc = qcowFreeImage(pImage, false);
2173 if (RT_FAILURE(rc))
2174 goto out;
2175 rc = qcowOpenImage(pImage, uOpenFlags);
2176
2177out:
2178 LogFlowFunc(("returns %Rrc\n", rc));
2179 return rc;
2180}
2181
2182/** @copydoc VBOXHDDBACKEND::pfnGetComment */
2183static int qcowGetComment(void *pBackendData, char *pszComment,
2184 size_t cbComment)
2185{
2186 LogFlowFunc(("pBackendData=%#p pszComment=%#p cbComment=%zu\n", pBackendData, pszComment, cbComment));
2187 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2188 int rc;
2189
2190 AssertPtr(pImage);
2191
2192 if (pImage)
2193 rc = VERR_NOT_SUPPORTED;
2194 else
2195 rc = VERR_VD_NOT_OPENED;
2196
2197 LogFlowFunc(("returns %Rrc comment='%s'\n", rc, pszComment));
2198 return rc;
2199}
2200
2201/** @copydoc VBOXHDDBACKEND::pfnSetComment */
2202static int qcowSetComment(void *pBackendData, const char *pszComment)
2203{
2204 LogFlowFunc(("pBackendData=%#p pszComment=\"%s\"\n", pBackendData, pszComment));
2205 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2206 int rc;
2207
2208 AssertPtr(pImage);
2209
2210 if (pImage)
2211 {
2212 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
2213 rc = VERR_VD_IMAGE_READ_ONLY;
2214 else
2215 rc = VERR_NOT_SUPPORTED;
2216 }
2217 else
2218 rc = VERR_VD_NOT_OPENED;
2219
2220 LogFlowFunc(("returns %Rrc\n", rc));
2221 return rc;
2222}
2223
2224/** @copydoc VBOXHDDBACKEND::pfnGetUuid */
2225static int qcowGetUuid(void *pBackendData, PRTUUID pUuid)
2226{
2227 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
2228 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2229 int rc;
2230
2231 AssertPtr(pImage);
2232
2233 if (pImage)
2234 rc = VERR_NOT_SUPPORTED;
2235 else
2236 rc = VERR_VD_NOT_OPENED;
2237
2238 LogFlowFunc(("returns %Rrc (%RTuuid)\n", rc, pUuid));
2239 return rc;
2240}
2241
2242/** @copydoc VBOXHDDBACKEND::pfnSetUuid */
2243static int qcowSetUuid(void *pBackendData, PCRTUUID pUuid)
2244{
2245 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
2246 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2247 int rc;
2248
2249 LogFlowFunc(("%RTuuid\n", pUuid));
2250 AssertPtr(pImage);
2251
2252 if (pImage)
2253 {
2254 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
2255 rc = VERR_NOT_SUPPORTED;
2256 else
2257 rc = VERR_VD_IMAGE_READ_ONLY;
2258 }
2259 else
2260 rc = VERR_VD_NOT_OPENED;
2261
2262 LogFlowFunc(("returns %Rrc\n", rc));
2263 return rc;
2264}
2265
2266/** @copydoc VBOXHDDBACKEND::pfnGetModificationUuid */
2267static int qcowGetModificationUuid(void *pBackendData, PRTUUID pUuid)
2268{
2269 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
2270 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2271 int rc;
2272
2273 AssertPtr(pImage);
2274
2275 if (pImage)
2276 rc = VERR_NOT_SUPPORTED;
2277 else
2278 rc = VERR_VD_NOT_OPENED;
2279
2280 LogFlowFunc(("returns %Rrc (%RTuuid)\n", rc, pUuid));
2281 return rc;
2282}
2283
2284/** @copydoc VBOXHDDBACKEND::pfnSetModificationUuid */
2285static int qcowSetModificationUuid(void *pBackendData, PCRTUUID pUuid)
2286{
2287 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
2288 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2289 int rc;
2290
2291 AssertPtr(pImage);
2292
2293 if (pImage)
2294 {
2295 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
2296 rc = VERR_NOT_SUPPORTED;
2297 else
2298 rc = VERR_VD_IMAGE_READ_ONLY;
2299 }
2300 else
2301 rc = VERR_VD_NOT_OPENED;
2302
2303 LogFlowFunc(("returns %Rrc\n", rc));
2304 return rc;
2305}
2306
2307/** @copydoc VBOXHDDBACKEND::pfnGetParentUuid */
2308static int qcowGetParentUuid(void *pBackendData, PRTUUID pUuid)
2309{
2310 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
2311 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2312 int rc;
2313
2314 AssertPtr(pImage);
2315
2316 if (pImage)
2317 rc = VERR_NOT_SUPPORTED;
2318 else
2319 rc = VERR_VD_NOT_OPENED;
2320
2321 LogFlowFunc(("returns %Rrc (%RTuuid)\n", rc, pUuid));
2322 return rc;
2323}
2324
2325/** @copydoc VBOXHDDBACKEND::pfnSetParentUuid */
2326static int qcowSetParentUuid(void *pBackendData, PCRTUUID pUuid)
2327{
2328 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
2329 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2330 int rc;
2331
2332 AssertPtr(pImage);
2333
2334 if (pImage)
2335 {
2336 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
2337 rc = VERR_NOT_SUPPORTED;
2338 else
2339 rc = VERR_VD_IMAGE_READ_ONLY;
2340 }
2341 else
2342 rc = VERR_VD_NOT_OPENED;
2343
2344 LogFlowFunc(("returns %Rrc\n", rc));
2345 return rc;
2346}
2347
2348/** @copydoc VBOXHDDBACKEND::pfnGetParentModificationUuid */
2349static int qcowGetParentModificationUuid(void *pBackendData, PRTUUID pUuid)
2350{
2351 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
2352 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2353 int rc;
2354
2355 AssertPtr(pImage);
2356
2357 if (pImage)
2358 rc = VERR_NOT_SUPPORTED;
2359 else
2360 rc = VERR_VD_NOT_OPENED;
2361
2362 LogFlowFunc(("returns %Rrc (%RTuuid)\n", rc, pUuid));
2363 return rc;
2364}
2365
2366/** @copydoc VBOXHDDBACKEND::pfnSetParentModificationUuid */
2367static int qcowSetParentModificationUuid(void *pBackendData, PCRTUUID pUuid)
2368{
2369 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
2370 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2371 int rc;
2372
2373 AssertPtr(pImage);
2374
2375 if (pImage)
2376 {
2377 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
2378 rc = VERR_NOT_SUPPORTED;
2379 else
2380 rc = VERR_VD_IMAGE_READ_ONLY;
2381 }
2382 else
2383 rc = VERR_VD_NOT_OPENED;
2384
2385 LogFlowFunc(("returns %Rrc\n", rc));
2386 return rc;
2387}
2388
2389/** @copydoc VBOXHDDBACKEND::pfnDump */
2390static void qcowDump(void *pBackendData)
2391{
2392 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2393
2394 AssertPtr(pImage);
2395 if (pImage)
2396 {
2397 vdIfErrorMessage(pImage->pIfError, "Header: Geometry PCHS=%u/%u/%u LCHS=%u/%u/%u cSector=%llu\n",
2398 pImage->PCHSGeometry.cCylinders, pImage->PCHSGeometry.cHeads, pImage->PCHSGeometry.cSectors,
2399 pImage->LCHSGeometry.cCylinders, pImage->LCHSGeometry.cHeads, pImage->LCHSGeometry.cSectors,
2400 pImage->cbSize / 512);
2401 }
2402}
2403
2404/** @copydoc VBOXHDDBACKEND::pfnGetParentFilename */
2405static int qcowGetParentFilename(void *pBackendData, char **ppszParentFilename)
2406{
2407 int rc = VINF_SUCCESS;
2408 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2409
2410 AssertPtr(pImage);
2411 if (pImage)
2412 if (pImage->pszBackingFilename)
2413 *ppszParentFilename = RTStrDup(pImage->pszBackingFilename);
2414 else
2415 rc = VERR_NOT_SUPPORTED;
2416 else
2417 rc = VERR_VD_NOT_OPENED;
2418
2419 LogFlowFunc(("returns %Rrc\n", rc));
2420 return rc;
2421}
2422
2423/** @copydoc VBOXHDDBACKEND::pfnSetParentFilename */
2424static int qcowSetParentFilename(void *pBackendData, const char *pszParentFilename)
2425{
2426 int rc = VINF_SUCCESS;
2427 PQCOWIMAGE pImage = (PQCOWIMAGE)pBackendData;
2428
2429 AssertPtr(pImage);
2430 if (pImage)
2431 {
2432 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
2433 rc = VERR_VD_IMAGE_READ_ONLY;
2434 else if ( pImage->pszBackingFilename
2435 && (strlen(pszParentFilename) > pImage->cbBackingFilename))
2436 rc = VERR_NOT_SUPPORTED; /* The new filename is longer than the old one. */
2437 else
2438 {
2439 if (pImage->pszBackingFilename)
2440 RTStrFree(pImage->pszBackingFilename);
2441 pImage->pszBackingFilename = RTStrDup(pszParentFilename);
2442 if (!pImage->pszBackingFilename)
2443 rc = VERR_NO_MEMORY;
2444 else
2445 {
2446 if (!pImage->offBackingFilename)
2447 {
2448 /* Allocate new cluster. */
2449 uint64_t offData = qcowClusterAllocate(pImage, 1);
2450
2451 Assert((offData & UINT32_MAX) == offData);
2452 pImage->offBackingFilename = (uint32_t)offData;
2453 pImage->cbBackingFilename = (uint32_t)strlen(pszParentFilename);
2454 rc = vdIfIoIntFileSetSize(pImage->pIfIo, pImage->pStorage,
2455 offData + pImage->cbCluster);
2456 }
2457
2458 if (RT_SUCCESS(rc))
2459 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pImage->pStorage,
2460 pImage->offBackingFilename,
2461 pImage->pszBackingFilename,
2462 strlen(pImage->pszBackingFilename));
2463 }
2464 }
2465 }
2466 else
2467 rc = VERR_VD_NOT_OPENED;
2468
2469 LogFlowFunc(("returns %Rrc\n", rc));
2470 return rc;
2471}
2472
2473
2474
2475const VBOXHDDBACKEND g_QCowBackend =
2476{
2477 /* pszBackendName */
2478 "QCOW",
2479 /* cbSize */
2480 sizeof(VBOXHDDBACKEND),
2481 /* uBackendCaps */
2482 VD_CAP_FILE | VD_CAP_VFS | VD_CAP_CREATE_DYNAMIC | VD_CAP_DIFF | VD_CAP_ASYNC,
2483 /* paFileExtensions */
2484 s_aQCowFileExtensions,
2485 /* paConfigInfo */
2486 NULL,
2487 /* pfnCheckIfValid */
2488 qcowCheckIfValid,
2489 /* pfnOpen */
2490 qcowOpen,
2491 /* pfnCreate */
2492 qcowCreate,
2493 /* pfnRename */
2494 qcowRename,
2495 /* pfnClose */
2496 qcowClose,
2497 /* pfnRead */
2498 qcowRead,
2499 /* pfnWrite */
2500 qcowWrite,
2501 /* pfnFlush */
2502 qcowFlush,
2503 /* pfnDiscard */
2504 NULL,
2505 /* pfnGetVersion */
2506 qcowGetVersion,
2507 /* pfnGetSectorSize */
2508 qcowGetSectorSize,
2509 /* pfnGetSize */
2510 qcowGetSize,
2511 /* pfnGetFileSize */
2512 qcowGetFileSize,
2513 /* pfnGetPCHSGeometry */
2514 qcowGetPCHSGeometry,
2515 /* pfnSetPCHSGeometry */
2516 qcowSetPCHSGeometry,
2517 /* pfnGetLCHSGeometry */
2518 qcowGetLCHSGeometry,
2519 /* pfnSetLCHSGeometry */
2520 qcowSetLCHSGeometry,
2521 /* pfnGetImageFlags */
2522 qcowGetImageFlags,
2523 /* pfnGetOpenFlags */
2524 qcowGetOpenFlags,
2525 /* pfnSetOpenFlags */
2526 qcowSetOpenFlags,
2527 /* pfnGetComment */
2528 qcowGetComment,
2529 /* pfnSetComment */
2530 qcowSetComment,
2531 /* pfnGetUuid */
2532 qcowGetUuid,
2533 /* pfnSetUuid */
2534 qcowSetUuid,
2535 /* pfnGetModificationUuid */
2536 qcowGetModificationUuid,
2537 /* pfnSetModificationUuid */
2538 qcowSetModificationUuid,
2539 /* pfnGetParentUuid */
2540 qcowGetParentUuid,
2541 /* pfnSetParentUuid */
2542 qcowSetParentUuid,
2543 /* pfnGetParentModificationUuid */
2544 qcowGetParentModificationUuid,
2545 /* pfnSetParentModificationUuid */
2546 qcowSetParentModificationUuid,
2547 /* pfnDump */
2548 qcowDump,
2549 /* pfnGetTimeStamp */
2550 NULL,
2551 /* pfnGetParentTimeStamp */
2552 NULL,
2553 /* pfnSetParentTimeStamp */
2554 NULL,
2555 /* pfnGetParentFilename */
2556 qcowGetParentFilename,
2557 /* pfnSetParentFilename */
2558 qcowSetParentFilename,
2559 /* pfnComposeLocation */
2560 genericFileComposeLocation,
2561 /* pfnComposeName */
2562 genericFileComposeName,
2563 /* pfnCompact */
2564 NULL,
2565 /* pfnResize */
2566 NULL,
2567 /* pfnRepair */
2568 NULL,
2569 /* pfnTraverseMetadata */
2570 NULL
2571};
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