VirtualBox

source: vbox/trunk/src/VBox/Storage/VDI.cpp@ 86186

Last change on this file since 86186 was 85121, checked in by vboxsync, 4 years ago

iprt/cdefs.h: Refactored the typedef use of DECLCALLBACK as well as DECLCALLBACKMEMBER to wrap the whole expression, similar to the DECLR?CALLBACKMEMBER macros. This allows adding a throw() at the end when compiling with the VC++ compiler to indicate that the callbacks won't throw anything, so we can stop supressing the C5039 warning about passing functions that can potential throw C++ exceptions to extern C code that can't necessarily cope with such (unwind,++). Introduced a few _EX variations that allows specifying different/no calling convention too, as that's handy when dynamically resolving host APIs. Fixed numerous places missing DECLCALLBACK and such. Left two angry @todos regarding use of CreateThread. bugref:9794

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 127.6 KB
Line 
1/* $Id: VDI.cpp 85121 2020-07-08 19:33:26Z vboxsync $ */
2/** @file
3 * Virtual Disk Image (VDI), Core Code.
4 */
5
6/*
7 * Copyright (C) 2006-2020 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18
19/*********************************************************************************************************************************
20* Header Files *
21*********************************************************************************************************************************/
22#define LOG_GROUP LOG_GROUP_VD_VDI
23#include <VBox/vd-plugin.h>
24#include "VDICore.h"
25#include <VBox/err.h>
26
27#include <VBox/log.h>
28#include <iprt/alloc.h>
29#include <iprt/assert.h>
30#include <iprt/uuid.h>
31#include <iprt/string.h>
32#include <iprt/asm.h>
33
34#include "VDBackends.h"
35
36#define VDI_IMAGE_DEFAULT_BLOCK_SIZE _1M
37
38/** Macros for endianess conversion. */
39#define SET_ENDIAN_U32(conv, u32) (conv == VDIECONV_H2F ? RT_H2LE_U32(u32) : RT_LE2H_U32(u32))
40#define SET_ENDIAN_U64(conv, u64) (conv == VDIECONV_H2F ? RT_H2LE_U64(u64) : RT_LE2H_U64(u64))
41
42static const char *vdiAllocationBlockSize = "1048576";
43
44static const VDCONFIGINFO vdiConfigInfo[] =
45{
46 { "AllocationBlockSize", vdiAllocationBlockSize, VDCFGVALUETYPE_INTEGER, VD_CFGKEY_CREATEONLY },
47 { NULL, NULL, VDCFGVALUETYPE_INTEGER, 0 }
48};
49
50
51/*********************************************************************************************************************************
52* Static Variables *
53*********************************************************************************************************************************/
54
55/** NULL-terminated array of supported file extensions. */
56static const VDFILEEXTENSION s_aVdiFileExtensions[] =
57{
58 {"vdi", VDTYPE_HDD},
59 {NULL, VDTYPE_INVALID}
60};
61
62
63/*********************************************************************************************************************************
64* Internal Functions *
65*********************************************************************************************************************************/
66static unsigned getPowerOfTwo(unsigned uNumber);
67static void vdiInitPreHeader(PVDIPREHEADER pPreHdr);
68static int vdiValidatePreHeader(PVDIPREHEADER pPreHdr);
69static int vdiValidateHeader(PVDIHEADER pHeader);
70static void vdiSetupImageDesc(PVDIIMAGEDESC pImage);
71static int vdiUpdateHeader(PVDIIMAGEDESC pImage);
72static int vdiUpdateBlockInfo(PVDIIMAGEDESC pImage, unsigned uBlock);
73static int vdiUpdateHeaderAsync(PVDIIMAGEDESC pImage, PVDIOCTX pIoCtx);
74static int vdiUpdateBlockInfoAsync(PVDIIMAGEDESC pImage, unsigned uBlock, PVDIOCTX pIoCtx,
75 bool fUpdateHdr);
76
77/**
78 * Internal: Convert the PreHeader fields to the appropriate endianess.
79 * @param enmConv Direction of the conversion.
80 * @param pPreHdrConv Where to store the converted pre header.
81 * @param pPreHdr PreHeader pointer.
82 */
83static void vdiConvPreHeaderEndianess(VDIECONV enmConv, PVDIPREHEADER pPreHdrConv,
84 PVDIPREHEADER pPreHdr)
85{
86 memcpy(pPreHdrConv->szFileInfo, pPreHdr->szFileInfo, sizeof(pPreHdr->szFileInfo));
87 pPreHdrConv->u32Signature = SET_ENDIAN_U32(enmConv, pPreHdr->u32Signature);
88 pPreHdrConv->u32Version = SET_ENDIAN_U32(enmConv, pPreHdr->u32Version);
89}
90
91/**
92 * Internal: Convert the VDIDISKGEOMETRY fields to the appropriate endianess.
93 * @param enmConv Direction of the conversion.
94 * @param pDiskGeoConv Where to store the converted geometry.
95 * @param pDiskGeo Pointer to the disk geometry to convert.
96 */
97static void vdiConvGeometryEndianess(VDIECONV enmConv, PVDIDISKGEOMETRY pDiskGeoConv,
98 PVDIDISKGEOMETRY pDiskGeo)
99{
100 pDiskGeoConv->cCylinders = SET_ENDIAN_U32(enmConv, pDiskGeo->cCylinders);
101 pDiskGeoConv->cHeads = SET_ENDIAN_U32(enmConv, pDiskGeo->cHeads);
102 pDiskGeoConv->cSectors = SET_ENDIAN_U32(enmConv, pDiskGeo->cSectors);
103 pDiskGeoConv->cbSector = SET_ENDIAN_U32(enmConv, pDiskGeo->cbSector);
104}
105
106/**
107 * Internal: Convert the Header - version 0 fields to the appropriate endianess.
108 * @param enmConv Direction of the conversion.
109 * @param pHdrConv Where to store the converted header.
110 * @param pHdr Pointer to the version 0 header.
111 */
112static void vdiConvHeaderEndianessV0(VDIECONV enmConv, PVDIHEADER0 pHdrConv,
113 PVDIHEADER0 pHdr)
114{
115 memmove(pHdrConv->szComment, pHdr->szComment, sizeof(pHdr->szComment));
116 pHdrConv->u32Type = SET_ENDIAN_U32(enmConv, pHdr->u32Type);
117 pHdrConv->fFlags = SET_ENDIAN_U32(enmConv, pHdr->fFlags);
118 vdiConvGeometryEndianess(enmConv, &pHdrConv->LegacyGeometry, &pHdr->LegacyGeometry);
119 pHdrConv->cbDisk = SET_ENDIAN_U64(enmConv, pHdr->cbDisk);
120 pHdrConv->cbBlock = SET_ENDIAN_U32(enmConv, pHdr->cbBlock);
121 pHdrConv->cBlocks = SET_ENDIAN_U32(enmConv, pHdr->cBlocks);
122 pHdrConv->cBlocksAllocated = SET_ENDIAN_U32(enmConv, pHdr->cBlocksAllocated);
123 /* Don't convert the RTUUID fields. */
124 pHdrConv->uuidCreate = pHdr->uuidCreate;
125 pHdrConv->uuidModify = pHdr->uuidModify;
126 pHdrConv->uuidLinkage = pHdr->uuidLinkage;
127}
128
129/**
130 * Internal: Set the Header - version 1 fields to the appropriate endianess.
131 * @param enmConv Direction of the conversion.
132 * @param pHdrConv Where to store the converted header.
133 * @param pHdr Version 1 Header pointer.
134 */
135static void vdiConvHeaderEndianessV1(VDIECONV enmConv, PVDIHEADER1 pHdrConv,
136 PVDIHEADER1 pHdr)
137{
138 memmove(pHdrConv->szComment, pHdr->szComment, sizeof(pHdr->szComment));
139 pHdrConv->cbHeader = SET_ENDIAN_U32(enmConv, pHdr->cbHeader);
140 pHdrConv->u32Type = SET_ENDIAN_U32(enmConv, pHdr->u32Type);
141 pHdrConv->fFlags = SET_ENDIAN_U32(enmConv, pHdr->fFlags);
142 pHdrConv->offBlocks = SET_ENDIAN_U32(enmConv, pHdr->offBlocks);
143 pHdrConv->offData = SET_ENDIAN_U32(enmConv, pHdr->offData);
144 vdiConvGeometryEndianess(enmConv, &pHdrConv->LegacyGeometry, &pHdr->LegacyGeometry);
145 pHdrConv->u32Dummy = SET_ENDIAN_U32(enmConv, pHdr->u32Dummy);
146 pHdrConv->cbDisk = SET_ENDIAN_U64(enmConv, pHdr->cbDisk);
147 pHdrConv->cbBlock = SET_ENDIAN_U32(enmConv, pHdr->cbBlock);
148 pHdrConv->cbBlockExtra = SET_ENDIAN_U32(enmConv, pHdr->cbBlockExtra);
149 pHdrConv->cBlocks = SET_ENDIAN_U32(enmConv, pHdr->cBlocks);
150 pHdrConv->cBlocksAllocated = SET_ENDIAN_U32(enmConv, pHdr->cBlocksAllocated);
151 /* Don't convert the RTUUID fields. */
152 pHdrConv->uuidCreate = pHdr->uuidCreate;
153 pHdrConv->uuidModify = pHdr->uuidModify;
154 pHdrConv->uuidLinkage = pHdr->uuidLinkage;
155 pHdrConv->uuidParentModify = pHdr->uuidParentModify;
156}
157
158/**
159 * Internal: Set the Header - version 1plus fields to the appropriate endianess.
160 * @param enmConv Direction of the conversion.
161 * @param pHdrConv Where to store the converted header.
162 * @param pHdr Version 1+ Header pointer.
163 */
164static void vdiConvHeaderEndianessV1p(VDIECONV enmConv, PVDIHEADER1PLUS pHdrConv,
165 PVDIHEADER1PLUS pHdr)
166{
167 memmove(pHdrConv->szComment, pHdr->szComment, sizeof(pHdr->szComment));
168 pHdrConv->cbHeader = SET_ENDIAN_U32(enmConv, pHdr->cbHeader);
169 pHdrConv->u32Type = SET_ENDIAN_U32(enmConv, pHdr->u32Type);
170 pHdrConv->fFlags = SET_ENDIAN_U32(enmConv, pHdr->fFlags);
171 pHdrConv->offBlocks = SET_ENDIAN_U32(enmConv, pHdr->offBlocks);
172 pHdrConv->offData = SET_ENDIAN_U32(enmConv, pHdr->offData);
173 vdiConvGeometryEndianess(enmConv, &pHdrConv->LegacyGeometry, &pHdr->LegacyGeometry);
174 pHdrConv->u32Dummy = SET_ENDIAN_U32(enmConv, pHdr->u32Dummy);
175 pHdrConv->cbDisk = SET_ENDIAN_U64(enmConv, pHdr->cbDisk);
176 pHdrConv->cbBlock = SET_ENDIAN_U32(enmConv, pHdr->cbBlock);
177 pHdrConv->cbBlockExtra = SET_ENDIAN_U32(enmConv, pHdr->cbBlockExtra);
178 pHdrConv->cBlocks = SET_ENDIAN_U32(enmConv, pHdr->cBlocks);
179 pHdrConv->cBlocksAllocated = SET_ENDIAN_U32(enmConv, pHdr->cBlocksAllocated);
180 /* Don't convert the RTUUID fields. */
181 pHdrConv->uuidCreate = pHdr->uuidCreate;
182 pHdrConv->uuidModify = pHdr->uuidModify;
183 pHdrConv->uuidLinkage = pHdr->uuidLinkage;
184 pHdrConv->uuidParentModify = pHdr->uuidParentModify;
185 vdiConvGeometryEndianess(enmConv, &pHdrConv->LCHSGeometry, &pHdr->LCHSGeometry);
186}
187
188
189/**
190 * Internal: Set the appropriate endianess on all the Blocks pointed.
191 * @param enmConv Direction of the conversion.
192 * @param paBlocks Pointer to the block array.
193 * @param cEntries Number of entries in the block array.
194 *
195 * @note Unlike the other conversion functions this method does an in place conversion
196 * to avoid temporary memory allocations when writing the block array.
197 */
198static void vdiConvBlocksEndianess(VDIECONV enmConv, PVDIIMAGEBLOCKPOINTER paBlocks,
199 unsigned cEntries)
200{
201 for (unsigned i = 0; i < cEntries; i++)
202 paBlocks[i] = SET_ENDIAN_U32(enmConv, paBlocks[i]);
203}
204
205/**
206 * Internal: Flush the image file to disk.
207 */
208static void vdiFlushImage(PVDIIMAGEDESC pImage)
209{
210 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
211 {
212 /* Save header. */
213 int rc = vdiUpdateHeader(pImage);
214 AssertMsgRC(rc, ("vdiUpdateHeader() failed, filename=\"%s\", rc=%Rrc\n",
215 pImage->pszFilename, rc));
216 vdIfIoIntFileFlushSync(pImage->pIfIo, pImage->pStorage);
217 }
218}
219
220/**
221 * Internal: Free all allocated space for representing an image, and optionally
222 * delete the image from disk.
223 */
224static int vdiFreeImage(PVDIIMAGEDESC pImage, bool fDelete)
225{
226 int rc = VINF_SUCCESS;
227
228 /* Freeing a never allocated image (e.g. because the open failed) is
229 * not signalled as an error. After all nothing bad happens. */
230 if (pImage)
231 {
232 if (pImage->pStorage)
233 {
234 /* No point updating the file that is deleted anyway. */
235 if (!fDelete)
236 vdiFlushImage(pImage);
237
238 rc = vdIfIoIntFileClose(pImage->pIfIo, pImage->pStorage);
239 pImage->pStorage = NULL;
240 }
241
242 if (pImage->paBlocks)
243 {
244 RTMemFree(pImage->paBlocks);
245 pImage->paBlocks = NULL;
246 }
247
248 if (pImage->paBlocksRev)
249 {
250 RTMemFree(pImage->paBlocksRev);
251 pImage->paBlocksRev = NULL;
252 }
253
254 if (fDelete && pImage->pszFilename)
255 {
256 int rc2 = vdIfIoIntFileDelete(pImage->pIfIo, pImage->pszFilename);
257 if (RT_SUCCESS(rc))
258 rc = rc2;
259 }
260 }
261
262 LogFlowFunc(("returns %Rrc\n", rc));
263 return rc;
264}
265
266/**
267 * internal: return power of 2 or 0 if num error.
268 */
269static unsigned getPowerOfTwo(unsigned uNumber)
270{
271 if (uNumber == 0)
272 return 0;
273 unsigned uPower2 = 0;
274 while ((uNumber & 1) == 0)
275 {
276 uNumber >>= 1;
277 uPower2++;
278 }
279 return uNumber == 1 ? uPower2 : 0;
280}
281
282/**
283 * Internal: Init VDI preheader.
284 */
285static void vdiInitPreHeader(PVDIPREHEADER pPreHdr)
286{
287 pPreHdr->u32Signature = VDI_IMAGE_SIGNATURE;
288 pPreHdr->u32Version = VDI_IMAGE_VERSION;
289 memset(pPreHdr->szFileInfo, 0, sizeof(pPreHdr->szFileInfo));
290 strncat(pPreHdr->szFileInfo, VDI_IMAGE_FILE_INFO, sizeof(pPreHdr->szFileInfo)-1);
291}
292
293/**
294 * Internal: check VDI preheader.
295 */
296static int vdiValidatePreHeader(PVDIPREHEADER pPreHdr)
297{
298 if (pPreHdr->u32Signature != VDI_IMAGE_SIGNATURE)
299 return VERR_VD_VDI_INVALID_HEADER;
300
301 if ( VDI_GET_VERSION_MAJOR(pPreHdr->u32Version) != VDI_IMAGE_VERSION_MAJOR
302 && pPreHdr->u32Version != 0x00000002) /* old version. */
303 return VERR_VD_VDI_UNSUPPORTED_VERSION;
304
305 return VINF_SUCCESS;
306}
307
308/**
309 * Internal: translate VD image flags to VDI image type enum.
310 */
311static VDIIMAGETYPE vdiTranslateImageFlags2VDI(unsigned uImageFlags)
312{
313 if (uImageFlags & VD_IMAGE_FLAGS_FIXED)
314 return VDI_IMAGE_TYPE_FIXED;
315 else if (uImageFlags & VD_IMAGE_FLAGS_DIFF)
316 return VDI_IMAGE_TYPE_DIFF;
317 else
318 return VDI_IMAGE_TYPE_NORMAL;
319}
320
321/**
322 * Internal: translate VDI image type enum to VD image type enum.
323 */
324static unsigned vdiTranslateVDI2ImageFlags(VDIIMAGETYPE enmType)
325{
326 switch (enmType)
327 {
328 case VDI_IMAGE_TYPE_NORMAL:
329 return VD_IMAGE_FLAGS_NONE;
330 case VDI_IMAGE_TYPE_FIXED:
331 return VD_IMAGE_FLAGS_FIXED;
332 case VDI_IMAGE_TYPE_DIFF:
333 return VD_IMAGE_FLAGS_DIFF;
334 default:
335 AssertMsgFailed(("invalid VDIIMAGETYPE enmType=%d\n", (int)enmType));
336 return VD_IMAGE_FLAGS_NONE;
337 }
338}
339
340/**
341 * Internal: Init VDI header. Always use latest header version.
342 *
343 * @returns nothing.
344 * @param pHeader Assumes it was initially initialized to all zeros.
345 * @param uImageFlags Flags for this image.
346 * @param pszComment Optional comment to set for the image.
347 * @param cbDisk Size of the disk in bytes.
348 * @param cbBlock Size of one block in the image.
349 * @param cbBlockExtra Extra data for one block private to the image.
350 * @param cbDataAlign The alignment for all data structures.
351 */
352static void vdiInitHeader(PVDIHEADER pHeader, uint32_t uImageFlags,
353 const char *pszComment, uint64_t cbDisk,
354 uint32_t cbBlock, uint32_t cbBlockExtra,
355 uint32_t cbDataAlign)
356{
357 pHeader->uVersion = VDI_IMAGE_VERSION;
358 pHeader->u.v1plus.cbHeader = sizeof(VDIHEADER1PLUS);
359 pHeader->u.v1plus.u32Type = (uint32_t)vdiTranslateImageFlags2VDI(uImageFlags);
360 pHeader->u.v1plus.fFlags = (uImageFlags & VD_VDI_IMAGE_FLAGS_ZERO_EXPAND) ? 1 : 0;
361#ifdef VBOX_STRICT
362 char achZero[VDI_IMAGE_COMMENT_SIZE] = {0};
363 Assert(!memcmp(pHeader->u.v1plus.szComment, achZero, VDI_IMAGE_COMMENT_SIZE));
364#endif
365 pHeader->u.v1plus.szComment[0] = '\0';
366 if (pszComment)
367 {
368 AssertMsg(strlen(pszComment) < sizeof(pHeader->u.v1plus.szComment),
369 ("HDD Comment is too long, cb=%d\n", strlen(pszComment)));
370 strncat(pHeader->u.v1plus.szComment, pszComment, sizeof(pHeader->u.v1plus.szComment)-1);
371 }
372
373 /* Mark the legacy geometry not-calculated. */
374 pHeader->u.v1plus.LegacyGeometry.cCylinders = 0;
375 pHeader->u.v1plus.LegacyGeometry.cHeads = 0;
376 pHeader->u.v1plus.LegacyGeometry.cSectors = 0;
377 pHeader->u.v1plus.LegacyGeometry.cbSector = VDI_GEOMETRY_SECTOR_SIZE;
378 pHeader->u.v1plus.u32Dummy = 0; /* used to be the translation value */
379
380 pHeader->u.v1plus.cbDisk = cbDisk;
381 pHeader->u.v1plus.cbBlock = cbBlock;
382 pHeader->u.v1plus.cBlocks = (uint32_t)(cbDisk / cbBlock);
383 if (cbDisk % cbBlock)
384 pHeader->u.v1plus.cBlocks++;
385 pHeader->u.v1plus.cbBlockExtra = cbBlockExtra;
386 pHeader->u.v1plus.cBlocksAllocated = 0;
387
388 /* Init offsets. */
389 pHeader->u.v1plus.offBlocks = RT_ALIGN_32(sizeof(VDIPREHEADER) + sizeof(VDIHEADER1PLUS), cbDataAlign);
390 pHeader->u.v1plus.offData = RT_ALIGN_32(pHeader->u.v1plus.offBlocks + (pHeader->u.v1plus.cBlocks * sizeof(VDIIMAGEBLOCKPOINTER)), cbDataAlign);
391
392 /* Init uuids. */
393#ifdef _MSC_VER
394# pragma warning(disable:4366) /* (harmless "misalignment") */
395#endif
396 RTUuidCreate(&pHeader->u.v1plus.uuidCreate);
397 RTUuidClear(&pHeader->u.v1plus.uuidModify);
398 RTUuidClear(&pHeader->u.v1plus.uuidLinkage);
399 RTUuidClear(&pHeader->u.v1plus.uuidParentModify);
400#ifdef _MSC_VER
401# pragma warning(default:4366)
402#endif
403
404 /* Mark LCHS geometry not-calculated. */
405 pHeader->u.v1plus.LCHSGeometry.cCylinders = 0;
406 pHeader->u.v1plus.LCHSGeometry.cHeads = 0;
407 pHeader->u.v1plus.LCHSGeometry.cSectors = 0;
408 pHeader->u.v1plus.LCHSGeometry.cbSector = VDI_GEOMETRY_SECTOR_SIZE;
409}
410
411/**
412 * Internal: Check VDI header.
413 */
414static int vdiValidateHeader(PVDIHEADER pHeader)
415{
416 /* Check version-dependent header parameters. */
417 switch (GET_MAJOR_HEADER_VERSION(pHeader))
418 {
419 case 0:
420 {
421 /* Old header version. */
422 break;
423 }
424 case 1:
425 {
426 /* Current header version. */
427
428 if (pHeader->u.v1.cbHeader < sizeof(VDIHEADER1))
429 {
430 LogRel(("VDI: v1 header size wrong (%d < %d)\n",
431 pHeader->u.v1.cbHeader, sizeof(VDIHEADER1)));
432 return VERR_VD_VDI_INVALID_HEADER;
433 }
434
435 if (getImageBlocksOffset(pHeader) < (sizeof(VDIPREHEADER) + sizeof(VDIHEADER1)))
436 {
437 LogRel(("VDI: v1 blocks offset wrong (%d < %d)\n",
438 getImageBlocksOffset(pHeader), sizeof(VDIPREHEADER) + sizeof(VDIHEADER1)));
439 return VERR_VD_VDI_INVALID_HEADER;
440 }
441
442 if (getImageDataOffset(pHeader) < (getImageBlocksOffset(pHeader) + getImageBlocks(pHeader) * sizeof(VDIIMAGEBLOCKPOINTER)))
443 {
444 LogRel(("VDI: v1 image data offset wrong (%d < %d)\n",
445 getImageDataOffset(pHeader), getImageBlocksOffset(pHeader) + getImageBlocks(pHeader) * sizeof(VDIIMAGEBLOCKPOINTER)));
446 return VERR_VD_VDI_INVALID_HEADER;
447 }
448
449 break;
450 }
451 default:
452 /* Unsupported. */
453 return VERR_VD_VDI_UNSUPPORTED_VERSION;
454 }
455
456 /* Check common header parameters. */
457
458 bool fFailed = false;
459
460 if ( getImageType(pHeader) < VDI_IMAGE_TYPE_FIRST
461 || getImageType(pHeader) > VDI_IMAGE_TYPE_LAST)
462 {
463 LogRel(("VDI: bad image type %d\n", getImageType(pHeader)));
464 fFailed = true;
465 }
466
467 if (getImageFlags(pHeader) & ~VD_VDI_IMAGE_FLAGS_MASK)
468 {
469 LogRel(("VDI: bad image flags %08x\n", getImageFlags(pHeader)));
470 fFailed = true;
471 }
472
473 if ( getImageLCHSGeometry(pHeader)
474 && (getImageLCHSGeometry(pHeader))->cbSector != VDI_GEOMETRY_SECTOR_SIZE)
475 {
476 LogRel(("VDI: wrong sector size (%d != %d)\n",
477 (getImageLCHSGeometry(pHeader))->cbSector, VDI_GEOMETRY_SECTOR_SIZE));
478 fFailed = true;
479 }
480
481 if ( getImageDiskSize(pHeader) == 0
482 || getImageBlockSize(pHeader) == 0
483 || getImageBlocks(pHeader) == 0
484 || getPowerOfTwo(getImageBlockSize(pHeader)) == 0)
485 {
486 LogRel(("VDI: wrong size (%lld, %d, %d, %d)\n",
487 getImageDiskSize(pHeader), getImageBlockSize(pHeader),
488 getImageBlocks(pHeader), getPowerOfTwo(getImageBlockSize(pHeader))));
489 fFailed = true;
490 }
491
492 if (getImageBlocksAllocated(pHeader) > getImageBlocks(pHeader))
493 {
494 LogRel(("VDI: too many blocks allocated (%d > %d)\n"
495 " blocksize=%d disksize=%lld\n",
496 getImageBlocksAllocated(pHeader), getImageBlocks(pHeader),
497 getImageBlockSize(pHeader), getImageDiskSize(pHeader)));
498 fFailed = true;
499 }
500
501 if ( getImageExtraBlockSize(pHeader) != 0
502 && getPowerOfTwo(getImageExtraBlockSize(pHeader)) == 0)
503 {
504 LogRel(("VDI: wrong extra size (%d, %d)\n",
505 getImageExtraBlockSize(pHeader), getPowerOfTwo(getImageExtraBlockSize(pHeader))));
506 fFailed = true;
507 }
508
509 if ((uint64_t)getImageBlockSize(pHeader) * getImageBlocks(pHeader) < getImageDiskSize(pHeader))
510 {
511 LogRel(("VDI: wrong disk size (%d, %d, %lld)\n",
512 getImageBlockSize(pHeader), getImageBlocks(pHeader), getImageDiskSize(pHeader)));
513 fFailed = true;
514 }
515
516 if (RTUuidIsNull(getImageCreationUUID(pHeader)))
517 {
518 LogRel(("VDI: uuid of creator is 0\n"));
519 fFailed = true;
520 }
521
522 if (RTUuidIsNull(getImageModificationUUID(pHeader)))
523 {
524 LogRel(("VDI: uuid of modifier is 0\n"));
525 fFailed = true;
526 }
527
528 return fFailed ? VERR_VD_VDI_INVALID_HEADER : VINF_SUCCESS;
529}
530
531/**
532 * Internal: Set up VDIIMAGEDESC structure by image header.
533 */
534static void vdiSetupImageDesc(PVDIIMAGEDESC pImage)
535{
536 pImage->uImageFlags = getImageFlags(&pImage->Header);
537 pImage->uImageFlags |= vdiTranslateVDI2ImageFlags(getImageType(&pImage->Header));
538 pImage->offStartBlocks = getImageBlocksOffset(&pImage->Header);
539 pImage->offStartData = getImageDataOffset(&pImage->Header);
540 pImage->uBlockMask = getImageBlockSize(&pImage->Header) - 1;
541 pImage->uShiftOffset2Index = getPowerOfTwo(getImageBlockSize(&pImage->Header));
542 pImage->offStartBlockData = getImageExtraBlockSize(&pImage->Header);
543 pImage->cbAllocationBlock = getImageBlockSize(&pImage->Header);
544 pImage->cbTotalBlockData = pImage->offStartBlockData
545 + getImageBlockSize(&pImage->Header);
546}
547
548/**
549 * Sets up the complete image state from the given parameters.
550 *
551 * @returns VBox status code.
552 * @param pImage The VDI image descriptor.
553 * @param uImageFlags Image flags.
554 * @param pszComment The comment for the image (optional).
555 * @param cbSize Size of the resulting image in bytes.
556 * @param cbAllocationBlock Size of blocks allocated
557 * @param cbDataAlign Data alignment in bytes.
558 * @param pPCHSGeometry Physical CHS geometry for the image.
559 * @param pLCHSGeometry Logical CHS geometry for the image.
560 */
561static int vdiSetupImageState(PVDIIMAGEDESC pImage, unsigned uImageFlags, const char *pszComment,
562 uint64_t cbSize, uint32_t cbAllocationBlock, uint32_t cbDataAlign, PCVDGEOMETRY pPCHSGeometry,
563 PCVDGEOMETRY pLCHSGeometry)
564{
565 int rc = VINF_SUCCESS;
566
567 vdiInitPreHeader(&pImage->PreHeader);
568 vdiInitHeader(&pImage->Header, uImageFlags, pszComment, cbSize, cbAllocationBlock, 0,
569 cbDataAlign);
570 /* Save PCHS geometry. Not much work, and makes the flow of information
571 * quite a bit clearer - relying on the higher level isn't obvious. */
572 pImage->PCHSGeometry = *pPCHSGeometry;
573 /* Set LCHS geometry (legacy geometry is ignored for the current 1.1+). */
574 pImage->Header.u.v1plus.LCHSGeometry.cCylinders = pLCHSGeometry->cCylinders;
575 pImage->Header.u.v1plus.LCHSGeometry.cHeads = pLCHSGeometry->cHeads;
576 pImage->Header.u.v1plus.LCHSGeometry.cSectors = pLCHSGeometry->cSectors;
577 pImage->Header.u.v1plus.LCHSGeometry.cbSector = VDI_GEOMETRY_SECTOR_SIZE;
578
579 pImage->paBlocks = (PVDIIMAGEBLOCKPOINTER)RTMemAlloc(sizeof(VDIIMAGEBLOCKPOINTER) * getImageBlocks(&pImage->Header));
580 if (RT_LIKELY(pImage->paBlocks))
581 {
582 if (!(uImageFlags & VD_IMAGE_FLAGS_FIXED))
583 {
584 /* for growing images mark all blocks in paBlocks as free. */
585 for (unsigned i = 0; i < pImage->Header.u.v1.cBlocks; i++)
586 pImage->paBlocks[i] = VDI_IMAGE_BLOCK_FREE;
587 }
588 else
589 {
590 /* for fixed images mark all blocks in paBlocks as allocated */
591 for (unsigned i = 0; i < pImage->Header.u.v1.cBlocks; i++)
592 pImage->paBlocks[i] = i;
593 pImage->Header.u.v1.cBlocksAllocated = pImage->Header.u.v1.cBlocks;
594 }
595
596 /* Setup image parameters. */
597 vdiSetupImageDesc(pImage);
598 }
599 else
600 rc = VERR_NO_MEMORY;
601
602 return rc;
603}
604
605/**
606 * Creates the image file from the given descriptor.
607 *
608 * @returns VBox status code.
609 * @param pImage The VDI image descriptor.
610 * @param uOpenFlags Open flags.
611 * @param pIfProgress The progress interface.
612 * @param uPercentStart Progress starting point.
613 * @param uPercentSpan How many percent for this part of the operation is used.
614 */
615static int vdiImageCreateFile(PVDIIMAGEDESC pImage, unsigned uOpenFlags,
616 PVDINTERFACEPROGRESS pIfProgress, unsigned uPercentStart,
617 unsigned uPercentSpan)
618{
619 int rc = vdIfIoIntFileOpen(pImage->pIfIo, pImage->pszFilename,
620 VDOpenFlagsToFileOpenFlags(uOpenFlags & ~VD_OPEN_FLAGS_READONLY,
621 true /* fCreate */),
622 &pImage->pStorage);
623 if (RT_SUCCESS(rc))
624 {
625 if (pImage->uImageFlags & VD_IMAGE_FLAGS_FIXED)
626 {
627 uint64_t cbTotal = pImage->offStartData
628 + (uint64_t)getImageBlocks(&pImage->Header) * pImage->cbTotalBlockData;
629
630 /* Check the free space on the disk and leave early if there is not
631 * sufficient space available. */
632 int64_t cbFree = 0;
633 rc = vdIfIoIntFileGetFreeSpace(pImage->pIfIo, pImage->pszFilename, &cbFree);
634 if (RT_SUCCESS(rc) /* ignore errors */ && ((uint64_t)cbFree < cbTotal))
635 rc = vdIfError(pImage->pIfError, VERR_DISK_FULL, RT_SRC_POS,
636 N_("VDI: disk would overflow creating image '%s'"), pImage->pszFilename);
637 else
638 {
639 /*
640 * Allocate & commit whole file if fixed image, it must be more
641 * effective than expanding file by write operations.
642 */
643 rc = vdIfIoIntFileSetAllocationSize(pImage->pIfIo, pImage->pStorage, cbTotal, 0 /* fFlags */,
644 pIfProgress, uPercentStart, uPercentSpan);
645 pImage->cbImage = cbTotal;
646 }
647 }
648 else
649 {
650 /* Set file size to hold header and blocks array. */
651 rc = vdIfIoIntFileSetSize(pImage->pIfIo, pImage->pStorage, pImage->offStartData);
652 pImage->cbImage = pImage->offStartData;
653 }
654 if (RT_SUCCESS(rc))
655 {
656 /* Write pre-header. */
657 VDIPREHEADER PreHeader;
658 vdiConvPreHeaderEndianess(VDIECONV_H2F, &PreHeader, &pImage->PreHeader);
659 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pImage->pStorage, 0,
660 &PreHeader, sizeof(PreHeader));
661 if (RT_SUCCESS(rc))
662 {
663 /* Write header. */
664 VDIHEADER1PLUS Hdr;
665 vdiConvHeaderEndianessV1p(VDIECONV_H2F, &Hdr, &pImage->Header.u.v1plus);
666 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pImage->pStorage, sizeof(pImage->PreHeader),
667 &Hdr, sizeof(Hdr));
668 if (RT_SUCCESS(rc))
669 {
670 vdiConvBlocksEndianess(VDIECONV_H2F, pImage->paBlocks, getImageBlocks(&pImage->Header));
671 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pImage->pStorage, pImage->offStartBlocks, pImage->paBlocks,
672 getImageBlocks(&pImage->Header) * sizeof(VDIIMAGEBLOCKPOINTER));
673 vdiConvBlocksEndianess(VDIECONV_F2H, pImage->paBlocks, getImageBlocks(&pImage->Header));
674 if (RT_FAILURE(rc))
675 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VDI: writing block pointers failed for '%s'"),
676 pImage->pszFilename);
677 }
678 else
679 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VDI: writing header failed for '%s'"),
680 pImage->pszFilename);
681 }
682 else
683 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VDI: writing pre-header failed for '%s'"),
684 pImage->pszFilename);
685 }
686 else
687 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VDI: setting image size failed for '%s'"),
688 pImage->pszFilename);
689 }
690 else
691 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VDI: cannot create image '%s'"),
692 pImage->pszFilename);
693
694 return rc;
695}
696
697/**
698 * Internal: Create VDI image file.
699 */
700static int vdiCreateImage(PVDIIMAGEDESC pImage, uint64_t cbSize,
701 unsigned uImageFlags, const char *pszComment,
702 PCVDGEOMETRY pPCHSGeometry, PCVDGEOMETRY pLCHSGeometry,
703 PCRTUUID pUuid, unsigned uOpenFlags,
704 PVDINTERFACEPROGRESS pIfProgress, unsigned uPercentStart,
705 unsigned uPercentSpan, PVDINTERFACECONFIG pIfCfg)
706{
707 int rc = VINF_SUCCESS;
708 uint32_t cbDataAlign = VDI_DATA_ALIGN;
709 AssertPtr(pPCHSGeometry);
710 AssertPtr(pLCHSGeometry);
711
712 pImage->pIfError = VDIfErrorGet(pImage->pVDIfsDisk);
713 pImage->pIfIo = VDIfIoIntGet(pImage->pVDIfsImage);
714 AssertPtrReturn(pImage->pIfIo, VERR_INVALID_PARAMETER);
715
716 /* Special check for comment length. */
717 if ( VALID_PTR(pszComment)
718 && strlen(pszComment) >= VDI_IMAGE_COMMENT_SIZE)
719 rc = vdIfError(pImage->pIfError, VERR_VD_VDI_COMMENT_TOO_LONG, RT_SRC_POS,
720 N_("VDI: comment is too long for '%s'"), pImage->pszFilename);
721
722 PVDINTERFACECONFIG pImgCfg = VDIfConfigGet(pImage->pVDIfsImage);
723 if (pImgCfg)
724 {
725 rc = VDCFGQueryU32Def(pImgCfg, "AllocationBlockSize",
726 &pImage->cbAllocationBlock, VDI_IMAGE_DEFAULT_BLOCK_SIZE);
727 if (RT_FAILURE(rc))
728 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS,
729 N_("VDI: Getting AllocationBlockSize for '%s' failed (%Rrc)"), pImage->pszFilename, rc);
730 } else
731 pImage->cbAllocationBlock = VDI_IMAGE_DEFAULT_BLOCK_SIZE;
732
733 if (pIfCfg)
734 {
735 rc = VDCFGQueryU32Def(pIfCfg, "DataAlignment", &cbDataAlign, VDI_DATA_ALIGN);
736 if (RT_FAILURE(rc))
737 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS,
738 N_("VDI: Getting data alignment for '%s' failed (%Rrc)"), pImage->pszFilename, rc);
739 }
740
741 if (RT_SUCCESS(rc))
742 {
743
744 rc = vdiSetupImageState(pImage, uImageFlags, pszComment, cbSize,
745 pImage->cbAllocationBlock, cbDataAlign, pPCHSGeometry, pLCHSGeometry);
746
747 if (RT_SUCCESS(rc))
748 {
749 /* Use specified image uuid */
750 *getImageCreationUUID(&pImage->Header) = *pUuid;
751 /* Generate image last-modify uuid */
752 RTUuidCreate(getImageModificationUUID(&pImage->Header));
753
754 rc = vdiImageCreateFile(pImage, uOpenFlags, pIfProgress,
755 uPercentStart, uPercentSpan);
756 }
757 }
758
759 if (RT_SUCCESS(rc))
760 {
761 PVDREGIONDESC pRegion = &pImage->RegionList.aRegions[0];
762 pImage->RegionList.fFlags = 0;
763 pImage->RegionList.cRegions = 1;
764
765 pRegion->offRegion = 0; /* Disk start. */
766 pRegion->cbBlock = 512;
767 pRegion->enmDataForm = VDREGIONDATAFORM_RAW;
768 pRegion->enmMetadataForm = VDREGIONMETADATAFORM_NONE;
769 pRegion->cbData = 512;
770 pRegion->cbMetadata = 0;
771 pRegion->cRegionBlocksOrBytes = getImageDiskSize(&pImage->Header);
772
773 vdIfProgress(pIfProgress, uPercentStart + uPercentSpan);
774 }
775
776 if (RT_FAILURE(rc))
777 vdiFreeImage(pImage, rc != VERR_ALREADY_EXISTS);
778 return rc;
779}
780
781/**
782 * Reads and validates the header for the given image descriptor.
783 *
784 * @returns VBox status code.
785 * @param pImage The VDI image descriptor.
786 */
787static int vdiImageReadHeader(PVDIIMAGEDESC pImage)
788{
789 /* Get file size. */
790 int rc = vdIfIoIntFileGetSize(pImage->pIfIo, pImage->pStorage,
791 &pImage->cbImage);
792 if (RT_SUCCESS(rc))
793 {
794 /* Read pre-header. */
795 VDIPREHEADER PreHeader;
796 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pImage->pStorage, 0,
797 &PreHeader, sizeof(PreHeader));
798 if (RT_SUCCESS(rc))
799 {
800 vdiConvPreHeaderEndianess(VDIECONV_F2H, &pImage->PreHeader, &PreHeader);
801 rc = vdiValidatePreHeader(&pImage->PreHeader);
802 if (RT_SUCCESS(rc))
803 {
804 /* Read header. */
805 pImage->Header.uVersion = pImage->PreHeader.u32Version;
806 switch (GET_MAJOR_HEADER_VERSION(&pImage->Header))
807 {
808 case 0:
809 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pImage->pStorage, sizeof(pImage->PreHeader),
810 &pImage->Header.u.v0, sizeof(pImage->Header.u.v0));
811 if (RT_SUCCESS(rc))
812 vdiConvHeaderEndianessV0(VDIECONV_F2H, &pImage->Header.u.v0, &pImage->Header.u.v0);
813 else
814 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VDI: error reading v0 header in '%s'"), pImage->pszFilename);
815 break;
816 case 1:
817 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pImage->pStorage, sizeof(pImage->PreHeader),
818 &pImage->Header.u.v1, sizeof(pImage->Header.u.v1));
819 if (RT_SUCCESS(rc))
820 {
821 vdiConvHeaderEndianessV1(VDIECONV_F2H, &pImage->Header.u.v1, &pImage->Header.u.v1);
822 /* Convert VDI 1.1 images to VDI 1.1+ on open in read/write mode.
823 * Conversion is harmless, as any VirtualBox version supporting VDI
824 * 1.1 doesn't touch fields it doesn't know about. */
825 if ( !(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
826 && GET_MINOR_HEADER_VERSION(&pImage->Header) == 1
827 && pImage->Header.u.v1.cbHeader < sizeof(pImage->Header.u.v1plus))
828 {
829 pImage->Header.u.v1plus.cbHeader = sizeof(pImage->Header.u.v1plus);
830 /* Mark LCHS geometry not-calculated. */
831 pImage->Header.u.v1plus.LCHSGeometry.cCylinders = 0;
832 pImage->Header.u.v1plus.LCHSGeometry.cHeads = 0;
833 pImage->Header.u.v1plus.LCHSGeometry.cSectors = 0;
834 pImage->Header.u.v1plus.LCHSGeometry.cbSector = VDI_GEOMETRY_SECTOR_SIZE;
835 }
836 else if (pImage->Header.u.v1.cbHeader >= sizeof(pImage->Header.u.v1plus))
837 {
838 /* Read the actual VDI 1.1+ header completely. */
839 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pImage->pStorage, sizeof(pImage->PreHeader),
840 &pImage->Header.u.v1plus,
841 sizeof(pImage->Header.u.v1plus));
842 if (RT_SUCCESS(rc))
843 vdiConvHeaderEndianessV1p(VDIECONV_F2H, &pImage->Header.u.v1plus, &pImage->Header.u.v1plus);
844 else
845 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VDI: error reading v1.1+ header in '%s'"), pImage->pszFilename);
846 }
847 }
848 else
849 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VDI: error reading v1 header in '%s'"), pImage->pszFilename);
850 break;
851 default:
852 rc = vdIfError(pImage->pIfError, VERR_VD_VDI_UNSUPPORTED_VERSION, RT_SRC_POS,
853 N_("VDI: unsupported major version %u in '%s'"), GET_MAJOR_HEADER_VERSION(&pImage->Header), pImage->pszFilename);
854 }
855
856 if (RT_SUCCESS(rc))
857 {
858 rc = vdiValidateHeader(&pImage->Header);
859 if (RT_SUCCESS(rc))
860 {
861 /* Setup image parameters by header. */
862 vdiSetupImageDesc(pImage);
863
864 /*
865 * Until revision r111992 there was no check that the size was sector aligned
866 * when creating a new image and a bug in the VirtualBox GUI on OS X resulted
867 * in such images being created which caused issues when writing to the
868 * end of the image.
869 *
870 * Detect such images and repair the small damage by rounding down to the next
871 * aligned size. This is no problem as the guest would see a sector count
872 * only anyway from the device emulations so it already sees only the smaller
873 * size as result of the integer division of the size and sector size.
874 *
875 * This might not be written to the image if it is opened readonly
876 * which is not much of a problem because only writing to the last block
877 * causes trouble.
878 */
879 uint64_t cbDisk = getImageDiskSize(&pImage->Header);
880 if (cbDisk & 0x1ff)
881 setImageDiskSize(&pImage->Header, cbDisk & ~UINT64_C(0x1ff));
882 }
883 else
884 rc = vdIfError(pImage->pIfError, VERR_VD_VDI_INVALID_HEADER, RT_SRC_POS,
885 N_("VDI: invalid header in '%s'"), pImage->pszFilename);
886 }
887 }
888 else
889 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VDI: invalid pre-header in '%s'"), pImage->pszFilename);
890 }
891 else
892 {
893 vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VDI: error reading pre-header in '%s'"), pImage->pszFilename);
894 rc = VERR_VD_VDI_INVALID_HEADER;
895 }
896 }
897 else
898 {
899 vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VDI: error getting the image size in '%s'"), pImage->pszFilename);
900 rc = VERR_VD_VDI_INVALID_HEADER;
901 }
902
903 return rc;
904}
905
906/**
907 * Creates the back resolving table for the image for the discard operation.
908 *
909 * @returns VBox status code.
910 * @param pImage The VDI image descriptor.
911 */
912static int vdiImageBackResolvTblCreate(PVDIIMAGEDESC pImage)
913{
914 int rc = VINF_SUCCESS;
915
916 /*
917 * Any error or inconsistency results in a fail because this might
918 * get us into trouble later on.
919 */
920 pImage->paBlocksRev = (unsigned *)RTMemAllocZ(sizeof(unsigned) * getImageBlocks(&pImage->Header));
921 if (pImage->paBlocksRev)
922 {
923 unsigned cBlocksAllocated = getImageBlocksAllocated(&pImage->Header);
924 unsigned cBlocks = getImageBlocks(&pImage->Header);
925
926 for (unsigned i = 0; i < cBlocks; i++)
927 pImage->paBlocksRev[i] = VDI_IMAGE_BLOCK_FREE;
928
929 for (unsigned i = 0; i < cBlocks; i++)
930 {
931 VDIIMAGEBLOCKPOINTER ptrBlock = pImage->paBlocks[i];
932 if (IS_VDI_IMAGE_BLOCK_ALLOCATED(ptrBlock))
933 {
934 if (ptrBlock < cBlocksAllocated)
935 {
936 if (pImage->paBlocksRev[ptrBlock] == VDI_IMAGE_BLOCK_FREE)
937 pImage->paBlocksRev[ptrBlock] = i;
938 else
939 {
940 rc = VERR_VD_VDI_INVALID_HEADER;
941 break;
942 }
943 }
944 else
945 {
946 rc = VERR_VD_VDI_INVALID_HEADER;
947 break;
948 }
949 }
950 }
951 }
952 else
953 rc = VERR_NO_MEMORY;
954
955 return rc;
956}
957
958/**
959 * Internal: Open a VDI image.
960 */
961static int vdiOpenImage(PVDIIMAGEDESC pImage, unsigned uOpenFlags)
962{
963 pImage->uOpenFlags = uOpenFlags;
964
965 pImage->pIfError = VDIfErrorGet(pImage->pVDIfsDisk);
966 pImage->pIfIo = VDIfIoIntGet(pImage->pVDIfsImage);
967 AssertPtrReturn(pImage->pIfIo, VERR_INVALID_PARAMETER);
968
969 /*
970 * Open the image.
971 */
972 int rc = vdIfIoIntFileOpen(pImage->pIfIo, pImage->pszFilename,
973 VDOpenFlagsToFileOpenFlags(uOpenFlags, false /* fCreate */),
974 &pImage->pStorage);
975 if (RT_SUCCESS(rc))
976 {
977 rc = vdiImageReadHeader(pImage);
978 if (RT_SUCCESS(rc))
979 {
980 /* Allocate memory for blocks array. */
981 pImage->paBlocks = (PVDIIMAGEBLOCKPOINTER)RTMemAlloc(sizeof(VDIIMAGEBLOCKPOINTER) * getImageBlocks(&pImage->Header));
982 if (RT_LIKELY(pImage->paBlocks))
983 {
984 /* Read blocks array. */
985 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pImage->pStorage, pImage->offStartBlocks, pImage->paBlocks,
986 getImageBlocks(&pImage->Header) * sizeof(VDIIMAGEBLOCKPOINTER));
987 if (RT_SUCCESS(rc))
988 {
989 vdiConvBlocksEndianess(VDIECONV_F2H, pImage->paBlocks, getImageBlocks(&pImage->Header));
990
991 if (uOpenFlags & VD_OPEN_FLAGS_DISCARD)
992 rc = vdiImageBackResolvTblCreate(pImage);
993 }
994 else
995 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VDI: Error reading the block table in '%s'"), pImage->pszFilename);
996 }
997 else
998 rc = vdIfError(pImage->pIfError, VERR_NO_MEMORY, RT_SRC_POS,
999 N_("VDI: Error allocating memory for the block table in '%s'"), pImage->pszFilename);;
1000 }
1001 }
1002 /* else: Do NOT signal an appropriate error here, as the VD layer has the
1003 * choice of retrying the open if it failed. */
1004
1005 if (RT_SUCCESS(rc))
1006 {
1007 PVDREGIONDESC pRegion = &pImage->RegionList.aRegions[0];
1008 pImage->RegionList.fFlags = 0;
1009 pImage->RegionList.cRegions = 1;
1010
1011 pRegion->offRegion = 0; /* Disk start. */
1012 pRegion->cbBlock = 512;
1013 pRegion->enmDataForm = VDREGIONDATAFORM_RAW;
1014 pRegion->enmMetadataForm = VDREGIONMETADATAFORM_NONE;
1015 pRegion->cbData = 512;
1016 pRegion->cbMetadata = 0;
1017 pRegion->cRegionBlocksOrBytes = getImageDiskSize(&pImage->Header);
1018 if (uOpenFlags & VD_OPEN_FLAGS_INFO)
1019 {
1020 PVDINTERFACECONFIG pImgCfg = VDIfConfigGet(pImage->pVDIfsImage);
1021 if (pImgCfg)
1022 {
1023 rc = VDCFGUpdateU64(pImgCfg, true, "AllocationBlockSize", pImage->cbAllocationBlock);
1024 if (RT_FAILURE(rc))
1025 return rc;
1026 }
1027 }
1028 }
1029 else
1030 vdiFreeImage(pImage, false);
1031 return rc;
1032}
1033
1034/**
1035 * Internal: Save header to file.
1036 */
1037static int vdiUpdateHeader(PVDIIMAGEDESC pImage)
1038{
1039 int rc;
1040 switch (GET_MAJOR_HEADER_VERSION(&pImage->Header))
1041 {
1042 case 0:
1043 {
1044 VDIHEADER0 Hdr;
1045 vdiConvHeaderEndianessV0(VDIECONV_H2F, &Hdr, &pImage->Header.u.v0);
1046 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pImage->pStorage, sizeof(VDIPREHEADER),
1047 &Hdr, sizeof(Hdr));
1048 break;
1049 }
1050 case 1:
1051 if (pImage->Header.u.v1plus.cbHeader < sizeof(pImage->Header.u.v1plus))
1052 {
1053 VDIHEADER1 Hdr;
1054 vdiConvHeaderEndianessV1(VDIECONV_H2F, &Hdr, &pImage->Header.u.v1);
1055 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pImage->pStorage, sizeof(VDIPREHEADER),
1056 &Hdr, sizeof(Hdr));
1057 }
1058 else
1059 {
1060 VDIHEADER1PLUS Hdr;
1061 vdiConvHeaderEndianessV1p(VDIECONV_H2F, &Hdr, &pImage->Header.u.v1plus);
1062 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pImage->pStorage, sizeof(VDIPREHEADER),
1063 &Hdr, sizeof(Hdr));
1064 }
1065 break;
1066 default:
1067 rc = VERR_VD_VDI_UNSUPPORTED_VERSION;
1068 break;
1069 }
1070 AssertMsgRC(rc, ("vdiUpdateHeader failed, filename=\"%s\" rc=%Rrc\n", pImage->pszFilename, rc));
1071 return rc;
1072}
1073
1074/**
1075 * Internal: Save header to file - async version.
1076 */
1077static int vdiUpdateHeaderAsync(PVDIIMAGEDESC pImage, PVDIOCTX pIoCtx)
1078{
1079 int rc;
1080 switch (GET_MAJOR_HEADER_VERSION(&pImage->Header))
1081 {
1082 case 0:
1083 {
1084 VDIHEADER0 Hdr;
1085 vdiConvHeaderEndianessV0(VDIECONV_H2F, &Hdr, &pImage->Header.u.v0);
1086 rc = vdIfIoIntFileWriteMeta(pImage->pIfIo, pImage->pStorage,
1087 sizeof(VDIPREHEADER), &Hdr, sizeof(Hdr),
1088 pIoCtx, NULL, NULL);
1089 break;
1090 }
1091 case 1:
1092 if (pImage->Header.u.v1plus.cbHeader < sizeof(pImage->Header.u.v1plus))
1093 {
1094 VDIHEADER1 Hdr;
1095 vdiConvHeaderEndianessV1(VDIECONV_H2F, &Hdr, &pImage->Header.u.v1);
1096 rc = vdIfIoIntFileWriteMeta(pImage->pIfIo, pImage->pStorage,
1097 sizeof(VDIPREHEADER), &Hdr, sizeof(Hdr),
1098 pIoCtx, NULL, NULL);
1099 }
1100 else
1101 {
1102 VDIHEADER1PLUS Hdr;
1103 vdiConvHeaderEndianessV1p(VDIECONV_H2F, &Hdr, &pImage->Header.u.v1plus);
1104 rc = vdIfIoIntFileWriteMeta(pImage->pIfIo, pImage->pStorage,
1105 sizeof(VDIPREHEADER), &Hdr, sizeof(Hdr),
1106 pIoCtx, NULL, NULL);
1107 }
1108 break;
1109 default:
1110 rc = VERR_VD_VDI_UNSUPPORTED_VERSION;
1111 break;
1112 }
1113 AssertMsg(RT_SUCCESS(rc) || rc == VERR_VD_ASYNC_IO_IN_PROGRESS,
1114 ("vdiUpdateHeader failed, filename=\"%s\" rc=%Rrc\n", pImage->pszFilename, rc));
1115 return rc;
1116}
1117
1118/**
1119 * Internal: Save block pointer to file, save header to file.
1120 */
1121static int vdiUpdateBlockInfo(PVDIIMAGEDESC pImage, unsigned uBlock)
1122{
1123 /* Update image header. */
1124 int rc = vdiUpdateHeader(pImage);
1125 if (RT_SUCCESS(rc))
1126 {
1127 /* write only one block pointer. */
1128 VDIIMAGEBLOCKPOINTER ptrBlock = RT_H2LE_U32(pImage->paBlocks[uBlock]);
1129 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pImage->pStorage,
1130 pImage->offStartBlocks + uBlock * sizeof(VDIIMAGEBLOCKPOINTER),
1131 &ptrBlock, sizeof(VDIIMAGEBLOCKPOINTER));
1132 AssertMsgRC(rc, ("vdiUpdateBlockInfo failed to update block=%u, filename=\"%s\", rc=%Rrc\n",
1133 uBlock, pImage->pszFilename, rc));
1134 }
1135 return rc;
1136}
1137
1138/**
1139 * Internal: Save block pointer to file, save header to file - async version.
1140 */
1141static int vdiUpdateBlockInfoAsync(PVDIIMAGEDESC pImage, unsigned uBlock,
1142 PVDIOCTX pIoCtx, bool fUpdateHdr)
1143{
1144 int rc = VINF_SUCCESS;
1145
1146 /* Update image header. */
1147 if (fUpdateHdr)
1148 rc = vdiUpdateHeaderAsync(pImage, pIoCtx);
1149
1150 if (RT_SUCCESS(rc) || rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
1151 {
1152 /* write only one block pointer. */
1153 VDIIMAGEBLOCKPOINTER ptrBlock = RT_H2LE_U32(pImage->paBlocks[uBlock]);
1154 rc = vdIfIoIntFileWriteMeta(pImage->pIfIo, pImage->pStorage,
1155 pImage->offStartBlocks + uBlock * sizeof(VDIIMAGEBLOCKPOINTER),
1156 &ptrBlock, sizeof(VDIIMAGEBLOCKPOINTER),
1157 pIoCtx, NULL, NULL);
1158 AssertMsg(RT_SUCCESS(rc) || rc == VERR_VD_ASYNC_IO_IN_PROGRESS,
1159 ("vdiUpdateBlockInfo failed to update block=%u, filename=\"%s\", rc=%Rrc\n",
1160 uBlock, pImage->pszFilename, rc));
1161 }
1162 return rc;
1163}
1164
1165/**
1166 * Internal: Flush the image file to disk - async version.
1167 */
1168static int vdiFlushImageIoCtx(PVDIIMAGEDESC pImage, PVDIOCTX pIoCtx)
1169{
1170 int rc = VINF_SUCCESS;
1171
1172 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
1173 {
1174 /* Save header. */
1175 rc = vdiUpdateHeaderAsync(pImage, pIoCtx);
1176 AssertMsg(RT_SUCCESS(rc) || rc == VERR_VD_ASYNC_IO_IN_PROGRESS,
1177 ("vdiUpdateHeaderAsync() failed, filename=\"%s\", rc=%Rrc\n",
1178 pImage->pszFilename, rc));
1179 rc = vdIfIoIntFileFlush(pImage->pIfIo, pImage->pStorage, pIoCtx, NULL, NULL);
1180 AssertMsg(RT_SUCCESS(rc) || rc == VERR_VD_ASYNC_IO_IN_PROGRESS,
1181 ("Flushing data to disk failed rc=%Rrc\n", rc));
1182 }
1183
1184 return rc;
1185}
1186
1187/**
1188 * Completion callback for meta/userdata reads or writes.
1189 *
1190 * @return VBox status code.
1191 * VINF_SUCCESS if everything was successful and the transfer can continue.
1192 * VERR_VD_ASYNC_IO_IN_PROGRESS if there is another data transfer pending.
1193 * @param pBackendData The opaque backend data.
1194 * @param pIoCtx I/O context associated with this request.
1195 * @param pvUser Opaque user data passed during a read/write request.
1196 * @param rcReq Status code for the completed request.
1197 */
1198static DECLCALLBACK(int) vdiDiscardBlockAsyncUpdate(void *pBackendData, PVDIOCTX pIoCtx, void *pvUser, int rcReq)
1199{
1200 RT_NOREF1(rcReq);
1201 int rc = VINF_SUCCESS;
1202 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1203 PVDIBLOCKDISCARDASYNC pDiscardAsync = (PVDIBLOCKDISCARDASYNC)pvUser;
1204
1205 switch (pDiscardAsync->enmState)
1206 {
1207 case VDIBLOCKDISCARDSTATE_READ_BLOCK:
1208 {
1209 PVDMETAXFER pMetaXfer;
1210 uint64_t u64Offset = (uint64_t)pDiscardAsync->idxLastBlock * pImage->cbTotalBlockData + pImage->offStartData;
1211 rc = vdIfIoIntFileReadMeta(pImage->pIfIo, pImage->pStorage, u64Offset,
1212 pDiscardAsync->pvBlock, pImage->cbTotalBlockData, pIoCtx,
1213 &pMetaXfer, vdiDiscardBlockAsyncUpdate, pDiscardAsync);
1214 if (RT_FAILURE(rc))
1215 break;
1216
1217 /* Release immediately and go to next step. */
1218 vdIfIoIntMetaXferRelease(pImage->pIfIo, pMetaXfer);
1219 pDiscardAsync->enmState = VDIBLOCKDISCARDSTATE_WRITE_BLOCK;
1220 }
1221 RT_FALL_THRU();
1222 case VDIBLOCKDISCARDSTATE_WRITE_BLOCK:
1223 {
1224 /* Block read complete. Write to the new location (discarded block). */
1225 uint64_t u64Offset = (uint64_t)pDiscardAsync->ptrBlockDiscard * pImage->cbTotalBlockData + pImage->offStartData;
1226 rc = vdIfIoIntFileWriteMeta(pImage->pIfIo, pImage->pStorage, u64Offset,
1227 pDiscardAsync->pvBlock, pImage->cbTotalBlockData, pIoCtx,
1228 vdiDiscardBlockAsyncUpdate, pDiscardAsync);
1229
1230 pDiscardAsync->enmState = VDIBLOCKDISCARDSTATE_UPDATE_METADATA;
1231 if (RT_FAILURE(rc))
1232 break;
1233 }
1234 RT_FALL_THRU();
1235 case VDIBLOCKDISCARDSTATE_UPDATE_METADATA:
1236 {
1237 int rc2;
1238
1239 /* Block write complete. Update metadata. */
1240 pImage->paBlocksRev[pDiscardAsync->idxLastBlock] = VDI_IMAGE_BLOCK_FREE;
1241 pImage->paBlocks[pDiscardAsync->uBlock] = VDI_IMAGE_BLOCK_ZERO;
1242
1243 if (pDiscardAsync->idxLastBlock != pDiscardAsync->ptrBlockDiscard)
1244 {
1245 pImage->paBlocks[pDiscardAsync->uBlockLast] = pDiscardAsync->ptrBlockDiscard;
1246 pImage->paBlocksRev[pDiscardAsync->ptrBlockDiscard] = pDiscardAsync->uBlockLast;
1247
1248 rc = vdiUpdateBlockInfoAsync(pImage, pDiscardAsync->uBlockLast, pIoCtx, false /* fUpdateHdr */);
1249 if ( RT_FAILURE(rc)
1250 && rc != VERR_VD_ASYNC_IO_IN_PROGRESS)
1251 break;
1252 }
1253
1254 setImageBlocksAllocated(&pImage->Header, pDiscardAsync->idxLastBlock);
1255 rc = vdiUpdateBlockInfoAsync(pImage, pDiscardAsync->uBlock, pIoCtx, true /* fUpdateHdr */);
1256 if ( RT_FAILURE(rc)
1257 && rc != VERR_VD_ASYNC_IO_IN_PROGRESS)
1258 break;
1259
1260 pImage->cbImage -= pImage->cbTotalBlockData;
1261 LogFlowFunc(("Set new size %llu\n", pImage->cbImage));
1262 rc2 = vdIfIoIntFileSetSize(pImage->pIfIo, pImage->pStorage, pImage->cbImage);
1263 if (RT_FAILURE(rc2))
1264 rc = rc2;
1265
1266 /* Free discard state. */
1267 RTMemFree(pDiscardAsync->pvBlock);
1268 RTMemFree(pDiscardAsync);
1269 break;
1270 }
1271 default:
1272 AssertMsgFailed(("Invalid state %d\n", pDiscardAsync->enmState));
1273 }
1274
1275 if (rc == VERR_VD_NOT_ENOUGH_METADATA)
1276 rc = VERR_VD_ASYNC_IO_IN_PROGRESS;
1277
1278 return rc;
1279}
1280
1281/**
1282 * Internal: Discard a whole block from the image filling the created hole with
1283 * data from another block - async I/O version.
1284 *
1285 * @returns VBox status code.
1286 * @param pImage VDI image instance data.
1287 * @param pIoCtx I/O context associated with this request.
1288 * @param uBlock The block to discard.
1289 * @param pvBlock Memory to use for the I/O.
1290 */
1291static int vdiDiscardBlockAsync(PVDIIMAGEDESC pImage, PVDIOCTX pIoCtx,
1292 unsigned uBlock, void *pvBlock)
1293{
1294 int rc = VINF_SUCCESS;
1295 PVDIBLOCKDISCARDASYNC pDiscardAsync = NULL;
1296
1297 LogFlowFunc(("pImage=%#p uBlock=%u pvBlock=%#p\n",
1298 pImage, uBlock, pvBlock));
1299
1300 pDiscardAsync = (PVDIBLOCKDISCARDASYNC)RTMemAllocZ(sizeof(VDIBLOCKDISCARDASYNC));
1301 if (RT_UNLIKELY(!pDiscardAsync))
1302 return VERR_NO_MEMORY;
1303
1304 /* Init block discard state. */
1305 pDiscardAsync->uBlock = uBlock;
1306 pDiscardAsync->pvBlock = pvBlock;
1307 pDiscardAsync->ptrBlockDiscard = pImage->paBlocks[uBlock];
1308 pDiscardAsync->idxLastBlock = getImageBlocksAllocated(&pImage->Header) - 1;
1309 pDiscardAsync->uBlockLast = pImage->paBlocksRev[pDiscardAsync->idxLastBlock];
1310
1311 /*
1312 * The block is empty, remove it.
1313 * Read the last block of the image first.
1314 */
1315 if (pDiscardAsync->idxLastBlock != pDiscardAsync->ptrBlockDiscard)
1316 {
1317 LogFlowFunc(("Moving block [%u]=%u into [%u]=%u\n",
1318 pDiscardAsync->uBlockLast, pDiscardAsync->idxLastBlock,
1319 uBlock, pImage->paBlocks[uBlock]));
1320 pDiscardAsync->enmState = VDIBLOCKDISCARDSTATE_READ_BLOCK;
1321 }
1322 else
1323 {
1324 pDiscardAsync->enmState = VDIBLOCKDISCARDSTATE_UPDATE_METADATA; /* Start immediately to shrink the image. */
1325 LogFlowFunc(("Discard last block [%u]=%u\n", uBlock, pImage->paBlocks[uBlock]));
1326 }
1327
1328 /* Call the update callback directly. */
1329 rc = vdiDiscardBlockAsyncUpdate(pImage, pIoCtx, pDiscardAsync, VINF_SUCCESS);
1330
1331 LogFlowFunc(("returns rc=%Rrc\n", rc));
1332 return rc;
1333}
1334
1335/**
1336 * Internal: Creates a allocation bitmap from the given data.
1337 * Sectors which contain only 0 are marked as unallocated and sectors with
1338 * other data as allocated.
1339 *
1340 * @returns Pointer to the allocation bitmap or NULL on failure.
1341 * @param pvData The data to create the allocation bitmap for.
1342 * @param cbData Number of bytes in the buffer.
1343 */
1344static void *vdiAllocationBitmapCreate(void *pvData, size_t cbData)
1345{
1346 Assert(cbData <= UINT32_MAX / 8);
1347 uint32_t cSectors = (uint32_t)(cbData / 512);
1348 uint32_t uSectorCur = 0;
1349 void *pbmAllocationBitmap = NULL;
1350
1351 Assert(!(cbData % 512));
1352 Assert(!(cSectors % 8));
1353
1354 pbmAllocationBitmap = RTMemAllocZ(cSectors / 8);
1355 if (!pbmAllocationBitmap)
1356 return NULL;
1357
1358 while (uSectorCur < cSectors)
1359 {
1360 int idxSet = ASMBitFirstSet((uint8_t *)pvData + uSectorCur * 512, (uint32_t)cbData * 8);
1361
1362 if (idxSet != -1)
1363 {
1364 unsigned idxSectorAlloc = idxSet / 8 / 512;
1365 ASMBitSet(pbmAllocationBitmap, uSectorCur + idxSectorAlloc);
1366
1367 uSectorCur += idxSectorAlloc + 1;
1368 cbData -= (idxSectorAlloc + 1) * 512;
1369 }
1370 else
1371 break;
1372 }
1373
1374 return pbmAllocationBitmap;
1375}
1376
1377
1378/**
1379 * Updates the state of the async cluster allocation.
1380 *
1381 * @returns VBox status code.
1382 * @param pBackendData The opaque backend data.
1383 * @param pIoCtx I/O context associated with this request.
1384 * @param pvUser Opaque user data passed during a read/write request.
1385 * @param rcReq Status code for the completed request.
1386 */
1387static DECLCALLBACK(int) vdiBlockAllocUpdate(void *pBackendData, PVDIOCTX pIoCtx, void *pvUser, int rcReq)
1388{
1389 int rc = VINF_SUCCESS;
1390 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1391 PVDIASYNCBLOCKALLOC pBlockAlloc = (PVDIASYNCBLOCKALLOC)pvUser;
1392
1393 if (RT_SUCCESS(rcReq))
1394 {
1395 pImage->cbImage += pImage->cbTotalBlockData;
1396 pImage->paBlocks[pBlockAlloc->uBlock] = pBlockAlloc->cBlocksAllocated;
1397
1398 if (pImage->paBlocksRev)
1399 pImage->paBlocksRev[pBlockAlloc->cBlocksAllocated] = pBlockAlloc->uBlock;
1400
1401 setImageBlocksAllocated(&pImage->Header, pBlockAlloc->cBlocksAllocated + 1);
1402 rc = vdiUpdateBlockInfoAsync(pImage, pBlockAlloc->uBlock, pIoCtx,
1403 true /* fUpdateHdr */);
1404 }
1405 /* else: I/O error don't update the block table. */
1406
1407 RTMemFree(pBlockAlloc);
1408 return rc;
1409}
1410
1411/** @copydoc VDIMAGEBACKEND::pfnProbe */
1412static DECLCALLBACK(int) vdiProbe(const char *pszFilename, PVDINTERFACE pVDIfsDisk,
1413 PVDINTERFACE pVDIfsImage, VDTYPE enmDesiredType, VDTYPE *penmType)
1414{
1415 RT_NOREF(enmDesiredType);
1416 LogFlowFunc(("pszFilename=\"%s\"\n", pszFilename));
1417 int rc = VINF_SUCCESS;
1418
1419 AssertReturn((VALID_PTR(pszFilename) && *pszFilename), VERR_INVALID_PARAMETER);
1420
1421 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)RTMemAllocZ(RT_UOFFSETOF(VDIIMAGEDESC, RegionList.aRegions[1]));
1422 if (RT_LIKELY(pImage))
1423 {
1424 pImage->pszFilename = pszFilename;
1425 pImage->pStorage = NULL;
1426 pImage->paBlocks = NULL;
1427 pImage->pVDIfsDisk = pVDIfsDisk;
1428 pImage->pVDIfsImage = pVDIfsImage;
1429
1430 rc = vdiOpenImage(pImage, VD_OPEN_FLAGS_INFO | VD_OPEN_FLAGS_READONLY);
1431 vdiFreeImage(pImage, false);
1432 RTMemFree(pImage);
1433
1434 if (RT_SUCCESS(rc))
1435 *penmType = VDTYPE_HDD;
1436 }
1437 else
1438 rc = VERR_NO_MEMORY;
1439
1440 LogFlowFunc(("returns %Rrc\n", rc));
1441 return rc;
1442}
1443
1444/** @copydoc VDIMAGEBACKEND::pfnOpen */
1445static DECLCALLBACK(int) vdiOpen(const char *pszFilename, unsigned uOpenFlags,
1446 PVDINTERFACE pVDIfsDisk, PVDINTERFACE pVDIfsImage,
1447 VDTYPE enmType, void **ppBackendData)
1448{
1449 RT_NOREF1(enmType); /**< @todo r=klaus make use of the type info. */
1450
1451 LogFlowFunc(("pszFilename=\"%s\" uOpenFlags=%#x pVDIfsDisk=%#p pVDIfsImage=%#p enmType=%u ppBackendData=%#p\n",
1452 pszFilename, uOpenFlags, pVDIfsDisk, pVDIfsImage, enmType, ppBackendData));
1453 int rc;
1454
1455 /* Check open flags. All valid flags are supported. */
1456 AssertReturn(!(uOpenFlags & ~VD_OPEN_FLAGS_MASK), VERR_INVALID_PARAMETER);
1457 AssertReturn((VALID_PTR(pszFilename) && *pszFilename), VERR_INVALID_PARAMETER);
1458
1459 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)RTMemAllocZ(RT_UOFFSETOF(VDIIMAGEDESC, RegionList.aRegions[1]));
1460 if (RT_LIKELY(pImage))
1461 {
1462 pImage->pszFilename = pszFilename;
1463 pImage->pStorage = NULL;
1464 pImage->paBlocks = NULL;
1465 pImage->pVDIfsDisk = pVDIfsDisk;
1466 pImage->pVDIfsImage = pVDIfsImage;
1467
1468 rc = vdiOpenImage(pImage, uOpenFlags);
1469 if (RT_SUCCESS(rc))
1470 *ppBackendData = pImage;
1471 else
1472 RTMemFree(pImage);
1473 }
1474 else
1475 rc = VERR_NO_MEMORY;
1476
1477 LogFlowFunc(("returns %Rrc (pBackendData=%#p)\n", rc, *ppBackendData));
1478 return rc;
1479}
1480
1481/** @copydoc VDIMAGEBACKEND::pfnCreate */
1482static DECLCALLBACK(int) vdiCreate(const char *pszFilename, uint64_t cbSize,
1483 unsigned uImageFlags, const char *pszComment,
1484 PCVDGEOMETRY pPCHSGeometry, PCVDGEOMETRY pLCHSGeometry,
1485 PCRTUUID pUuid, unsigned uOpenFlags,
1486 unsigned uPercentStart, unsigned uPercentSpan,
1487 PVDINTERFACE pVDIfsDisk, PVDINTERFACE pVDIfsImage,
1488 PVDINTERFACE pVDIfsOperation, VDTYPE enmType,
1489 void **ppBackendData)
1490{
1491 LogFlowFunc(("pszFilename=\"%s\" cbSize=%llu uImageFlags=%#x pszComment=\"%s\" pPCHSGeometry=%#p pLCHSGeometry=%#p Uuid=%RTuuid uOpenFlags=%#x uPercentStart=%u uPercentSpan=%u pVDIfsDisk=%#p pVDIfsImage=%#p pVDIfsOperation=%#p enmType=%u ppBackendData=%#p\n",
1492 pszFilename, cbSize, uImageFlags, pszComment, pPCHSGeometry, pLCHSGeometry, pUuid, uOpenFlags, uPercentStart, uPercentSpan, pVDIfsDisk, pVDIfsImage, pVDIfsOperation, enmType, ppBackendData));
1493 int rc;
1494
1495 /* Check the VD container type and image flags. */
1496 if ( enmType != VDTYPE_HDD
1497 || (uImageFlags & ~VD_VDI_IMAGE_FLAGS_MASK) != 0)
1498 return VERR_VD_INVALID_TYPE;
1499
1500 /* Check size. Maximum 4PB-3M. No tricks with adjusting the 1M block size
1501 * so far, which would extend the size. */
1502 if ( !cbSize
1503 || cbSize >= _1P * 4 - _1M * 3
1504 || cbSize < VDI_IMAGE_DEFAULT_BLOCK_SIZE
1505 || (cbSize % 512))
1506 return VERR_VD_INVALID_SIZE;
1507
1508 /* Check open flags. All valid flags are supported. */
1509 AssertReturn(!(uOpenFlags & ~VD_OPEN_FLAGS_MASK), VERR_INVALID_PARAMETER);
1510 AssertReturn( VALID_PTR(pszFilename)
1511 && *pszFilename
1512 && VALID_PTR(pPCHSGeometry)
1513 && VALID_PTR(pLCHSGeometry), VERR_INVALID_PARAMETER);
1514
1515 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)RTMemAllocZ(RT_UOFFSETOF(VDIIMAGEDESC, RegionList.aRegions[1]));
1516 if (RT_LIKELY(pImage))
1517 {
1518 PVDINTERFACEPROGRESS pIfProgress = VDIfProgressGet(pVDIfsOperation);
1519 PVDINTERFACECONFIG pIfCfg = VDIfConfigGet(pVDIfsOperation);
1520 pImage->pszFilename = pszFilename;
1521 pImage->pStorage = NULL;
1522 pImage->paBlocks = NULL;
1523 pImage->pVDIfsDisk = pVDIfsDisk;
1524 pImage->pVDIfsImage = pVDIfsImage;
1525
1526 rc = vdiCreateImage(pImage, cbSize, uImageFlags, pszComment,
1527 pPCHSGeometry, pLCHSGeometry, pUuid, uOpenFlags,
1528 pIfProgress, uPercentStart, uPercentSpan, pIfCfg);
1529 if (RT_SUCCESS(rc))
1530 {
1531 /* So far the image is opened in read/write mode. Make sure the
1532 * image is opened in read-only mode if the caller requested that. */
1533 if (uOpenFlags & VD_OPEN_FLAGS_READONLY)
1534 {
1535 vdiFreeImage(pImage, false);
1536 rc = vdiOpenImage(pImage, uOpenFlags);
1537 }
1538
1539 if (RT_SUCCESS(rc))
1540 *ppBackendData = pImage;
1541 }
1542
1543 if (RT_FAILURE(rc))
1544 RTMemFree(pImage);
1545 }
1546 else
1547 rc = VERR_NO_MEMORY;
1548
1549 LogFlowFunc(("returns %Rrc (pBackendData=%#p)\n", rc, *ppBackendData));
1550 return rc;
1551}
1552
1553/** @copydoc VDIMAGEBACKEND::pfnRename */
1554static DECLCALLBACK(int) vdiRename(void *pBackendData, const char *pszFilename)
1555{
1556 LogFlowFunc(("pBackendData=%#p pszFilename=%#p\n", pBackendData, pszFilename));
1557 int rc = VINF_SUCCESS;
1558 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1559
1560 /* Check arguments. */
1561 AssertReturn((pImage && pszFilename && *pszFilename), VERR_INVALID_PARAMETER);
1562
1563 /* Close the image. */
1564 rc = vdiFreeImage(pImage, false);
1565 if (RT_SUCCESS(rc))
1566 {
1567 /* Rename the file. */
1568 rc = vdIfIoIntFileMove(pImage->pIfIo, pImage->pszFilename, pszFilename, 0);
1569 if (RT_SUCCESS(rc))
1570 {
1571 /* Update pImage with the new information. */
1572 pImage->pszFilename = pszFilename;
1573
1574 /* Open the new image. */
1575 rc = vdiOpenImage(pImage, pImage->uOpenFlags);
1576 }
1577 else
1578 {
1579 /* The move failed, try to reopen the original image. */
1580 int rc2 = vdiOpenImage(pImage, pImage->uOpenFlags);
1581 if (RT_FAILURE(rc2))
1582 rc = rc2;
1583 }
1584 }
1585
1586 LogFlowFunc(("returns %Rrc\n", rc));
1587 return rc;
1588}
1589
1590/** @copydoc VDIMAGEBACKEND::pfnClose */
1591static DECLCALLBACK(int) vdiClose(void *pBackendData, bool fDelete)
1592{
1593 LogFlowFunc(("pBackendData=%#p fDelete=%d\n", pBackendData, fDelete));
1594 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1595
1596 int rc = vdiFreeImage(pImage, fDelete);
1597 RTMemFree(pImage);
1598
1599 LogFlowFunc(("returns %Rrc\n", rc));
1600 return rc;
1601}
1602
1603static DECLCALLBACK(int) vdiRead(void *pBackendData, uint64_t uOffset, size_t cbToRead,
1604 PVDIOCTX pIoCtx, size_t *pcbActuallyRead)
1605{
1606 LogFlowFunc(("pBackendData=%#p uOffset=%llu pIoCtx=%#p cbToRead=%zu pcbActuallyRead=%#p\n",
1607 pBackendData, uOffset, pIoCtx, cbToRead, pcbActuallyRead));
1608 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1609 unsigned uBlock;
1610 unsigned offRead;
1611 int rc = VINF_SUCCESS;
1612
1613 AssertPtr(pImage);
1614 Assert(!(uOffset % 512));
1615 Assert(!(cbToRead % 512));
1616 AssertReturn((VALID_PTR(pIoCtx) && cbToRead), VERR_INVALID_PARAMETER);
1617 AssertReturn(uOffset + cbToRead <= getImageDiskSize(&pImage->Header), VERR_INVALID_PARAMETER);
1618
1619 /* Calculate starting block number and offset inside it. */
1620 uBlock = (unsigned)(uOffset >> pImage->uShiftOffset2Index);
1621 offRead = (unsigned)uOffset & pImage->uBlockMask;
1622
1623 /* Clip read range to at most the rest of the block. */
1624 cbToRead = RT_MIN(cbToRead, getImageBlockSize(&pImage->Header) - offRead);
1625 Assert(!(cbToRead % 512));
1626
1627 if (pImage->paBlocks[uBlock] == VDI_IMAGE_BLOCK_FREE)
1628 rc = VERR_VD_BLOCK_FREE;
1629 else if (pImage->paBlocks[uBlock] == VDI_IMAGE_BLOCK_ZERO)
1630 {
1631 size_t cbSet;
1632
1633 cbSet = vdIfIoIntIoCtxSet(pImage->pIfIo, pIoCtx, 0, cbToRead);
1634 Assert(cbSet == cbToRead);
1635 }
1636 else
1637 {
1638 /* Block present in image file, read relevant data. */
1639 uint64_t u64Offset = (uint64_t)pImage->paBlocks[uBlock] * pImage->cbTotalBlockData
1640 + (pImage->offStartData + pImage->offStartBlockData + offRead);
1641
1642 if (u64Offset + cbToRead <= pImage->cbImage)
1643 rc = vdIfIoIntFileReadUser(pImage->pIfIo, pImage->pStorage, u64Offset,
1644 pIoCtx, cbToRead);
1645 else
1646 {
1647 LogRel(("VDI: Out of range access (%llu) in image %s, image size %llu\n",
1648 u64Offset, pImage->pszFilename, pImage->cbImage));
1649 vdIfIoIntIoCtxSet(pImage->pIfIo, pIoCtx, 0, cbToRead);
1650 rc = VERR_VD_READ_OUT_OF_RANGE;
1651 }
1652 }
1653
1654 if (pcbActuallyRead)
1655 *pcbActuallyRead = cbToRead;
1656
1657 LogFlowFunc(("returns %Rrc\n", rc));
1658 return rc;
1659}
1660
1661static DECLCALLBACK(int) vdiWrite(void *pBackendData, uint64_t uOffset, size_t cbToWrite,
1662 PVDIOCTX pIoCtx, size_t *pcbWriteProcess, size_t *pcbPreRead,
1663 size_t *pcbPostRead, unsigned fWrite)
1664{
1665 LogFlowFunc(("pBackendData=%#p uOffset=%llu pIoCtx=%#p cbToWrite=%zu pcbWriteProcess=%#p pcbPreRead=%#p pcbPostRead=%#p\n",
1666 pBackendData, uOffset, pIoCtx, cbToWrite, pcbWriteProcess, pcbPreRead, pcbPostRead));
1667 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1668 unsigned uBlock;
1669 unsigned offWrite;
1670 int rc = VINF_SUCCESS;
1671
1672 AssertPtr(pImage);
1673 Assert(!(uOffset % 512));
1674 Assert(!(cbToWrite % 512));
1675 AssertReturn((VALID_PTR(pIoCtx) && cbToWrite), VERR_INVALID_PARAMETER);
1676
1677 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
1678 {
1679 /* No size check here, will do that later. For dynamic images which are
1680 * not multiples of the block size in length, this would prevent writing to
1681 * the last block. */
1682
1683 /* Calculate starting block number and offset inside it. */
1684 uBlock = (unsigned)(uOffset >> pImage->uShiftOffset2Index);
1685 offWrite = (unsigned)uOffset & pImage->uBlockMask;
1686
1687 /* Clip write range to at most the rest of the block. */
1688 cbToWrite = RT_MIN(cbToWrite, getImageBlockSize(&pImage->Header) - offWrite);
1689 Assert(!(cbToWrite % 512));
1690
1691 do
1692 {
1693 if (!IS_VDI_IMAGE_BLOCK_ALLOCATED(pImage->paBlocks[uBlock]))
1694 {
1695 /* Block is either free or zero. */
1696 if ( !(pImage->uOpenFlags & VD_OPEN_FLAGS_HONOR_ZEROES)
1697 && ( pImage->paBlocks[uBlock] == VDI_IMAGE_BLOCK_ZERO
1698 || cbToWrite == getImageBlockSize(&pImage->Header)))
1699 {
1700 /* If the destination block is unallocated at this point, it's
1701 * either a zero block or a block which hasn't been used so far
1702 * (which also means that it's a zero block. Don't need to write
1703 * anything to this block if the data consists of just zeroes. */
1704 if (vdIfIoIntIoCtxIsZero(pImage->pIfIo, pIoCtx, cbToWrite, true))
1705 {
1706 pImage->paBlocks[uBlock] = VDI_IMAGE_BLOCK_ZERO;
1707 *pcbPreRead = 0;
1708 *pcbPostRead = 0;
1709 break;
1710 }
1711 }
1712
1713 if ( cbToWrite == getImageBlockSize(&pImage->Header)
1714 && !(fWrite & VD_WRITE_NO_ALLOC))
1715 {
1716 /* Full block write to previously unallocated block.
1717 * Allocate block and write data. */
1718 Assert(!offWrite);
1719 PVDIASYNCBLOCKALLOC pBlockAlloc = (PVDIASYNCBLOCKALLOC)RTMemAllocZ(sizeof(VDIASYNCBLOCKALLOC));
1720 if (!pBlockAlloc)
1721 {
1722 rc = VERR_NO_MEMORY;
1723 break;
1724 }
1725
1726 unsigned cBlocksAllocated = getImageBlocksAllocated(&pImage->Header);
1727 uint64_t u64Offset = (uint64_t)cBlocksAllocated * pImage->cbTotalBlockData
1728 + (pImage->offStartData + pImage->offStartBlockData);
1729
1730 pBlockAlloc->cBlocksAllocated = cBlocksAllocated;
1731 pBlockAlloc->uBlock = uBlock;
1732
1733 *pcbPreRead = 0;
1734 *pcbPostRead = 0;
1735
1736 rc = vdIfIoIntFileWriteUser(pImage->pIfIo, pImage->pStorage,
1737 u64Offset, pIoCtx, cbToWrite,
1738 vdiBlockAllocUpdate, pBlockAlloc);
1739 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
1740 break;
1741 else if (RT_FAILURE(rc))
1742 {
1743 RTMemFree(pBlockAlloc);
1744 break;
1745 }
1746
1747 rc = vdiBlockAllocUpdate(pImage, pIoCtx, pBlockAlloc, rc);
1748 }
1749 else
1750 {
1751 /* Trying to do a partial write to an unallocated block. Don't do
1752 * anything except letting the upper layer know what to do. */
1753 *pcbPreRead = offWrite % getImageBlockSize(&pImage->Header);
1754 *pcbPostRead = getImageBlockSize(&pImage->Header) - cbToWrite - *pcbPreRead;
1755 rc = VERR_VD_BLOCK_FREE;
1756 }
1757 }
1758 else
1759 {
1760 /* Block present in image file, write relevant data. */
1761 uint64_t u64Offset = (uint64_t)pImage->paBlocks[uBlock] * pImage->cbTotalBlockData
1762 + (pImage->offStartData + pImage->offStartBlockData + offWrite);
1763 rc = vdIfIoIntFileWriteUser(pImage->pIfIo, pImage->pStorage,
1764 u64Offset, pIoCtx, cbToWrite, NULL, NULL);
1765 }
1766 } while (0);
1767
1768 if (pcbWriteProcess)
1769 *pcbWriteProcess = cbToWrite;
1770 }
1771 else
1772 rc = VERR_VD_IMAGE_READ_ONLY;
1773
1774 LogFlowFunc(("returns %Rrc\n", rc));
1775 return rc;
1776}
1777
1778static DECLCALLBACK(int) vdiFlush(void *pBackendData, PVDIOCTX pIoCtx)
1779{
1780 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
1781 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1782 int rc = VINF_SUCCESS;
1783
1784 Assert(pImage);
1785
1786 rc = vdiFlushImageIoCtx(pImage, pIoCtx);
1787 LogFlowFunc(("returns %Rrc\n", rc));
1788 return rc;
1789}
1790
1791/** @copydoc VDIMAGEBACKEND::pfnGetVersion */
1792static DECLCALLBACK(unsigned) vdiGetVersion(void *pBackendData)
1793{
1794 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
1795 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1796
1797 AssertPtrReturn(pImage, 0);
1798
1799 LogFlowFunc(("returns %#x\n", pImage->PreHeader.u32Version));
1800 return pImage->PreHeader.u32Version;
1801}
1802
1803/** @copydoc VDIMAGEBACKEND::pfnGetFileSize */
1804static DECLCALLBACK(uint64_t) vdiGetFileSize(void *pBackendData)
1805{
1806 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
1807 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1808 uint64_t cb = 0;
1809
1810 AssertPtrReturn(pImage, 0);
1811
1812 if (pImage->pStorage)
1813 {
1814 uint64_t cbFile;
1815 int rc = vdIfIoIntFileGetSize(pImage->pIfIo, pImage->pStorage, &cbFile);
1816 if (RT_SUCCESS(rc))
1817 cb += cbFile;
1818 }
1819
1820 LogFlowFunc(("returns %lld\n", cb));
1821 return cb;
1822}
1823
1824/** @copydoc VDIMAGEBACKEND::pfnGetPCHSGeometry */
1825static DECLCALLBACK(int) vdiGetPCHSGeometry(void *pBackendData, PVDGEOMETRY pPCHSGeometry)
1826{
1827 LogFlowFunc(("pBackendData=%#p pPCHSGeometry=%#p\n", pBackendData, pPCHSGeometry));
1828 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1829 int rc = VINF_SUCCESS;
1830
1831 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
1832
1833 if (pImage->PCHSGeometry.cCylinders)
1834 *pPCHSGeometry = pImage->PCHSGeometry;
1835 else
1836 rc = VERR_VD_GEOMETRY_NOT_SET;
1837
1838 LogFlowFunc(("returns %Rrc (PCHS=%u/%u/%u)\n", rc, pPCHSGeometry->cCylinders, pPCHSGeometry->cHeads, pPCHSGeometry->cSectors));
1839 return rc;
1840}
1841
1842/** @copydoc VDIMAGEBACKEND::pfnSetPCHSGeometry */
1843static DECLCALLBACK(int) vdiSetPCHSGeometry(void *pBackendData, PCVDGEOMETRY pPCHSGeometry)
1844{
1845 LogFlowFunc(("pBackendData=%#p pPCHSGeometry=%#p PCHS=%u/%u/%u\n",
1846 pBackendData, pPCHSGeometry, pPCHSGeometry->cCylinders, pPCHSGeometry->cHeads, pPCHSGeometry->cSectors));
1847 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1848 int rc = VINF_SUCCESS;
1849
1850 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
1851
1852 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
1853 rc = VERR_VD_IMAGE_READ_ONLY;
1854 else
1855 pImage->PCHSGeometry = *pPCHSGeometry;
1856
1857 LogFlowFunc(("returns %Rrc\n", rc));
1858 return rc;
1859}
1860
1861/** @copydoc VDIMAGEBACKEND::pfnGetLCHSGeometry */
1862static DECLCALLBACK(int) vdiGetLCHSGeometry(void *pBackendData, PVDGEOMETRY pLCHSGeometry)
1863{
1864 LogFlowFunc(("pBackendData=%#p pLCHSGeometry=%#p\n", pBackendData, pLCHSGeometry));
1865 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1866
1867 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
1868
1869 int rc = VINF_SUCCESS;
1870 VDIDISKGEOMETRY DummyGeo = { 0, 0, 0, VDI_GEOMETRY_SECTOR_SIZE };
1871 PVDIDISKGEOMETRY pGeometry = getImageLCHSGeometry(&pImage->Header);
1872 if (!pGeometry)
1873 pGeometry = &DummyGeo;
1874
1875 if ( pGeometry->cCylinders > 0
1876 && pGeometry->cHeads > 0
1877 && pGeometry->cSectors > 0)
1878 {
1879 pLCHSGeometry->cCylinders = pGeometry->cCylinders;
1880 pLCHSGeometry->cHeads = pGeometry->cHeads;
1881 pLCHSGeometry->cSectors = pGeometry->cSectors;
1882 }
1883 else
1884 rc = VERR_VD_GEOMETRY_NOT_SET;
1885
1886 LogFlowFunc(("returns %Rrc (LCHS=%u/%u/%u)\n", rc, pLCHSGeometry->cCylinders, pLCHSGeometry->cHeads, pLCHSGeometry->cSectors));
1887 return rc;
1888}
1889
1890/** @copydoc VDIMAGEBACKEND::pfnSetLCHSGeometry */
1891static DECLCALLBACK(int) vdiSetLCHSGeometry(void *pBackendData, PCVDGEOMETRY pLCHSGeometry)
1892{
1893 LogFlowFunc(("pBackendData=%#p pLCHSGeometry=%#p LCHS=%u/%u/%u\n",
1894 pBackendData, pLCHSGeometry, pLCHSGeometry->cCylinders, pLCHSGeometry->cHeads, pLCHSGeometry->cSectors));
1895 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1896 PVDIDISKGEOMETRY pGeometry;
1897 int rc = VINF_SUCCESS;
1898
1899 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
1900
1901 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
1902 {
1903 pGeometry = getImageLCHSGeometry(&pImage->Header);
1904 if (pGeometry)
1905 {
1906 pGeometry->cCylinders = pLCHSGeometry->cCylinders;
1907 pGeometry->cHeads = pLCHSGeometry->cHeads;
1908 pGeometry->cSectors = pLCHSGeometry->cSectors;
1909 pGeometry->cbSector = VDI_GEOMETRY_SECTOR_SIZE;
1910
1911 /* Update header information in base image file. */
1912 vdiFlushImage(pImage);
1913 }
1914 }
1915 else
1916 rc = VERR_VD_IMAGE_READ_ONLY;
1917
1918 LogFlowFunc(("returns %Rrc\n", rc));
1919 return rc;
1920}
1921
1922/** @copydoc VDIMAGEBACKEND::pfnQueryRegions */
1923static DECLCALLBACK(int) vdiQueryRegions(void *pBackendData, PCVDREGIONLIST *ppRegionList)
1924{
1925 LogFlowFunc(("pBackendData=%#p ppRegionList=%#p\n", pBackendData, ppRegionList));
1926 PVDIIMAGEDESC pThis = (PVDIIMAGEDESC)pBackendData;
1927
1928 AssertPtrReturn(pThis, VERR_VD_NOT_OPENED);
1929
1930 *ppRegionList = &pThis->RegionList;
1931 LogFlowFunc(("returns %Rrc\n", VINF_SUCCESS));
1932 return VINF_SUCCESS;
1933}
1934
1935/** @copydoc VDIMAGEBACKEND::pfnRegionListRelease */
1936static DECLCALLBACK(void) vdiRegionListRelease(void *pBackendData, PCVDREGIONLIST pRegionList)
1937{
1938 RT_NOREF1(pRegionList);
1939 LogFlowFunc(("pBackendData=%#p pRegionList=%#p\n", pBackendData, pRegionList));
1940 PVDIIMAGEDESC pThis = (PVDIIMAGEDESC)pBackendData;
1941 AssertPtr(pThis); RT_NOREF(pThis);
1942
1943 /* Nothing to do here. */
1944}
1945
1946/** @copydoc VDIMAGEBACKEND::pfnGetImageFlags */
1947static DECLCALLBACK(unsigned) vdiGetImageFlags(void *pBackendData)
1948{
1949 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
1950 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1951
1952 AssertPtrReturn(pImage, 0);
1953
1954 LogFlowFunc(("returns %#x\n", pImage->uImageFlags));
1955 return pImage->uImageFlags;
1956}
1957
1958/** @copydoc VDIMAGEBACKEND::pfnGetOpenFlags */
1959static DECLCALLBACK(unsigned) vdiGetOpenFlags(void *pBackendData)
1960{
1961 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
1962 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1963
1964 AssertPtrReturn(pImage, 0);
1965
1966 LogFlowFunc(("returns %#x\n", pImage->uOpenFlags));
1967 return pImage->uOpenFlags;
1968}
1969
1970/** @copydoc VDIMAGEBACKEND::pfnSetOpenFlags */
1971static DECLCALLBACK(int) vdiSetOpenFlags(void *pBackendData, unsigned uOpenFlags)
1972{
1973 LogFlowFunc(("pBackendData=%#p uOpenFlags=%#x\n", pBackendData, uOpenFlags));
1974 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1975 int rc;
1976 const char *pszFilename;
1977
1978 /* Image must be opened and the new flags must be valid. */
1979 if (!pImage || (uOpenFlags & ~( VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_INFO
1980 | VD_OPEN_FLAGS_ASYNC_IO | VD_OPEN_FLAGS_SHAREABLE
1981 | VD_OPEN_FLAGS_SEQUENTIAL | VD_OPEN_FLAGS_DISCARD
1982 | VD_OPEN_FLAGS_SKIP_CONSISTENCY_CHECKS)))
1983 rc = VERR_INVALID_PARAMETER;
1984 else
1985 {
1986 /* Implement this operation via reopening the image. */
1987 pszFilename = pImage->pszFilename;
1988 rc = vdiFreeImage(pImage, false);
1989 if (RT_SUCCESS(rc))
1990 rc = vdiOpenImage(pImage, uOpenFlags);
1991 }
1992
1993 LogFlowFunc(("returns %Rrc\n", rc));
1994 return rc;
1995}
1996
1997/** @copydoc VDIMAGEBACKEND::pfnGetComment */
1998static DECLCALLBACK(int) vdiGetComment(void *pBackendData, char *pszComment,
1999 size_t cbComment)
2000{
2001 LogFlowFunc(("pBackendData=%#p pszComment=%#p cbComment=%zu\n", pBackendData, pszComment, cbComment));
2002 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
2003
2004 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
2005
2006 int rc = VINF_SUCCESS;
2007 char *pszTmp = getImageComment(&pImage->Header);
2008 /* Make this foolproof even if the image doesn't have the zero
2009 * termination. With some luck the repaired header will be saved. */
2010 size_t cb = RTStrNLen(pszTmp, VDI_IMAGE_COMMENT_SIZE);
2011 if (cb == VDI_IMAGE_COMMENT_SIZE)
2012 {
2013 pszTmp[VDI_IMAGE_COMMENT_SIZE-1] = '\0';
2014 cb--;
2015 }
2016 if (cb < cbComment)
2017 {
2018 /* memcpy is much better than strncpy. */
2019 memcpy(pszComment, pszTmp, cb + 1);
2020 }
2021 else
2022 rc = VERR_BUFFER_OVERFLOW;
2023
2024 LogFlowFunc(("returns %Rrc comment=\"%s\"\n", rc, pszComment));
2025 return rc;
2026}
2027
2028/** @copydoc VDIMAGEBACKEND::pfnSetComment */
2029static DECLCALLBACK(int) vdiSetComment(void *pBackendData, const char *pszComment)
2030{
2031 LogFlowFunc(("pBackendData=%#p pszComment=\"%s\"\n", pBackendData, pszComment));
2032 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
2033 int rc;
2034
2035 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
2036
2037 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
2038 {
2039 size_t cchComment = pszComment ? strlen(pszComment) : 0;
2040 if (cchComment < VDI_IMAGE_COMMENT_SIZE)
2041 {
2042 /* we don't support old style images */
2043 if (GET_MAJOR_HEADER_VERSION(&pImage->Header) == 1)
2044 {
2045 /*
2046 * Update the comment field, making sure to zero out all of the previous comment.
2047 */
2048 memset(pImage->Header.u.v1.szComment, '\0', VDI_IMAGE_COMMENT_SIZE);
2049 memcpy(pImage->Header.u.v1.szComment, pszComment, cchComment);
2050
2051 /* write out new the header */
2052 rc = vdiUpdateHeader(pImage);
2053 }
2054 else
2055 rc = VERR_VD_VDI_UNSUPPORTED_VERSION;
2056 }
2057 else
2058 {
2059 LogFunc(("pszComment is too long, %d bytes!\n", cchComment));
2060 rc = VERR_VD_VDI_COMMENT_TOO_LONG;
2061 }
2062 }
2063 else
2064 rc = VERR_VD_IMAGE_READ_ONLY;
2065
2066 LogFlowFunc(("returns %Rrc\n", rc));
2067 return rc;
2068}
2069
2070/** @copydoc VDIMAGEBACKEND::pfnGetUuid */
2071static DECLCALLBACK(int) vdiGetUuid(void *pBackendData, PRTUUID pUuid)
2072{
2073 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
2074 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
2075
2076 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
2077
2078 *pUuid = *getImageCreationUUID(&pImage->Header);
2079
2080 LogFlowFunc(("returns %Rrc (%RTuuid)\n", VINF_SUCCESS, pUuid));
2081 return VINF_SUCCESS;
2082}
2083
2084/** @copydoc VDIMAGEBACKEND::pfnSetUuid */
2085static DECLCALLBACK(int) vdiSetUuid(void *pBackendData, PCRTUUID pUuid)
2086{
2087 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
2088 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
2089
2090 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
2091
2092 int rc = VINF_SUCCESS;
2093 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
2094 {
2095 if (GET_MAJOR_HEADER_VERSION(&pImage->Header) == 1)
2096 pImage->Header.u.v1.uuidCreate = *pUuid;
2097 /* Make it possible to clone old VDIs. */
2098 else if (GET_MAJOR_HEADER_VERSION(&pImage->Header) == 0)
2099 pImage->Header.u.v0.uuidCreate = *pUuid;
2100 else
2101 {
2102 LogFunc(("Version is not supported!\n"));
2103 rc = VERR_VD_VDI_UNSUPPORTED_VERSION;
2104 }
2105 }
2106 else
2107 rc = VERR_VD_IMAGE_READ_ONLY;
2108
2109 LogFlowFunc(("returns %Rrc\n", rc));
2110 return rc;
2111}
2112
2113/** @copydoc VDIMAGEBACKEND::pfnGetModificationUuid */
2114static DECLCALLBACK(int) vdiGetModificationUuid(void *pBackendData, PRTUUID pUuid)
2115{
2116 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
2117 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
2118
2119 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
2120
2121 *pUuid = *getImageModificationUUID(&pImage->Header);
2122
2123 LogFlowFunc(("returns %Rrc (%RTuuid)\n", VINF_SUCCESS, pUuid));
2124 return VINF_SUCCESS;
2125}
2126
2127/** @copydoc VDIMAGEBACKEND::pfnSetModificationUuid */
2128static DECLCALLBACK(int) vdiSetModificationUuid(void *pBackendData, PCRTUUID pUuid)
2129{
2130 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
2131 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
2132
2133 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
2134
2135 int rc = VINF_SUCCESS;
2136 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
2137 {
2138 if (GET_MAJOR_HEADER_VERSION(&pImage->Header) == 1)
2139 pImage->Header.u.v1.uuidModify = *pUuid;
2140 /* Make it possible to clone old VDIs. */
2141 else if (GET_MAJOR_HEADER_VERSION(&pImage->Header) == 0)
2142 pImage->Header.u.v0.uuidModify = *pUuid;
2143 else
2144 {
2145 LogFunc(("Version is not supported!\n"));
2146 rc = VERR_VD_VDI_UNSUPPORTED_VERSION;
2147 }
2148 }
2149 else
2150 rc = VERR_VD_IMAGE_READ_ONLY;
2151
2152 LogFlowFunc(("returns %Rrc\n", rc));
2153 return rc;
2154}
2155
2156/** @copydoc VDIMAGEBACKEND::pfnGetParentUuid */
2157static DECLCALLBACK(int) vdiGetParentUuid(void *pBackendData, PRTUUID pUuid)
2158{
2159 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
2160 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
2161
2162 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
2163
2164 *pUuid = *getImageParentUUID(&pImage->Header);
2165
2166 LogFlowFunc(("returns %Rrc (%RTuuid)\n", VINF_SUCCESS, pUuid));
2167 return VINF_SUCCESS;
2168}
2169
2170/** @copydoc VDIMAGEBACKEND::pfnSetParentUuid */
2171static DECLCALLBACK(int) vdiSetParentUuid(void *pBackendData, PCRTUUID pUuid)
2172{
2173 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
2174 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
2175
2176 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
2177
2178 int rc = VINF_SUCCESS;
2179 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
2180 {
2181 if (GET_MAJOR_HEADER_VERSION(&pImage->Header) == 1)
2182 pImage->Header.u.v1.uuidLinkage = *pUuid;
2183 /* Make it possible to clone old VDIs. */
2184 else if (GET_MAJOR_HEADER_VERSION(&pImage->Header) == 0)
2185 pImage->Header.u.v0.uuidLinkage = *pUuid;
2186 else
2187 {
2188 LogFunc(("Version is not supported!\n"));
2189 rc = VERR_VD_VDI_UNSUPPORTED_VERSION;
2190 }
2191 }
2192 else
2193 rc = VERR_VD_IMAGE_READ_ONLY;
2194
2195 LogFlowFunc(("returns %Rrc\n", rc));
2196 return rc;
2197}
2198
2199/** @copydoc VDIMAGEBACKEND::pfnGetParentModificationUuid */
2200static DECLCALLBACK(int) vdiGetParentModificationUuid(void *pBackendData, PRTUUID pUuid)
2201{
2202 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
2203 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
2204
2205 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
2206
2207 *pUuid = *getImageParentModificationUUID(&pImage->Header);
2208
2209 LogFlowFunc(("returns %Rrc (%RTuuid)\n", VINF_SUCCESS, pUuid));
2210 return VINF_SUCCESS;
2211}
2212
2213/** @copydoc VDIMAGEBACKEND::pfnSetParentModificationUuid */
2214static DECLCALLBACK(int) vdiSetParentModificationUuid(void *pBackendData, PCRTUUID pUuid)
2215{
2216 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
2217 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
2218
2219 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
2220
2221 int rc = VINF_SUCCESS;
2222 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
2223 {
2224 if (GET_MAJOR_HEADER_VERSION(&pImage->Header) == 1)
2225 pImage->Header.u.v1.uuidParentModify = *pUuid;
2226 else
2227 {
2228 LogFunc(("Version is not supported!\n"));
2229 rc = VERR_VD_VDI_UNSUPPORTED_VERSION;
2230 }
2231 }
2232 else
2233 rc = VERR_VD_IMAGE_READ_ONLY;
2234
2235 LogFlowFunc(("returns %Rrc\n", rc));
2236 return rc;
2237}
2238
2239/** @copydoc VDIMAGEBACKEND::pfnDump */
2240static DECLCALLBACK(void) vdiDump(void *pBackendData)
2241{
2242 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
2243
2244 AssertPtrReturnVoid(pImage);
2245 vdIfErrorMessage(pImage->pIfError, "Dumping VDI image \"%s\" mode=%s uOpenFlags=%X File=%#p\n",
2246 pImage->pszFilename,
2247 (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY) ? "r/o" : "r/w",
2248 pImage->uOpenFlags,
2249 pImage->pStorage);
2250 vdIfErrorMessage(pImage->pIfError, "Header: Version=%08X Type=%X Flags=%X Size=%llu\n",
2251 pImage->PreHeader.u32Version,
2252 getImageType(&pImage->Header),
2253 getImageFlags(&pImage->Header),
2254 getImageDiskSize(&pImage->Header));
2255 vdIfErrorMessage(pImage->pIfError, "Header: cbBlock=%u cbBlockExtra=%u cBlocks=%u cBlocksAllocated=%u\n",
2256 getImageBlockSize(&pImage->Header),
2257 getImageExtraBlockSize(&pImage->Header),
2258 getImageBlocks(&pImage->Header),
2259 getImageBlocksAllocated(&pImage->Header));
2260 vdIfErrorMessage(pImage->pIfError, "Header: offBlocks=%u offData=%u\n",
2261 getImageBlocksOffset(&pImage->Header),
2262 getImageDataOffset(&pImage->Header));
2263 PVDIDISKGEOMETRY pg = getImageLCHSGeometry(&pImage->Header);
2264 if (pg)
2265 vdIfErrorMessage(pImage->pIfError, "Header: Geometry: C/H/S=%u/%u/%u cbSector=%u\n",
2266 pg->cCylinders, pg->cHeads, pg->cSectors, pg->cbSector);
2267 vdIfErrorMessage(pImage->pIfError, "Header: uuidCreation={%RTuuid}\n", getImageCreationUUID(&pImage->Header));
2268 vdIfErrorMessage(pImage->pIfError, "Header: uuidModification={%RTuuid}\n", getImageModificationUUID(&pImage->Header));
2269 vdIfErrorMessage(pImage->pIfError, "Header: uuidParent={%RTuuid}\n", getImageParentUUID(&pImage->Header));
2270 if (GET_MAJOR_HEADER_VERSION(&pImage->Header) >= 1)
2271 vdIfErrorMessage(pImage->pIfError, "Header: uuidParentModification={%RTuuid}\n", getImageParentModificationUUID(&pImage->Header));
2272 vdIfErrorMessage(pImage->pIfError, "Image: fFlags=%08X offStartBlocks=%u offStartData=%u\n",
2273 pImage->uImageFlags, pImage->offStartBlocks, pImage->offStartData);
2274 vdIfErrorMessage(pImage->pIfError, "Image: uBlockMask=%08X cbTotalBlockData=%u uShiftOffset2Index=%u offStartBlockData=%u\n",
2275 pImage->uBlockMask,
2276 pImage->cbTotalBlockData,
2277 pImage->uShiftOffset2Index,
2278 pImage->offStartBlockData);
2279
2280 unsigned uBlock, cBlocksNotFree, cBadBlocks, cBlocks = getImageBlocks(&pImage->Header);
2281 for (uBlock=0, cBlocksNotFree=0, cBadBlocks=0; uBlock<cBlocks; uBlock++)
2282 {
2283 if (IS_VDI_IMAGE_BLOCK_ALLOCATED(pImage->paBlocks[uBlock]))
2284 {
2285 cBlocksNotFree++;
2286 if (pImage->paBlocks[uBlock] >= cBlocks)
2287 cBadBlocks++;
2288 }
2289 }
2290 if (cBlocksNotFree != getImageBlocksAllocated(&pImage->Header))
2291 {
2292 vdIfErrorMessage(pImage->pIfError, "!! WARNING: %u blocks actually allocated (cBlocksAllocated=%u) !!\n",
2293 cBlocksNotFree, getImageBlocksAllocated(&pImage->Header));
2294 }
2295 if (cBadBlocks)
2296 {
2297 vdIfErrorMessage(pImage->pIfError, "!! WARNING: %u bad blocks found !!\n",
2298 cBadBlocks);
2299 }
2300}
2301
2302/** @copydoc VDIMAGEBACKEND::pfnCompact */
2303static DECLCALLBACK(int) vdiCompact(void *pBackendData, unsigned uPercentStart,
2304 unsigned uPercentSpan, PVDINTERFACE pVDIfsDisk,
2305 PVDINTERFACE pVDIfsImage, PVDINTERFACE pVDIfsOperation)
2306{
2307 RT_NOREF2(pVDIfsDisk, pVDIfsImage);
2308 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
2309 int rc = VINF_SUCCESS;
2310 void *pvBuf = NULL, *pvTmp = NULL;
2311 unsigned *paBlocks2 = NULL;
2312
2313 PFNVDPARENTREAD pfnParentRead = NULL;
2314 void *pvParent = NULL;
2315 PVDINTERFACEPARENTSTATE pIfParentState = VDIfParentStateGet(pVDIfsOperation);
2316 if (pIfParentState)
2317 {
2318 pfnParentRead = pIfParentState->pfnParentRead;
2319 pvParent = pIfParentState->Core.pvUser;
2320 }
2321
2322 PVDINTERFACEPROGRESS pIfProgress = VDIfProgressGet(pVDIfsOperation);
2323 PVDINTERFACEQUERYRANGEUSE pIfQueryRangeUse = VDIfQueryRangeUseGet(pVDIfsOperation);
2324
2325 do
2326 {
2327 AssertBreakStmt(pImage, rc = VERR_INVALID_PARAMETER);
2328
2329 AssertBreakStmt(!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY),
2330 rc = VERR_VD_IMAGE_READ_ONLY);
2331
2332 unsigned cBlocks;
2333 unsigned cBlocksToMove = 0;
2334 size_t cbBlock;
2335 cBlocks = getImageBlocks(&pImage->Header);
2336 cbBlock = getImageBlockSize(&pImage->Header);
2337 if (pfnParentRead)
2338 {
2339 pvBuf = RTMemTmpAlloc(cbBlock);
2340 AssertBreakStmt(pvBuf, rc = VERR_NO_MEMORY);
2341 }
2342 pvTmp = RTMemTmpAlloc(cbBlock);
2343 AssertBreakStmt(pvTmp, rc = VERR_NO_MEMORY);
2344
2345 uint64_t cbFile;
2346 rc = vdIfIoIntFileGetSize(pImage->pIfIo, pImage->pStorage, &cbFile);
2347 AssertRCBreak(rc);
2348 unsigned cBlocksAllocated = (unsigned)((cbFile - pImage->offStartData - pImage->offStartBlockData) >> pImage->uShiftOffset2Index);
2349 if (cBlocksAllocated == 0)
2350 {
2351 /* No data blocks in this image, no need to compact. */
2352 rc = VINF_SUCCESS;
2353 break;
2354 }
2355
2356 /* Allocate block array for back resolving. */
2357 paBlocks2 = (unsigned *)RTMemAlloc(sizeof(unsigned *) * cBlocksAllocated);
2358 AssertBreakStmt(paBlocks2, rc = VERR_NO_MEMORY);
2359 /* Fill out back resolving, check/fix allocation errors before
2360 * compacting the image, just to be on the safe side. Update the
2361 * image contents straight away, as this enables cancelling. */
2362 for (unsigned i = 0; i < cBlocksAllocated; i++)
2363 paBlocks2[i] = VDI_IMAGE_BLOCK_FREE;
2364 rc = VINF_SUCCESS;
2365 for (unsigned i = 0; i < cBlocks; i++)
2366 {
2367 VDIIMAGEBLOCKPOINTER ptrBlock = pImage->paBlocks[i];
2368 if (IS_VDI_IMAGE_BLOCK_ALLOCATED(ptrBlock))
2369 {
2370 if (ptrBlock < cBlocksAllocated)
2371 {
2372 if (paBlocks2[ptrBlock] == VDI_IMAGE_BLOCK_FREE)
2373 paBlocks2[ptrBlock] = i;
2374 else
2375 {
2376 LogFunc(("Freed cross-linked block %u in file \"%s\"\n",
2377 i, pImage->pszFilename));
2378 pImage->paBlocks[i] = VDI_IMAGE_BLOCK_FREE;
2379 rc = vdiUpdateBlockInfo(pImage, i);
2380 if (RT_FAILURE(rc))
2381 break;
2382 }
2383 }
2384 else
2385 {
2386 LogFunc(("Freed out of bounds reference for block %u in file \"%s\"\n",
2387 i, pImage->pszFilename));
2388 pImage->paBlocks[i] = VDI_IMAGE_BLOCK_FREE;
2389 rc = vdiUpdateBlockInfo(pImage, i);
2390 if (RT_FAILURE(rc))
2391 break;
2392 }
2393 }
2394 }
2395 if (RT_FAILURE(rc))
2396 break;
2397
2398 /* Find redundant information and update the block pointers
2399 * accordingly, creating bubbles. Keep disk up to date, as this
2400 * enables cancelling. */
2401 for (unsigned i = 0; i < cBlocks; i++)
2402 {
2403 VDIIMAGEBLOCKPOINTER ptrBlock = pImage->paBlocks[i];
2404 if (IS_VDI_IMAGE_BLOCK_ALLOCATED(ptrBlock))
2405 {
2406 /* Block present in image file, read relevant data. */
2407 uint64_t u64Offset = (uint64_t)ptrBlock * pImage->cbTotalBlockData
2408 + (pImage->offStartData + pImage->offStartBlockData);
2409 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pImage->pStorage, u64Offset, pvTmp, cbBlock);
2410 if (RT_FAILURE(rc))
2411 break;
2412
2413 if (ASMBitFirstSet((volatile void *)pvTmp, (uint32_t)cbBlock * 8) == -1)
2414 {
2415 pImage->paBlocks[i] = VDI_IMAGE_BLOCK_ZERO;
2416 rc = vdiUpdateBlockInfo(pImage, i);
2417 if (RT_FAILURE(rc))
2418 break;
2419 paBlocks2[ptrBlock] = VDI_IMAGE_BLOCK_FREE;
2420 /* Adjust progress info, one block to be relocated. */
2421 cBlocksToMove++;
2422 }
2423 else if (pfnParentRead)
2424 {
2425 rc = pfnParentRead(pvParent, (uint64_t)i * cbBlock, pvBuf, cbBlock);
2426 if (RT_FAILURE(rc))
2427 break;
2428 if (!memcmp(pvTmp, pvBuf, cbBlock))
2429 {
2430 pImage->paBlocks[i] = VDI_IMAGE_BLOCK_FREE;
2431 rc = vdiUpdateBlockInfo(pImage, i);
2432 if (RT_FAILURE(rc))
2433 break;
2434 paBlocks2[ptrBlock] = VDI_IMAGE_BLOCK_FREE;
2435 /* Adjust progress info, one block to be relocated. */
2436 cBlocksToMove++;
2437 }
2438 }
2439 }
2440
2441 /* Check if the range is in use if the block is still allocated. */
2442 ptrBlock = pImage->paBlocks[i];
2443 if ( IS_VDI_IMAGE_BLOCK_ALLOCATED(ptrBlock)
2444 && pIfQueryRangeUse)
2445 {
2446 bool fUsed = true;
2447
2448 rc = vdIfQueryRangeUse(pIfQueryRangeUse, (uint64_t)i * cbBlock, cbBlock, &fUsed);
2449 if (RT_FAILURE(rc))
2450 break;
2451 if (!fUsed)
2452 {
2453 pImage->paBlocks[i] = VDI_IMAGE_BLOCK_ZERO;
2454 rc = vdiUpdateBlockInfo(pImage, i);
2455 if (RT_FAILURE(rc))
2456 break;
2457 paBlocks2[ptrBlock] = VDI_IMAGE_BLOCK_FREE;
2458 /* Adjust progress info, one block to be relocated. */
2459 cBlocksToMove++;
2460 }
2461 }
2462
2463 vdIfProgress(pIfProgress, (uint64_t)i * uPercentSpan / (cBlocks + cBlocksToMove) + uPercentStart);
2464 if (RT_FAILURE(rc))
2465 break;
2466 }
2467 if (RT_FAILURE(rc))
2468 break;
2469
2470 /* Fill bubbles with other data (if available). */
2471 unsigned cBlocksMoved = 0;
2472 unsigned uBlockUsedPos = cBlocksAllocated;
2473 for (unsigned i = 0; i < cBlocksAllocated; i++)
2474 {
2475 unsigned uBlock = paBlocks2[i];
2476 if (uBlock == VDI_IMAGE_BLOCK_FREE)
2477 {
2478 unsigned uBlockData = VDI_IMAGE_BLOCK_FREE;
2479 while (uBlockUsedPos > i && uBlockData == VDI_IMAGE_BLOCK_FREE)
2480 {
2481 uBlockUsedPos--;
2482 uBlockData = paBlocks2[uBlockUsedPos];
2483 }
2484 /* Terminate early if there is no block which needs copying. */
2485 if (uBlockUsedPos == i)
2486 break;
2487 uint64_t u64Offset = (uint64_t)uBlockUsedPos * pImage->cbTotalBlockData
2488 + (pImage->offStartData + pImage->offStartBlockData);
2489 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pImage->pStorage, u64Offset,
2490 pvTmp, cbBlock);
2491 u64Offset = (uint64_t)i * pImage->cbTotalBlockData
2492 + (pImage->offStartData + pImage->offStartBlockData);
2493 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pImage->pStorage, u64Offset,
2494 pvTmp, cbBlock);
2495 pImage->paBlocks[uBlockData] = i;
2496 setImageBlocksAllocated(&pImage->Header, cBlocksAllocated - cBlocksMoved);
2497 rc = vdiUpdateBlockInfo(pImage, uBlockData);
2498 if (RT_FAILURE(rc))
2499 break;
2500 paBlocks2[i] = uBlockData;
2501 paBlocks2[uBlockUsedPos] = VDI_IMAGE_BLOCK_FREE;
2502 cBlocksMoved++;
2503 }
2504
2505 rc = vdIfProgress(pIfProgress, (uint64_t)(cBlocks + cBlocksMoved) * uPercentSpan / (cBlocks + cBlocksToMove) + uPercentStart);
2506 if (RT_FAILURE(rc))
2507 break;
2508 }
2509 if (RT_FAILURE(rc))
2510 break;
2511
2512 /* Update image header. */
2513 setImageBlocksAllocated(&pImage->Header, uBlockUsedPos);
2514 vdiUpdateHeader(pImage);
2515
2516 /* Truncate the image to the proper size to finish compacting. */
2517 rc = vdIfIoIntFileSetSize(pImage->pIfIo, pImage->pStorage,
2518 (uint64_t)uBlockUsedPos * pImage->cbTotalBlockData
2519 + pImage->offStartData + pImage->offStartBlockData);
2520 } while (0);
2521
2522 if (paBlocks2)
2523 RTMemTmpFree(paBlocks2);
2524 if (pvTmp)
2525 RTMemTmpFree(pvTmp);
2526 if (pvBuf)
2527 RTMemTmpFree(pvBuf);
2528
2529 if (RT_SUCCESS(rc))
2530 vdIfProgress(pIfProgress, uPercentStart + uPercentSpan);
2531
2532 LogFlowFunc(("returns %Rrc\n", rc));
2533 return rc;
2534}
2535
2536
2537/** @copydoc VDIMAGEBACKEND::pfnResize */
2538static DECLCALLBACK(int) vdiResize(void *pBackendData, uint64_t cbSize,
2539 PCVDGEOMETRY pPCHSGeometry, PCVDGEOMETRY pLCHSGeometry,
2540 unsigned uPercentStart, unsigned uPercentSpan,
2541 PVDINTERFACE pVDIfsDisk, PVDINTERFACE pVDIfsImage,
2542 PVDINTERFACE pVDIfsOperation)
2543{
2544 RT_NOREF5(uPercentStart, uPercentSpan, pVDIfsDisk, pVDIfsImage, pVDIfsOperation);
2545 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
2546 int rc = VINF_SUCCESS;
2547
2548 /* Check size. Maximum 4PB-3M. No tricks with adjusting the 1M block size
2549 * so far, which would extend the size. */
2550 if ( !cbSize
2551 || cbSize >= _1P * 4 - _1M * 3
2552 || cbSize < VDI_IMAGE_DEFAULT_BLOCK_SIZE)
2553 return VERR_VD_INVALID_SIZE;
2554
2555 /*
2556 * Making the image smaller is not supported at the moment.
2557 * Resizing is also not supported for fixed size images and
2558 * very old images.
2559 */
2560 /** @todo implement making the image smaller, it is the responsibility of
2561 * the user to know what he's doing. */
2562 if (cbSize < getImageDiskSize(&pImage->Header))
2563 rc = VERR_VD_SHRINK_NOT_SUPPORTED;
2564 else if ( GET_MAJOR_HEADER_VERSION(&pImage->Header) == 0
2565 || pImage->uImageFlags & VD_IMAGE_FLAGS_FIXED)
2566 rc = VERR_NOT_SUPPORTED;
2567 else if (cbSize > getImageDiskSize(&pImage->Header))
2568 {
2569 unsigned cBlocksAllocated = getImageBlocksAllocated(&pImage->Header); /** < Blocks currently allocated, doesn't change during resize */
2570 unsigned const cbBlock = RT_MAX(getImageBlockSize(&pImage->Header), 1);
2571 uint32_t cBlocksNew = cbSize / cbBlock; /** < New number of blocks in the image after the resize */
2572 if (cbSize % cbBlock)
2573 cBlocksNew++;
2574
2575 uint32_t cBlocksOld = getImageBlocks(&pImage->Header); /** < Number of blocks before the resize. */
2576 uint64_t cbBlockspaceNew = cBlocksNew * sizeof(VDIIMAGEBLOCKPOINTER); /** < Required space for the block array after the resize. */
2577 uint64_t offStartDataNew = RT_ALIGN_32(pImage->offStartBlocks + cbBlockspaceNew, VDI_DATA_ALIGN); /** < New start offset for block data after the resize */
2578
2579 if (pImage->offStartData < offStartDataNew)
2580 {
2581 if (cBlocksAllocated > 0)
2582 {
2583 /* Calculate how many sectors need to be relocated. */
2584 uint64_t cbOverlapping = offStartDataNew - pImage->offStartData;
2585 unsigned cBlocksReloc = cbOverlapping / cbBlock;
2586 if (cbOverlapping % cbBlock)
2587 cBlocksReloc++;
2588
2589 /* Since only full blocks can be relocated the new data start is
2590 * determined by moving it block by block. */
2591 cBlocksReloc = RT_MIN(cBlocksReloc, cBlocksAllocated);
2592 offStartDataNew = pImage->offStartData;
2593
2594 /* Do the relocation. */
2595 LogFlow(("Relocating %u blocks\n", cBlocksReloc));
2596
2597 /*
2598 * Get the blocks we need to relocate first, they are appended to the end
2599 * of the image.
2600 */
2601 void *pvBuf = NULL, *pvZero = NULL;
2602 do
2603 {
2604 /* Allocate data buffer. */
2605 pvBuf = RTMemAllocZ(pImage->cbTotalBlockData);
2606 if (!pvBuf)
2607 {
2608 rc = VERR_NO_MEMORY;
2609 break;
2610 }
2611
2612 /* Allocate buffer for overwriting with zeroes. */
2613 pvZero = RTMemAllocZ(pImage->cbTotalBlockData);
2614 if (!pvZero)
2615 {
2616 rc = VERR_NO_MEMORY;
2617 break;
2618 }
2619
2620 for (unsigned i = 0; i < cBlocksReloc; i++)
2621 {
2622 /* Search the index in the block table. */
2623 for (unsigned idxBlock = 0; idxBlock < cBlocksOld; idxBlock++)
2624 {
2625 if (!pImage->paBlocks[idxBlock])
2626 {
2627 /* Read data and append to the end of the image. */
2628 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pImage->pStorage,
2629 offStartDataNew, pvBuf,
2630 pImage->cbTotalBlockData);
2631 if (RT_FAILURE(rc))
2632 break;
2633
2634 uint64_t offBlockAppend;
2635 rc = vdIfIoIntFileGetSize(pImage->pIfIo, pImage->pStorage, &offBlockAppend);
2636 if (RT_FAILURE(rc))
2637 break;
2638
2639 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pImage->pStorage,
2640 offBlockAppend, pvBuf,
2641 pImage->cbTotalBlockData);
2642 if (RT_FAILURE(rc))
2643 break;
2644
2645 /* Zero out the old block area. */
2646 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pImage->pStorage,
2647 offStartDataNew, pvZero,
2648 pImage->cbTotalBlockData);
2649 if (RT_FAILURE(rc))
2650 break;
2651
2652 /* Update block counter. */
2653 pImage->paBlocks[idxBlock] = cBlocksAllocated - 1;
2654
2655 /*
2656 * Decrease the block number of all other entries in the array.
2657 * They were moved one block to the front.
2658 * Doing it as a separate step iterating over the array again
2659 * because an error while relocating the block might end up
2660 * in a corrupted image otherwise.
2661 */
2662 for (unsigned idxBlock2 = 0; idxBlock2 < cBlocksOld; idxBlock2++)
2663 {
2664 if ( idxBlock2 != idxBlock
2665 && IS_VDI_IMAGE_BLOCK_ALLOCATED(pImage->paBlocks[idxBlock2]))
2666 pImage->paBlocks[idxBlock2]--;
2667 }
2668
2669 /* Continue with the next block. */
2670 break;
2671 }
2672 }
2673
2674 if (RT_FAILURE(rc))
2675 break;
2676
2677 offStartDataNew += pImage->cbTotalBlockData;
2678 }
2679 } while (0);
2680
2681 if (pvBuf)
2682 RTMemFree(pvBuf);
2683 if (pvZero)
2684 RTMemFree(pvZero);
2685 }
2686
2687 /*
2688 * We need to update the new offsets for the image data in the out of memory
2689 * case too because we relocated the blocks already.
2690 */
2691 pImage->offStartData = offStartDataNew;
2692 setImageDataOffset(&pImage->Header, offStartDataNew);
2693 }
2694
2695 /*
2696 * Relocation done, expand the block array and update the header with
2697 * the new data.
2698 */
2699 if (RT_SUCCESS(rc))
2700 {
2701 PVDIIMAGEBLOCKPOINTER paBlocksNew = (PVDIIMAGEBLOCKPOINTER)RTMemRealloc(pImage->paBlocks, cbBlockspaceNew);
2702 if (paBlocksNew)
2703 {
2704 pImage->paBlocks = paBlocksNew;
2705
2706 /* Mark the new blocks as unallocated. */
2707 for (unsigned idxBlock = cBlocksOld; idxBlock < cBlocksNew; idxBlock++)
2708 pImage->paBlocks[idxBlock] = VDI_IMAGE_BLOCK_FREE;
2709 }
2710 else
2711 rc = VERR_NO_MEMORY;
2712
2713 /* Write the block array before updating the rest. */
2714 vdiConvBlocksEndianess(VDIECONV_H2F, pImage->paBlocks, cBlocksNew);
2715 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pImage->pStorage, pImage->offStartBlocks,
2716 pImage->paBlocks, cbBlockspaceNew);
2717 vdiConvBlocksEndianess(VDIECONV_F2H, pImage->paBlocks, cBlocksNew);
2718
2719 if (RT_SUCCESS(rc))
2720 {
2721 /* Update size and new block count. */
2722 setImageDiskSize(&pImage->Header, cbSize);
2723 setImageBlocks(&pImage->Header, cBlocksNew);
2724 /* Update geometry. */
2725 pImage->PCHSGeometry = *pPCHSGeometry;
2726 pImage->cbImage = cbSize;
2727
2728 PVDIDISKGEOMETRY pGeometry = getImageLCHSGeometry(&pImage->Header);
2729 if (pGeometry)
2730 {
2731 pGeometry->cCylinders = pLCHSGeometry->cCylinders;
2732 pGeometry->cHeads = pLCHSGeometry->cHeads;
2733 pGeometry->cSectors = pLCHSGeometry->cSectors;
2734 pGeometry->cbSector = VDI_GEOMETRY_SECTOR_SIZE;
2735 }
2736 }
2737 }
2738
2739 /* Update header information in base image file. */
2740 vdiFlushImage(pImage);
2741 }
2742 /* Same size doesn't change the image at all. */
2743
2744 LogFlowFunc(("returns %Rrc\n", rc));
2745 return rc;
2746}
2747
2748/** @copydoc VDIMAGEBACKEND::pfnDiscard */
2749static DECLCALLBACK(int) vdiDiscard(void *pBackendData, PVDIOCTX pIoCtx,
2750 uint64_t uOffset, size_t cbDiscard,
2751 size_t *pcbPreAllocated, size_t *pcbPostAllocated,
2752 size_t *pcbActuallyDiscarded, void **ppbmAllocationBitmap,
2753 unsigned fDiscard)
2754{
2755 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
2756 unsigned uBlock;
2757 unsigned offDiscard;
2758 int rc = VINF_SUCCESS;
2759 void *pvBlock = NULL;
2760
2761 LogFlowFunc(("pBackendData=%#p pIoCtx=%#p uOffset=%llu cbDiscard=%zu pcbPreAllocated=%#p pcbPostAllocated=%#p pcbActuallyDiscarded=%#p ppbmAllocationBitmap=%#p fDiscard=%#x\n",
2762 pBackendData, pIoCtx, uOffset, cbDiscard, pcbPreAllocated, pcbPostAllocated, pcbActuallyDiscarded, ppbmAllocationBitmap, fDiscard));
2763
2764 AssertPtr(pImage);
2765 Assert(!(uOffset % 512));
2766 Assert(!(cbDiscard % 512));
2767
2768 AssertMsgReturn(!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY),
2769 ("Image is readonly\n"), VERR_VD_IMAGE_READ_ONLY);
2770 AssertMsgReturn( uOffset + cbDiscard <= getImageDiskSize(&pImage->Header)
2771 && cbDiscard,
2772 ("Invalid parameters uOffset=%llu cbDiscard=%zu\n",
2773 uOffset, cbDiscard),
2774 VERR_INVALID_PARAMETER);
2775
2776 do
2777 {
2778 AssertMsgBreakStmt(!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY),
2779 ("Image is opened readonly\n"),
2780 rc = VERR_VD_IMAGE_READ_ONLY);
2781
2782 AssertMsgBreakStmt(cbDiscard,
2783 ("cbDiscard=%u\n", cbDiscard),
2784 rc = VERR_INVALID_PARAMETER);
2785
2786 /* Calculate starting block number and offset inside it. */
2787 uBlock = (unsigned)(uOffset >> pImage->uShiftOffset2Index);
2788 offDiscard = (unsigned)uOffset & pImage->uBlockMask;
2789
2790 /* Clip range to at most the rest of the block. */
2791 cbDiscard = RT_MIN(cbDiscard, getImageBlockSize(&pImage->Header) - offDiscard);
2792 Assert(!(cbDiscard % 512));
2793
2794 if (pcbPreAllocated)
2795 *pcbPreAllocated = 0;
2796
2797 if (pcbPostAllocated)
2798 *pcbPostAllocated = 0;
2799
2800 if (IS_VDI_IMAGE_BLOCK_ALLOCATED(pImage->paBlocks[uBlock]))
2801 {
2802 unsigned const cbBlock = RT_MAX(getImageBlockSize(&pImage->Header), 1);
2803 size_t const cbPreAllocated = offDiscard % cbBlock;
2804 size_t const cbPostAllocated = getImageBlockSize(&pImage->Header) - cbDiscard - cbPreAllocated;
2805 uint8_t *pbBlockData;
2806
2807 /* Read the block data. */
2808 pvBlock = RTMemAlloc(pImage->cbTotalBlockData);
2809 if (!pvBlock)
2810 {
2811 rc = VERR_NO_MEMORY;
2812 break;
2813 }
2814
2815 if (!cbPreAllocated && !cbPostAllocated)
2816 {
2817 /*
2818 * Discarding a whole block, don't check for allocated sectors.
2819 * It is possible to just remove the whole block which avoids
2820 * one read and checking the whole block for data.
2821 */
2822 rc = vdiDiscardBlockAsync(pImage, pIoCtx, uBlock, pvBlock);
2823 }
2824 else if (fDiscard & VD_DISCARD_MARK_UNUSED)
2825 {
2826 /* Just zero out the given range. */
2827 memset(pvBlock, 0, cbDiscard);
2828
2829 uint64_t u64Offset = (uint64_t)pImage->paBlocks[uBlock] * pImage->cbTotalBlockData + pImage->offStartData + offDiscard;
2830 rc = vdIfIoIntFileWriteMeta(pImage->pIfIo, pImage->pStorage,
2831 u64Offset, pvBlock, cbDiscard, pIoCtx,
2832 NULL, NULL);
2833 RTMemFree(pvBlock);
2834 }
2835 else
2836 {
2837 /*
2838 * Read complete block as metadata, the I/O context has no memory buffer
2839 * and we need to access the content directly anyway.
2840 */
2841 PVDMETAXFER pMetaXfer;
2842 pbBlockData = (uint8_t *)pvBlock + pImage->offStartBlockData;
2843
2844 uint64_t u64Offset = (uint64_t)pImage->paBlocks[uBlock] * pImage->cbTotalBlockData + pImage->offStartData;
2845 rc = vdIfIoIntFileReadMeta(pImage->pIfIo, pImage->pStorage, u64Offset,
2846 pbBlockData, pImage->cbTotalBlockData,
2847 pIoCtx, &pMetaXfer, NULL, NULL);
2848 if (RT_FAILURE(rc))
2849 {
2850 RTMemFree(pvBlock);
2851 break;
2852 }
2853
2854 vdIfIoIntMetaXferRelease(pImage->pIfIo, pMetaXfer);
2855
2856 /* Clear data. */
2857 memset(pbBlockData + offDiscard , 0, cbDiscard);
2858
2859 Assert(!(cbDiscard % 4));
2860 Assert(getImageBlockSize(&pImage->Header) * 8 <= UINT32_MAX);
2861 if (ASMBitFirstSet((volatile void *)pbBlockData, getImageBlockSize(&pImage->Header) * 8) == -1)
2862 rc = vdiDiscardBlockAsync(pImage, pIoCtx, uBlock, pvBlock);
2863 else
2864 {
2865 /* Block has data, create allocation bitmap. */
2866 *pcbPreAllocated = cbPreAllocated;
2867 *pcbPostAllocated = cbPostAllocated;
2868 *ppbmAllocationBitmap = vdiAllocationBitmapCreate(pbBlockData, getImageBlockSize(&pImage->Header));
2869 if (RT_UNLIKELY(!*ppbmAllocationBitmap))
2870 rc = VERR_NO_MEMORY;
2871 else
2872 rc = VERR_VD_DISCARD_ALIGNMENT_NOT_MET;
2873
2874 RTMemFree(pvBlock);
2875 }
2876 } /* if: no complete block discarded */
2877 } /* if: Block is allocated. */
2878 /* else: nothing to do. */
2879 } while (0);
2880
2881 if (pcbActuallyDiscarded)
2882 *pcbActuallyDiscarded = cbDiscard;
2883
2884 LogFlowFunc(("returns %Rrc\n", rc));
2885 return rc;
2886}
2887
2888/** @copydoc VDIMAGEBACKEND::pfnRepair */
2889static DECLCALLBACK(int) vdiRepair(const char *pszFilename, PVDINTERFACE pVDIfsDisk,
2890 PVDINTERFACE pVDIfsImage, uint32_t fFlags)
2891{
2892 LogFlowFunc(("pszFilename=\"%s\" pVDIfsDisk=%#p pVDIfsImage=%#p\n", pszFilename, pVDIfsDisk, pVDIfsImage));
2893 int rc;
2894 PVDINTERFACEERROR pIfError;
2895 PVDINTERFACEIOINT pIfIo;
2896 PVDIOSTORAGE pStorage = NULL;
2897 uint64_t cbFile;
2898 PVDIIMAGEBLOCKPOINTER paBlocks = NULL;
2899 uint32_t *pu32BlockBitmap = NULL;
2900 VDIPREHEADER PreHdr;
2901 VDIHEADER Hdr;
2902
2903 pIfIo = VDIfIoIntGet(pVDIfsImage);
2904 AssertPtrReturn(pIfIo, VERR_INVALID_PARAMETER);
2905
2906 pIfError = VDIfErrorGet(pVDIfsDisk);
2907
2908 do
2909 {
2910 bool fRepairBlockArray = false;
2911 bool fRepairHdr = false;
2912
2913 rc = vdIfIoIntFileOpen(pIfIo, pszFilename,
2914 VDOpenFlagsToFileOpenFlags( fFlags & VD_REPAIR_DRY_RUN
2915 ? VD_OPEN_FLAGS_READONLY
2916 : 0,
2917 false /* fCreate */),
2918 &pStorage);
2919 if (RT_FAILURE(rc))
2920 {
2921 rc = vdIfError(pIfError, rc, RT_SRC_POS, "VDI: Failed to open image \"%s\"", pszFilename);
2922 break;
2923 }
2924
2925 rc = vdIfIoIntFileGetSize(pIfIo, pStorage, &cbFile);
2926 if (RT_FAILURE(rc))
2927 {
2928 rc = vdIfError(pIfError, rc, RT_SRC_POS, "VDI: Failed to query image size");
2929 break;
2930 }
2931
2932 /* Read pre-header. */
2933 rc = vdIfIoIntFileReadSync(pIfIo, pStorage, 0, &PreHdr, sizeof(PreHdr));
2934 if (RT_FAILURE(rc))
2935 {
2936 rc = vdIfError(pIfError, rc, RT_SRC_POS, N_("VDI: Error reading pre-header in '%s'"), pszFilename);
2937 break;
2938 }
2939 vdiConvPreHeaderEndianess(VDIECONV_F2H, &PreHdr, &PreHdr);
2940 rc = vdiValidatePreHeader(&PreHdr);
2941 if (RT_FAILURE(rc))
2942 {
2943 rc = vdIfError(pIfError, VERR_VD_IMAGE_REPAIR_IMPOSSIBLE, RT_SRC_POS,
2944 N_("VDI: invalid pre-header in '%s'"), pszFilename);
2945 break;
2946 }
2947
2948 /* Read header. */
2949 Hdr.uVersion = PreHdr.u32Version;
2950 switch (GET_MAJOR_HEADER_VERSION(&Hdr))
2951 {
2952 case 0:
2953 rc = vdIfIoIntFileReadSync(pIfIo, pStorage, sizeof(PreHdr),
2954 &Hdr.u.v0, sizeof(Hdr.u.v0));
2955 if (RT_FAILURE(rc))
2956 rc = vdIfError(pIfError, rc, RT_SRC_POS, N_("VDI: error reading v0 header in '%s'"),
2957 pszFilename);
2958 vdiConvHeaderEndianessV0(VDIECONV_F2H, &Hdr.u.v0, &Hdr.u.v0);
2959 break;
2960 case 1:
2961 rc = vdIfIoIntFileReadSync(pIfIo, pStorage, sizeof(PreHdr),
2962 &Hdr.u.v1, sizeof(Hdr.u.v1));
2963 if (RT_FAILURE(rc))
2964 {
2965 rc = vdIfError(pIfError, rc, RT_SRC_POS, N_("VDI: error reading v1 header in '%s'"),
2966 pszFilename);
2967 }
2968 vdiConvHeaderEndianessV1(VDIECONV_F2H, &Hdr.u.v1, &Hdr.u.v1);
2969 if (Hdr.u.v1.cbHeader >= sizeof(Hdr.u.v1plus))
2970 {
2971 /* Read the VDI 1.1+ header completely. */
2972 rc = vdIfIoIntFileReadSync(pIfIo, pStorage, sizeof(PreHdr),
2973 &Hdr.u.v1plus, sizeof(Hdr.u.v1plus));
2974 if (RT_FAILURE(rc))
2975 rc = vdIfError(pIfError, rc, RT_SRC_POS, N_("VDI: error reading v1.1+ header in '%s'"),
2976 pszFilename);
2977 vdiConvHeaderEndianessV1p(VDIECONV_F2H, &Hdr.u.v1plus, &Hdr.u.v1plus);
2978 }
2979 break;
2980 default:
2981 rc = vdIfError(pIfError, VERR_VD_IMAGE_REPAIR_IMPOSSIBLE, RT_SRC_POS,
2982 N_("VDI: unsupported major version %u in '%s'"),
2983 GET_MAJOR_HEADER_VERSION(&Hdr), pszFilename);
2984 break;
2985 }
2986
2987 if (RT_SUCCESS(rc))
2988 {
2989 rc = vdiValidateHeader(&Hdr);
2990 if (RT_FAILURE(rc))
2991 {
2992 rc = vdIfError(pIfError, VERR_VD_IMAGE_REPAIR_IMPOSSIBLE, RT_SRC_POS,
2993 N_("VDI: invalid header in '%s'"), pszFilename);
2994 break;
2995 }
2996 }
2997
2998 /*
2999 * Check that the disk size is correctly aligned,
3000 * see comment above the same check in vdiImageReadHeader().
3001 */
3002 uint64_t cbDisk = getImageDiskSize(&Hdr);
3003 if (cbDisk & 0x1ff)
3004 {
3005 uint64_t cbDiskNew = cbDisk & ~UINT64_C(0x1ff);
3006 vdIfErrorMessage(pIfError, "Disk size in the header is not sector aligned, rounding down (%llu -> %llu)\n",
3007 cbDisk, cbDiskNew);
3008 setImageDiskSize(&Hdr, cbDiskNew);
3009 fRepairHdr = true;
3010 }
3011
3012 /* Setup image parameters by header. */
3013 uint64_t offStartBlocks, offStartData;
3014 size_t cbTotalBlockData;
3015
3016 offStartBlocks = getImageBlocksOffset(&Hdr);
3017 offStartData = getImageDataOffset(&Hdr);
3018 cbTotalBlockData = getImageExtraBlockSize(&Hdr) + getImageBlockSize(&Hdr);
3019
3020 /* Allocate memory for blocks array. */
3021 paBlocks = (PVDIIMAGEBLOCKPOINTER)RTMemAlloc(sizeof(VDIIMAGEBLOCKPOINTER) * getImageBlocks(&Hdr));
3022 if (!paBlocks)
3023 {
3024 rc = vdIfError(pIfError, VERR_NO_MEMORY, RT_SRC_POS,
3025 "Failed to allocate memory for block array");
3026 break;
3027 }
3028
3029 /* Read blocks array. */
3030 rc = vdIfIoIntFileReadSync(pIfIo, pStorage, offStartBlocks, paBlocks,
3031 getImageBlocks(&Hdr) * sizeof(VDIIMAGEBLOCKPOINTER));
3032 if (RT_FAILURE(rc))
3033 {
3034 rc = vdIfError(pIfError, VERR_VD_IMAGE_REPAIR_IMPOSSIBLE, RT_SRC_POS,
3035 "Failed to read block array (at %llu), %Rrc",
3036 offStartBlocks, rc);
3037 break;
3038 }
3039 vdiConvBlocksEndianess(VDIECONV_F2H, paBlocks, getImageBlocks(&Hdr));
3040
3041 pu32BlockBitmap = (uint32_t *)RTMemAllocZ(RT_ALIGN_Z(getImageBlocks(&Hdr) / 8, 4));
3042 if (!pu32BlockBitmap)
3043 {
3044 rc = vdIfError(pIfError, VERR_NO_MEMORY, RT_SRC_POS,
3045 "Failed to allocate memory for block bitmap");
3046 break;
3047 }
3048
3049 for (uint32_t i = 0; i < getImageBlocks(&Hdr); i++)
3050 {
3051 if (IS_VDI_IMAGE_BLOCK_ALLOCATED(paBlocks[i]))
3052 {
3053 uint64_t offBlock = (uint64_t)paBlocks[i] * cbTotalBlockData
3054 + offStartData;
3055
3056 /*
3057 * Check that the offsets are valid (inside of the image) and
3058 * that there are no double references.
3059 */
3060 if (offBlock + cbTotalBlockData > cbFile)
3061 {
3062 vdIfErrorMessage(pIfError, "Entry %u points to invalid offset %llu, clearing\n",
3063 i, offBlock);
3064 paBlocks[i] = VDI_IMAGE_BLOCK_FREE;
3065 fRepairBlockArray = true;
3066 }
3067 else if (ASMBitTestAndSet(pu32BlockBitmap, paBlocks[i]))
3068 {
3069 vdIfErrorMessage(pIfError, "Entry %u points to an already referenced data block, clearing\n",
3070 i);
3071 paBlocks[i] = VDI_IMAGE_BLOCK_FREE;
3072 fRepairBlockArray = true;
3073 }
3074 }
3075 }
3076
3077 /* Write repaired structures now. */
3078 if (!fRepairBlockArray && !fRepairHdr)
3079 vdIfErrorMessage(pIfError, "VDI image is in a consistent state, no repair required\n");
3080 else if (!(fFlags & VD_REPAIR_DRY_RUN))
3081 {
3082 if (fRepairHdr)
3083 {
3084 switch (GET_MAJOR_HEADER_VERSION(&Hdr))
3085 {
3086 case 0:
3087 {
3088 VDIHEADER0 Hdr0;
3089 vdiConvHeaderEndianessV0(VDIECONV_H2F, &Hdr0, &Hdr.u.v0);
3090 rc = vdIfIoIntFileWriteSync(pIfIo, pStorage, sizeof(VDIPREHEADER),
3091 &Hdr0, sizeof(Hdr0));
3092 break;
3093 }
3094 case 1:
3095 if (Hdr.u.v1plus.cbHeader < sizeof(Hdr.u.v1plus))
3096 {
3097 VDIHEADER1 Hdr1;
3098 vdiConvHeaderEndianessV1(VDIECONV_H2F, &Hdr1, &Hdr.u.v1);
3099 rc = vdIfIoIntFileWriteSync(pIfIo, pStorage, sizeof(VDIPREHEADER),
3100 &Hdr1, sizeof(Hdr1));
3101 }
3102 else
3103 {
3104 VDIHEADER1PLUS Hdr1plus;
3105 vdiConvHeaderEndianessV1p(VDIECONV_H2F, &Hdr1plus, &Hdr.u.v1plus);
3106 rc = vdIfIoIntFileWriteSync(pIfIo, pStorage, sizeof(VDIPREHEADER),
3107 &Hdr1plus, sizeof(Hdr1plus));
3108 }
3109 break;
3110 default:
3111 AssertMsgFailed(("Header indicates unsupported version which should not happen here!\n"));
3112 rc = VERR_VD_VDI_UNSUPPORTED_VERSION;
3113 break;
3114 }
3115 }
3116
3117 if (fRepairBlockArray)
3118 {
3119 vdIfErrorMessage(pIfError, "Writing repaired block allocation table...\n");
3120
3121 vdiConvBlocksEndianess(VDIECONV_H2F, paBlocks, getImageBlocks(&Hdr));
3122 rc = vdIfIoIntFileWriteSync(pIfIo, pStorage, offStartBlocks, paBlocks,
3123 getImageBlocks(&Hdr) * sizeof(VDIIMAGEBLOCKPOINTER));
3124 if (RT_FAILURE(rc))
3125 {
3126 rc = vdIfError(pIfError, VERR_VD_IMAGE_REPAIR_IMPOSSIBLE, RT_SRC_POS,
3127 "Could not write repaired block allocation table (at %llu), %Rrc",
3128 offStartBlocks, rc);
3129 break;
3130 }
3131 }
3132 }
3133
3134 vdIfErrorMessage(pIfError, "Corrupted VDI image repaired successfully\n");
3135 } while(0);
3136
3137 if (paBlocks)
3138 RTMemFree(paBlocks);
3139
3140 if (pu32BlockBitmap)
3141 RTMemFree(pu32BlockBitmap);
3142
3143 if (pStorage)
3144 {
3145 int rc2 = vdIfIoIntFileClose(pIfIo, pStorage);
3146 if (RT_SUCCESS(rc))
3147 rc = rc2; /* Propagate error code only if repairing was successful. */
3148 }
3149
3150 LogFlowFunc(("returns %Rrc\n", rc));
3151 return rc;
3152}
3153
3154const VDIMAGEBACKEND g_VDIBackend =
3155{
3156 /* u32Version */
3157 VD_IMGBACKEND_VERSION,
3158 /* pszBackendName */
3159 "VDI",
3160 /* uBackendCaps */
3161 VD_CAP_UUID | VD_CAP_CREATE_FIXED | VD_CAP_CREATE_DYNAMIC
3162 | VD_CAP_DIFF | VD_CAP_FILE | VD_CAP_ASYNC | VD_CAP_VFS | VD_CAP_DISCARD
3163 | VD_CAP_PREFERRED,
3164 /* paFileExtensions */
3165 s_aVdiFileExtensions,
3166 /* paConfigInfo */
3167 vdiConfigInfo,
3168 /* pfnProbe */
3169 vdiProbe,
3170 /* pfnOpen */
3171 vdiOpen,
3172 /* pfnCreate */
3173 vdiCreate,
3174 /* pfnRename */
3175 vdiRename,
3176 /* pfnClose */
3177 vdiClose,
3178 /* pfnRead */
3179 vdiRead,
3180 /* pfnWrite */
3181 vdiWrite,
3182 /* pfnFlush */
3183 vdiFlush,
3184 /* pfnDiscard */
3185 vdiDiscard,
3186 /* pfnGetVersion */
3187 vdiGetVersion,
3188 /* pfnGetFileSize */
3189 vdiGetFileSize,
3190 /* pfnGetPCHSGeometry */
3191 vdiGetPCHSGeometry,
3192 /* pfnSetPCHSGeometry */
3193 vdiSetPCHSGeometry,
3194 /* pfnGetLCHSGeometry */
3195 vdiGetLCHSGeometry,
3196 /* pfnSetLCHSGeometry */
3197 vdiSetLCHSGeometry,
3198 /* pfnQueryRegions */
3199 vdiQueryRegions,
3200 /* pfnRegionListRelease */
3201 vdiRegionListRelease,
3202 /* pfnGetImageFlags */
3203 vdiGetImageFlags,
3204 /* pfnGetOpenFlags */
3205 vdiGetOpenFlags,
3206 /* pfnSetOpenFlags */
3207 vdiSetOpenFlags,
3208 /* pfnGetComment */
3209 vdiGetComment,
3210 /* pfnSetComment */
3211 vdiSetComment,
3212 /* pfnGetUuid */
3213 vdiGetUuid,
3214 /* pfnSetUuid */
3215 vdiSetUuid,
3216 /* pfnGetModificationUuid */
3217 vdiGetModificationUuid,
3218 /* pfnSetModificationUuid */
3219 vdiSetModificationUuid,
3220 /* pfnGetParentUuid */
3221 vdiGetParentUuid,
3222 /* pfnSetParentUuid */
3223 vdiSetParentUuid,
3224 /* pfnGetParentModificationUuid */
3225 vdiGetParentModificationUuid,
3226 /* pfnSetParentModificationUuid */
3227 vdiSetParentModificationUuid,
3228 /* pfnDump */
3229 vdiDump,
3230 /* pfnGetTimestamp */
3231 NULL,
3232 /* pfnGetParentTimestamp */
3233 NULL,
3234 /* pfnSetParentTimestamp */
3235 NULL,
3236 /* pfnGetParentFilename */
3237 NULL,
3238 /* pfnSetParentFilename */
3239 NULL,
3240 /* pfnComposeLocation */
3241 genericFileComposeLocation,
3242 /* pfnComposeName */
3243 genericFileComposeName,
3244 /* pfnCompact */
3245 vdiCompact,
3246 /* pfnResize */
3247 vdiResize,
3248 /* pfnRepair */
3249 vdiRepair,
3250 /* pfnTraverseMetadata */
3251 NULL,
3252 /* u32VersionEnd */
3253 VD_IMGBACKEND_VERSION
3254};
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