VirtualBox

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

Last change on this file since 65644 was 65644, checked in by vboxsync, 8 years ago

gcc 7: Storage: fall thru

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