VirtualBox

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

Last change on this file since 45482 was 45069, checked in by vboxsync, 12 years ago

Storage/VDI: Remove rounding to the next MB boundary (should fix public #11597)

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