VirtualBox

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

Last change on this file since 49971 was 48851, checked in by vboxsync, 11 years ago

Storage: Addressing 64-bit windows warnings.

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