VirtualBox

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

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

Storage: Doxygen fixes

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 120.5 KB
Line 
1/* $Id: VDI.cpp 64272 2016-10-14 08:25:05Z 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 else
824 rc = vdIfError(pImage->pIfError, VERR_VD_VDI_INVALID_HEADER, RT_SRC_POS,
825 N_("VDI: invalid header in '%s'"), pImage->pszFilename);
826 }
827 }
828 else
829 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VDI: invalid pre-header in '%s'"), pImage->pszFilename);
830 }
831 else
832 {
833 vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VDI: error reading pre-header in '%s'"), pImage->pszFilename);
834 rc = VERR_VD_VDI_INVALID_HEADER;
835 }
836 }
837 else
838 {
839 vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VDI: error getting the image size in '%s'"), pImage->pszFilename);
840 rc = VERR_VD_VDI_INVALID_HEADER;
841 }
842
843 return rc;
844}
845
846/**
847 * Creates the back resolving table for the image for the discard operation.
848 *
849 * @returns VBox status code.
850 * @param pImage The VDI image descriptor.
851 */
852static int vdiImageBackResolvTblCreate(PVDIIMAGEDESC pImage)
853{
854 int rc = VINF_SUCCESS;
855
856 /*
857 * Any error or inconsistency results in a fail because this might
858 * get us into trouble later on.
859 */
860 pImage->paBlocksRev = (unsigned *)RTMemAllocZ(sizeof(unsigned) * getImageBlocks(&pImage->Header));
861 if (pImage->paBlocksRev)
862 {
863 unsigned cBlocksAllocated = getImageBlocksAllocated(&pImage->Header);
864 unsigned cBlocks = getImageBlocks(&pImage->Header);
865
866 for (unsigned i = 0; i < cBlocks; i++)
867 pImage->paBlocksRev[i] = VDI_IMAGE_BLOCK_FREE;
868
869 for (unsigned i = 0; i < cBlocks; i++)
870 {
871 VDIIMAGEBLOCKPOINTER ptrBlock = pImage->paBlocks[i];
872 if (IS_VDI_IMAGE_BLOCK_ALLOCATED(ptrBlock))
873 {
874 if (ptrBlock < cBlocksAllocated)
875 {
876 if (pImage->paBlocksRev[ptrBlock] == VDI_IMAGE_BLOCK_FREE)
877 pImage->paBlocksRev[ptrBlock] = i;
878 else
879 {
880 rc = VERR_VD_VDI_INVALID_HEADER;
881 break;
882 }
883 }
884 else
885 {
886 rc = VERR_VD_VDI_INVALID_HEADER;
887 break;
888 }
889 }
890 }
891 }
892 else
893 rc = VERR_NO_MEMORY;
894
895 return rc;
896}
897
898/**
899 * Internal: Open a VDI image.
900 */
901static int vdiOpenImage(PVDIIMAGEDESC pImage, unsigned uOpenFlags)
902{
903 pImage->uOpenFlags = uOpenFlags;
904
905 pImage->pIfError = VDIfErrorGet(pImage->pVDIfsDisk);
906 pImage->pIfIo = VDIfIoIntGet(pImage->pVDIfsImage);
907 AssertPtrReturn(pImage->pIfIo, VERR_INVALID_PARAMETER);
908
909 /*
910 * Open the image.
911 */
912 int rc = vdIfIoIntFileOpen(pImage->pIfIo, pImage->pszFilename,
913 VDOpenFlagsToFileOpenFlags(uOpenFlags, false /* fCreate */),
914 &pImage->pStorage);
915 if (RT_SUCCESS(rc))
916 {
917 rc = vdiImageReadHeader(pImage);
918 if (RT_SUCCESS(rc))
919 {
920 /* Allocate memory for blocks array. */
921 pImage->paBlocks = (PVDIIMAGEBLOCKPOINTER)RTMemAlloc(sizeof(VDIIMAGEBLOCKPOINTER) * getImageBlocks(&pImage->Header));
922 if (RT_LIKELY(pImage->paBlocks))
923 {
924 /* Read blocks array. */
925 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pImage->pStorage, pImage->offStartBlocks, pImage->paBlocks,
926 getImageBlocks(&pImage->Header) * sizeof(VDIIMAGEBLOCKPOINTER));
927 if (RT_SUCCESS(rc))
928 {
929 vdiConvBlocksEndianess(VDIECONV_F2H, pImage->paBlocks, getImageBlocks(&pImage->Header));
930
931 if (uOpenFlags & VD_OPEN_FLAGS_DISCARD)
932 rc = vdiImageBackResolvTblCreate(pImage);
933 }
934 else
935 rc = vdIfError(pImage->pIfError, rc, RT_SRC_POS, N_("VDI: Error reading the block table in '%s'"), pImage->pszFilename);
936 }
937 else
938 rc = vdIfError(pImage->pIfError, VERR_NO_MEMORY, RT_SRC_POS,
939 N_("VDI: Error allocating memory for the block table in '%s'"), pImage->pszFilename);;
940 }
941 }
942 /* else: Do NOT signal an appropriate error here, as the VD layer has the
943 * choice of retrying the open if it failed. */
944
945 if (RT_FAILURE(rc))
946 vdiFreeImage(pImage, false);
947 return rc;
948}
949
950/**
951 * Internal: Save header to file.
952 */
953static int vdiUpdateHeader(PVDIIMAGEDESC pImage)
954{
955 int rc;
956 switch (GET_MAJOR_HEADER_VERSION(&pImage->Header))
957 {
958 case 0:
959 {
960 VDIHEADER0 Hdr;
961 vdiConvHeaderEndianessV0(VDIECONV_H2F, &Hdr, &pImage->Header.u.v0);
962 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pImage->pStorage, sizeof(VDIPREHEADER),
963 &Hdr, sizeof(Hdr));
964 break;
965 }
966 case 1:
967 if (pImage->Header.u.v1plus.cbHeader < sizeof(pImage->Header.u.v1plus))
968 {
969 VDIHEADER1 Hdr;
970 vdiConvHeaderEndianessV1(VDIECONV_H2F, &Hdr, &pImage->Header.u.v1);
971 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pImage->pStorage, sizeof(VDIPREHEADER),
972 &Hdr, sizeof(Hdr));
973 }
974 else
975 {
976 VDIHEADER1PLUS Hdr;
977 vdiConvHeaderEndianessV1p(VDIECONV_H2F, &Hdr, &pImage->Header.u.v1plus);
978 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pImage->pStorage, sizeof(VDIPREHEADER),
979 &Hdr, sizeof(Hdr));
980 }
981 break;
982 default:
983 rc = VERR_VD_VDI_UNSUPPORTED_VERSION;
984 break;
985 }
986 AssertMsgRC(rc, ("vdiUpdateHeader failed, filename=\"%s\" rc=%Rrc\n", pImage->pszFilename, rc));
987 return rc;
988}
989
990/**
991 * Internal: Save header to file - async version.
992 */
993static int vdiUpdateHeaderAsync(PVDIIMAGEDESC pImage, PVDIOCTX pIoCtx)
994{
995 int rc;
996 switch (GET_MAJOR_HEADER_VERSION(&pImage->Header))
997 {
998 case 0:
999 {
1000 VDIHEADER0 Hdr;
1001 vdiConvHeaderEndianessV0(VDIECONV_H2F, &Hdr, &pImage->Header.u.v0);
1002 rc = vdIfIoIntFileWriteMeta(pImage->pIfIo, pImage->pStorage,
1003 sizeof(VDIPREHEADER), &Hdr, sizeof(Hdr),
1004 pIoCtx, NULL, NULL);
1005 break;
1006 }
1007 case 1:
1008 if (pImage->Header.u.v1plus.cbHeader < sizeof(pImage->Header.u.v1plus))
1009 {
1010 VDIHEADER1 Hdr;
1011 vdiConvHeaderEndianessV1(VDIECONV_H2F, &Hdr, &pImage->Header.u.v1);
1012 rc = vdIfIoIntFileWriteMeta(pImage->pIfIo, pImage->pStorage,
1013 sizeof(VDIPREHEADER), &Hdr, sizeof(Hdr),
1014 pIoCtx, NULL, NULL);
1015 }
1016 else
1017 {
1018 VDIHEADER1PLUS Hdr;
1019 vdiConvHeaderEndianessV1p(VDIECONV_H2F, &Hdr, &pImage->Header.u.v1plus);
1020 rc = vdIfIoIntFileWriteMeta(pImage->pIfIo, pImage->pStorage,
1021 sizeof(VDIPREHEADER), &Hdr, sizeof(Hdr),
1022 pIoCtx, NULL, NULL);
1023 }
1024 break;
1025 default:
1026 rc = VERR_VD_VDI_UNSUPPORTED_VERSION;
1027 break;
1028 }
1029 AssertMsg(RT_SUCCESS(rc) || rc == VERR_VD_ASYNC_IO_IN_PROGRESS,
1030 ("vdiUpdateHeader failed, filename=\"%s\" rc=%Rrc\n", pImage->pszFilename, rc));
1031 return rc;
1032}
1033
1034/**
1035 * Internal: Save block pointer to file, save header to file.
1036 */
1037static int vdiUpdateBlockInfo(PVDIIMAGEDESC pImage, unsigned uBlock)
1038{
1039 /* Update image header. */
1040 int rc = vdiUpdateHeader(pImage);
1041 if (RT_SUCCESS(rc))
1042 {
1043 /* write only one block pointer. */
1044 VDIIMAGEBLOCKPOINTER ptrBlock = RT_H2LE_U32(pImage->paBlocks[uBlock]);
1045 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pImage->pStorage,
1046 pImage->offStartBlocks + uBlock * sizeof(VDIIMAGEBLOCKPOINTER),
1047 &ptrBlock, sizeof(VDIIMAGEBLOCKPOINTER));
1048 AssertMsgRC(rc, ("vdiUpdateBlockInfo failed to update block=%u, filename=\"%s\", rc=%Rrc\n",
1049 uBlock, pImage->pszFilename, rc));
1050 }
1051 return rc;
1052}
1053
1054/**
1055 * Internal: Save block pointer to file, save header to file - async version.
1056 */
1057static int vdiUpdateBlockInfoAsync(PVDIIMAGEDESC pImage, unsigned uBlock,
1058 PVDIOCTX pIoCtx, bool fUpdateHdr)
1059{
1060 int rc = VINF_SUCCESS;
1061
1062 /* Update image header. */
1063 if (fUpdateHdr)
1064 rc = vdiUpdateHeaderAsync(pImage, pIoCtx);
1065
1066 if (RT_SUCCESS(rc) || rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
1067 {
1068 /* write only one block pointer. */
1069 VDIIMAGEBLOCKPOINTER ptrBlock = RT_H2LE_U32(pImage->paBlocks[uBlock]);
1070 rc = vdIfIoIntFileWriteMeta(pImage->pIfIo, pImage->pStorage,
1071 pImage->offStartBlocks + uBlock * sizeof(VDIIMAGEBLOCKPOINTER),
1072 &ptrBlock, sizeof(VDIIMAGEBLOCKPOINTER),
1073 pIoCtx, NULL, NULL);
1074 AssertMsg(RT_SUCCESS(rc) || rc == VERR_VD_ASYNC_IO_IN_PROGRESS,
1075 ("vdiUpdateBlockInfo failed to update block=%u, filename=\"%s\", rc=%Rrc\n",
1076 uBlock, pImage->pszFilename, rc));
1077 }
1078 return rc;
1079}
1080
1081/**
1082 * Internal: Flush the image file to disk - async version.
1083 */
1084static int vdiFlushImageIoCtx(PVDIIMAGEDESC pImage, PVDIOCTX pIoCtx)
1085{
1086 int rc = VINF_SUCCESS;
1087
1088 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
1089 {
1090 /* Save header. */
1091 rc = vdiUpdateHeaderAsync(pImage, pIoCtx);
1092 AssertMsg(RT_SUCCESS(rc) || rc == VERR_VD_ASYNC_IO_IN_PROGRESS,
1093 ("vdiUpdateHeaderAsync() failed, filename=\"%s\", rc=%Rrc\n",
1094 pImage->pszFilename, rc));
1095 rc = vdIfIoIntFileFlush(pImage->pIfIo, pImage->pStorage, pIoCtx, NULL, NULL);
1096 AssertMsg(RT_SUCCESS(rc) || rc == VERR_VD_ASYNC_IO_IN_PROGRESS,
1097 ("Flushing data to disk failed rc=%Rrc\n", rc));
1098 }
1099
1100 return rc;
1101}
1102
1103/**
1104 * Completion callback for meta/userdata reads or writes.
1105 *
1106 * @return VBox status code.
1107 * VINF_SUCCESS if everything was successful and the transfer can continue.
1108 * VERR_VD_ASYNC_IO_IN_PROGRESS if there is another data transfer pending.
1109 * @param pBackendData The opaque backend data.
1110 * @param pIoCtx I/O context associated with this request.
1111 * @param pvUser Opaque user data passed during a read/write request.
1112 * @param rcReq Status code for the completed request.
1113 */
1114static DECLCALLBACK(int) vdiDiscardBlockAsyncUpdate(void *pBackendData, PVDIOCTX pIoCtx, void *pvUser, int rcReq)
1115{
1116 RT_NOREF1(rcReq);
1117 int rc = VINF_SUCCESS;
1118 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1119 PVDIBLOCKDISCARDASYNC pDiscardAsync = (PVDIBLOCKDISCARDASYNC)pvUser;
1120
1121 switch (pDiscardAsync->enmState)
1122 {
1123 case VDIBLOCKDISCARDSTATE_READ_BLOCK:
1124 {
1125 PVDMETAXFER pMetaXfer;
1126 uint64_t u64Offset = (uint64_t)pDiscardAsync->idxLastBlock * pImage->cbTotalBlockData + pImage->offStartData;
1127 rc = vdIfIoIntFileReadMeta(pImage->pIfIo, pImage->pStorage, u64Offset,
1128 pDiscardAsync->pvBlock, pImage->cbTotalBlockData, pIoCtx,
1129 &pMetaXfer, vdiDiscardBlockAsyncUpdate, pDiscardAsync);
1130 if (RT_FAILURE(rc))
1131 break;
1132
1133 /* Release immediately and go to next step. */
1134 vdIfIoIntMetaXferRelease(pImage->pIfIo, pMetaXfer);
1135 pDiscardAsync->enmState = VDIBLOCKDISCARDSTATE_WRITE_BLOCK;
1136 }
1137 case VDIBLOCKDISCARDSTATE_WRITE_BLOCK:
1138 {
1139 /* Block read complete. Write to the new location (discarded block). */
1140 uint64_t u64Offset = (uint64_t)pDiscardAsync->ptrBlockDiscard * pImage->cbTotalBlockData + pImage->offStartData;
1141 rc = vdIfIoIntFileWriteMeta(pImage->pIfIo, pImage->pStorage, u64Offset,
1142 pDiscardAsync->pvBlock, pImage->cbTotalBlockData, pIoCtx,
1143 vdiDiscardBlockAsyncUpdate, pDiscardAsync);
1144
1145 pDiscardAsync->enmState = VDIBLOCKDISCARDSTATE_UPDATE_METADATA;
1146 if (RT_FAILURE(rc))
1147 break;
1148 }
1149 case VDIBLOCKDISCARDSTATE_UPDATE_METADATA:
1150 {
1151 int rc2;
1152
1153 /* Block write complete. Update metadata. */
1154 pImage->paBlocksRev[pDiscardAsync->idxLastBlock] = VDI_IMAGE_BLOCK_FREE;
1155 pImage->paBlocks[pDiscardAsync->uBlock] = VDI_IMAGE_BLOCK_ZERO;
1156
1157 if (pDiscardAsync->idxLastBlock != pDiscardAsync->ptrBlockDiscard)
1158 {
1159 pImage->paBlocks[pDiscardAsync->uBlockLast] = pDiscardAsync->ptrBlockDiscard;
1160 pImage->paBlocksRev[pDiscardAsync->ptrBlockDiscard] = pDiscardAsync->uBlockLast;
1161
1162 rc = vdiUpdateBlockInfoAsync(pImage, pDiscardAsync->uBlockLast, pIoCtx, false /* fUpdateHdr */);
1163 if ( RT_FAILURE(rc)
1164 && rc != VERR_VD_ASYNC_IO_IN_PROGRESS)
1165 break;
1166 }
1167
1168 setImageBlocksAllocated(&pImage->Header, pDiscardAsync->idxLastBlock);
1169 rc = vdiUpdateBlockInfoAsync(pImage, pDiscardAsync->uBlock, pIoCtx, true /* fUpdateHdr */);
1170 if ( RT_FAILURE(rc)
1171 && rc != VERR_VD_ASYNC_IO_IN_PROGRESS)
1172 break;
1173
1174 pImage->cbImage -= pImage->cbTotalBlockData;
1175 LogFlowFunc(("Set new size %llu\n", pImage->cbImage));
1176 rc2 = vdIfIoIntFileSetSize(pImage->pIfIo, pImage->pStorage, pImage->cbImage);
1177 if (RT_FAILURE(rc2))
1178 rc = rc2;
1179
1180 /* Free discard state. */
1181 RTMemFree(pDiscardAsync->pvBlock);
1182 RTMemFree(pDiscardAsync);
1183 break;
1184 }
1185 default:
1186 AssertMsgFailed(("Invalid state %d\n", pDiscardAsync->enmState));
1187 }
1188
1189 if (rc == VERR_VD_NOT_ENOUGH_METADATA)
1190 rc = VERR_VD_ASYNC_IO_IN_PROGRESS;
1191
1192 return rc;
1193}
1194
1195/**
1196 * Internal: Discard a whole block from the image filling the created hole with
1197 * data from another block - async I/O version.
1198 *
1199 * @returns VBox status code.
1200 * @param pImage VDI image instance data.
1201 * @param pIoCtx I/O context associated with this request.
1202 * @param uBlock The block to discard.
1203 * @param pvBlock Memory to use for the I/O.
1204 */
1205static int vdiDiscardBlockAsync(PVDIIMAGEDESC pImage, PVDIOCTX pIoCtx,
1206 unsigned uBlock, void *pvBlock)
1207{
1208 int rc = VINF_SUCCESS;
1209 PVDIBLOCKDISCARDASYNC pDiscardAsync = NULL;
1210
1211 LogFlowFunc(("pImage=%#p uBlock=%u pvBlock=%#p\n",
1212 pImage, uBlock, pvBlock));
1213
1214 pDiscardAsync = (PVDIBLOCKDISCARDASYNC)RTMemAllocZ(sizeof(VDIBLOCKDISCARDASYNC));
1215 if (RT_UNLIKELY(!pDiscardAsync))
1216 return VERR_NO_MEMORY;
1217
1218 /* Init block discard state. */
1219 pDiscardAsync->uBlock = uBlock;
1220 pDiscardAsync->pvBlock = pvBlock;
1221 pDiscardAsync->ptrBlockDiscard = pImage->paBlocks[uBlock];
1222 pDiscardAsync->idxLastBlock = getImageBlocksAllocated(&pImage->Header) - 1;
1223 pDiscardAsync->uBlockLast = pImage->paBlocksRev[pDiscardAsync->idxLastBlock];
1224
1225 /*
1226 * The block is empty, remove it.
1227 * Read the last block of the image first.
1228 */
1229 if (pDiscardAsync->idxLastBlock != pDiscardAsync->ptrBlockDiscard)
1230 {
1231 LogFlowFunc(("Moving block [%u]=%u into [%u]=%u\n",
1232 pDiscardAsync->uBlockLast, pDiscardAsync->idxLastBlock,
1233 uBlock, pImage->paBlocks[uBlock]));
1234 pDiscardAsync->enmState = VDIBLOCKDISCARDSTATE_READ_BLOCK;
1235 }
1236 else
1237 {
1238 pDiscardAsync->enmState = VDIBLOCKDISCARDSTATE_UPDATE_METADATA; /* Start immediately to shrink the image. */
1239 LogFlowFunc(("Discard last block [%u]=%u\n", uBlock, pImage->paBlocks[uBlock]));
1240 }
1241
1242 /* Call the update callback directly. */
1243 rc = vdiDiscardBlockAsyncUpdate(pImage, pIoCtx, pDiscardAsync, VINF_SUCCESS);
1244
1245 LogFlowFunc(("returns rc=%Rrc\n", rc));
1246 return rc;
1247}
1248
1249/**
1250 * Internal: Creates a allocation bitmap from the given data.
1251 * Sectors which contain only 0 are marked as unallocated and sectors with
1252 * other data as allocated.
1253 *
1254 * @returns Pointer to the allocation bitmap or NULL on failure.
1255 * @param pvData The data to create the allocation bitmap for.
1256 * @param cbData Number of bytes in the buffer.
1257 */
1258static void *vdiAllocationBitmapCreate(void *pvData, size_t cbData)
1259{
1260 Assert(cbData <= UINT32_MAX / 8);
1261 uint32_t cSectors = (uint32_t)(cbData / 512);
1262 uint32_t uSectorCur = 0;
1263 void *pbmAllocationBitmap = NULL;
1264
1265 Assert(!(cbData % 512));
1266 Assert(!(cSectors % 8));
1267
1268 pbmAllocationBitmap = RTMemAllocZ(cSectors / 8);
1269 if (!pbmAllocationBitmap)
1270 return NULL;
1271
1272 while (uSectorCur < cSectors)
1273 {
1274 int idxSet = ASMBitFirstSet((uint8_t *)pvData + uSectorCur * 512, (uint32_t)cbData * 8);
1275
1276 if (idxSet != -1)
1277 {
1278 unsigned idxSectorAlloc = idxSet / 8 / 512;
1279 ASMBitSet(pbmAllocationBitmap, uSectorCur + idxSectorAlloc);
1280
1281 uSectorCur += idxSectorAlloc + 1;
1282 cbData -= (idxSectorAlloc + 1) * 512;
1283 }
1284 else
1285 break;
1286 }
1287
1288 return pbmAllocationBitmap;
1289}
1290
1291
1292/**
1293 * Updates the state of the async cluster allocation.
1294 *
1295 * @returns VBox status code.
1296 * @param pBackendData The opaque backend data.
1297 * @param pIoCtx I/O context associated with this request.
1298 * @param pvUser Opaque user data passed during a read/write request.
1299 * @param rcReq Status code for the completed request.
1300 */
1301static DECLCALLBACK(int) vdiBlockAllocUpdate(void *pBackendData, PVDIOCTX pIoCtx, void *pvUser, int rcReq)
1302{
1303 int rc = VINF_SUCCESS;
1304 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1305 PVDIASYNCBLOCKALLOC pBlockAlloc = (PVDIASYNCBLOCKALLOC)pvUser;
1306
1307 if (RT_SUCCESS(rcReq))
1308 {
1309 pImage->cbImage += pImage->cbTotalBlockData;
1310 pImage->paBlocks[pBlockAlloc->uBlock] = pBlockAlloc->cBlocksAllocated;
1311
1312 if (pImage->paBlocksRev)
1313 pImage->paBlocksRev[pBlockAlloc->cBlocksAllocated] = pBlockAlloc->uBlock;
1314
1315 setImageBlocksAllocated(&pImage->Header, pBlockAlloc->cBlocksAllocated + 1);
1316 rc = vdiUpdateBlockInfoAsync(pImage, pBlockAlloc->uBlock, pIoCtx,
1317 true /* fUpdateHdr */);
1318 }
1319 /* else: I/O error don't update the block table. */
1320
1321 RTMemFree(pBlockAlloc);
1322 return rc;
1323}
1324
1325/** @copydoc VDIMAGEBACKEND::pfnProbe */
1326static DECLCALLBACK(int) vdiProbe(const char *pszFilename, PVDINTERFACE pVDIfsDisk,
1327 PVDINTERFACE pVDIfsImage, VDTYPE *penmType)
1328{
1329 LogFlowFunc(("pszFilename=\"%s\"\n", pszFilename));
1330 int rc = VINF_SUCCESS;
1331
1332 AssertReturn((VALID_PTR(pszFilename) && *pszFilename), VERR_INVALID_PARAMETER);
1333
1334 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)RTMemAllocZ(sizeof(VDIIMAGEDESC));
1335 if (RT_LIKELY(pImage))
1336 {
1337 pImage->pszFilename = pszFilename;
1338 pImage->pStorage = NULL;
1339 pImage->paBlocks = NULL;
1340 pImage->pVDIfsDisk = pVDIfsDisk;
1341 pImage->pVDIfsImage = pVDIfsImage;
1342
1343 rc = vdiOpenImage(pImage, VD_OPEN_FLAGS_INFO | VD_OPEN_FLAGS_READONLY);
1344 vdiFreeImage(pImage, false);
1345 RTMemFree(pImage);
1346
1347 if (RT_SUCCESS(rc))
1348 *penmType = VDTYPE_HDD;
1349 }
1350 else
1351 rc = VERR_NO_MEMORY;
1352
1353 LogFlowFunc(("returns %Rrc\n", rc));
1354 return rc;
1355}
1356
1357/** @copydoc VDIMAGEBACKEND::pfnOpen */
1358static DECLCALLBACK(int) vdiOpen(const char *pszFilename, unsigned uOpenFlags,
1359 PVDINTERFACE pVDIfsDisk, PVDINTERFACE pVDIfsImage,
1360 VDTYPE enmType, void **ppBackendData)
1361{
1362 RT_NOREF1(enmType); /**< @todo r=klaus make use of the type info. */
1363
1364 LogFlowFunc(("pszFilename=\"%s\" uOpenFlags=%#x pVDIfsDisk=%#p pVDIfsImage=%#p enmType=%u ppBackendData=%#p\n",
1365 pszFilename, uOpenFlags, pVDIfsDisk, pVDIfsImage, enmType, ppBackendData));
1366 int rc;
1367
1368 /* Check open flags. All valid flags are supported. */
1369 AssertReturn(!(uOpenFlags & ~VD_OPEN_FLAGS_MASK), VERR_INVALID_PARAMETER);
1370 AssertReturn((VALID_PTR(pszFilename) && *pszFilename), VERR_INVALID_PARAMETER);
1371
1372 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)RTMemAllocZ(sizeof(VDIIMAGEDESC));
1373 if (RT_LIKELY(pImage))
1374 {
1375 pImage->pszFilename = pszFilename;
1376 pImage->pStorage = NULL;
1377 pImage->paBlocks = NULL;
1378 pImage->pVDIfsDisk = pVDIfsDisk;
1379 pImage->pVDIfsImage = pVDIfsImage;
1380
1381 rc = vdiOpenImage(pImage, uOpenFlags);
1382 if (RT_SUCCESS(rc))
1383 *ppBackendData = pImage;
1384 else
1385 RTMemFree(pImage);
1386 }
1387 else
1388 rc = VERR_NO_MEMORY;
1389
1390 LogFlowFunc(("returns %Rrc (pBackendData=%#p)\n", rc, *ppBackendData));
1391 return rc;
1392}
1393
1394/** @copydoc VDIMAGEBACKEND::pfnCreate */
1395static DECLCALLBACK(int) vdiCreate(const char *pszFilename, uint64_t cbSize,
1396 unsigned uImageFlags, const char *pszComment,
1397 PCVDGEOMETRY pPCHSGeometry, PCVDGEOMETRY pLCHSGeometry,
1398 PCRTUUID pUuid, unsigned uOpenFlags,
1399 unsigned uPercentStart, unsigned uPercentSpan,
1400 PVDINTERFACE pVDIfsDisk, PVDINTERFACE pVDIfsImage,
1401 PVDINTERFACE pVDIfsOperation, VDTYPE enmType,
1402 void **ppBackendData)
1403{
1404 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",
1405 pszFilename, cbSize, uImageFlags, pszComment, pPCHSGeometry, pLCHSGeometry, pUuid, uOpenFlags, uPercentStart, uPercentSpan, pVDIfsDisk, pVDIfsImage, pVDIfsOperation, enmType, ppBackendData));
1406 int rc;
1407
1408 /* Check the VD container type and image flags. */
1409 if ( enmType != VDTYPE_HDD
1410 || (uImageFlags & ~VD_VDI_IMAGE_FLAGS_MASK) != 0)
1411 return VERR_VD_INVALID_TYPE;
1412
1413 /* Check size. Maximum 4PB-3M. No tricks with adjusting the 1M block size
1414 * so far, which would extend the size. */
1415 if ( !cbSize
1416 || cbSize >= _1P * 4 - _1M * 3
1417 || cbSize < VDI_IMAGE_DEFAULT_BLOCK_SIZE)
1418 return VERR_VD_INVALID_SIZE;
1419
1420 /* Check open flags. All valid flags are supported. */
1421 AssertReturn(!(uOpenFlags & ~VD_OPEN_FLAGS_MASK), VERR_INVALID_PARAMETER);
1422 AssertReturn( VALID_PTR(pszFilename)
1423 && *pszFilename
1424 && VALID_PTR(pPCHSGeometry)
1425 && VALID_PTR(pLCHSGeometry), VERR_INVALID_PARAMETER);
1426
1427 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)RTMemAllocZ(sizeof(VDIIMAGEDESC));
1428 if (RT_LIKELY(pImage))
1429 {
1430 PVDINTERFACEPROGRESS pIfProgress = VDIfProgressGet(pVDIfsOperation);
1431 PVDINTERFACECONFIG pIfCfg = VDIfConfigGet(pVDIfsOperation);
1432
1433 pImage->pszFilename = pszFilename;
1434 pImage->pStorage = NULL;
1435 pImage->paBlocks = NULL;
1436 pImage->pVDIfsDisk = pVDIfsDisk;
1437 pImage->pVDIfsImage = pVDIfsImage;
1438
1439 rc = vdiCreateImage(pImage, cbSize, uImageFlags, pszComment,
1440 pPCHSGeometry, pLCHSGeometry, pUuid, uOpenFlags,
1441 pIfProgress, uPercentStart, uPercentSpan, pIfCfg);
1442 if (RT_SUCCESS(rc))
1443 {
1444 /* So far the image is opened in read/write mode. Make sure the
1445 * image is opened in read-only mode if the caller requested that. */
1446 if (uOpenFlags & VD_OPEN_FLAGS_READONLY)
1447 {
1448 vdiFreeImage(pImage, false);
1449 rc = vdiOpenImage(pImage, uOpenFlags);
1450 }
1451
1452 if (RT_SUCCESS(rc))
1453 *ppBackendData = pImage;
1454 }
1455
1456 if (RT_FAILURE(rc))
1457 RTMemFree(pImage);
1458 }
1459 else
1460 rc = VERR_NO_MEMORY;
1461
1462 LogFlowFunc(("returns %Rrc (pBackendData=%#p)\n", rc, *ppBackendData));
1463 return rc;
1464}
1465
1466/** @copydoc VDIMAGEBACKEND::pfnRename */
1467static DECLCALLBACK(int) vdiRename(void *pBackendData, const char *pszFilename)
1468{
1469 LogFlowFunc(("pBackendData=%#p pszFilename=%#p\n", pBackendData, pszFilename));
1470 int rc = VINF_SUCCESS;
1471 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1472
1473 /* Check arguments. */
1474 AssertReturn((pImage && pszFilename && *pszFilename), VERR_INVALID_PARAMETER);
1475
1476 /* Close the image. */
1477 rc = vdiFreeImage(pImage, false);
1478 if (RT_SUCCESS(rc))
1479 {
1480 /* Rename the file. */
1481 rc = vdIfIoIntFileMove(pImage->pIfIo, pImage->pszFilename, pszFilename, 0);
1482 if (RT_SUCCESS(rc))
1483 {
1484 /* Update pImage with the new information. */
1485 pImage->pszFilename = pszFilename;
1486
1487 /* Open the new image. */
1488 rc = vdiOpenImage(pImage, pImage->uOpenFlags);
1489 }
1490 else
1491 {
1492 /* The move failed, try to reopen the original image. */
1493 int rc2 = vdiOpenImage(pImage, pImage->uOpenFlags);
1494 if (RT_FAILURE(rc2))
1495 rc = rc2;
1496 }
1497 }
1498
1499 LogFlowFunc(("returns %Rrc\n", rc));
1500 return rc;
1501}
1502
1503/** @copydoc VDIMAGEBACKEND::pfnClose */
1504static DECLCALLBACK(int) vdiClose(void *pBackendData, bool fDelete)
1505{
1506 LogFlowFunc(("pBackendData=%#p fDelete=%d\n", pBackendData, fDelete));
1507 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1508
1509 int rc = vdiFreeImage(pImage, fDelete);
1510 RTMemFree(pImage);
1511
1512 LogFlowFunc(("returns %Rrc\n", rc));
1513 return rc;
1514}
1515
1516static DECLCALLBACK(int) vdiRead(void *pBackendData, uint64_t uOffset, size_t cbToRead,
1517 PVDIOCTX pIoCtx, size_t *pcbActuallyRead)
1518{
1519 LogFlowFunc(("pBackendData=%#p uOffset=%llu pIoCtx=%#p cbToRead=%zu pcbActuallyRead=%#p\n",
1520 pBackendData, uOffset, pIoCtx, cbToRead, pcbActuallyRead));
1521 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1522 unsigned uBlock;
1523 unsigned offRead;
1524 int rc = VINF_SUCCESS;
1525
1526 AssertPtr(pImage);
1527 Assert(!(uOffset % 512));
1528 Assert(!(cbToRead % 512));
1529 AssertReturn((VALID_PTR(pIoCtx) && cbToRead), VERR_INVALID_PARAMETER);
1530 AssertReturn(uOffset + cbToRead <= getImageDiskSize(&pImage->Header), VERR_INVALID_PARAMETER);
1531
1532 /* Calculate starting block number and offset inside it. */
1533 uBlock = (unsigned)(uOffset >> pImage->uShiftOffset2Index);
1534 offRead = (unsigned)uOffset & pImage->uBlockMask;
1535
1536 /* Clip read range to at most the rest of the block. */
1537 cbToRead = RT_MIN(cbToRead, getImageBlockSize(&pImage->Header) - offRead);
1538 Assert(!(cbToRead % 512));
1539
1540 if (pImage->paBlocks[uBlock] == VDI_IMAGE_BLOCK_FREE)
1541 rc = VERR_VD_BLOCK_FREE;
1542 else if (pImage->paBlocks[uBlock] == VDI_IMAGE_BLOCK_ZERO)
1543 {
1544 size_t cbSet;
1545
1546 cbSet = vdIfIoIntIoCtxSet(pImage->pIfIo, pIoCtx, 0, cbToRead);
1547 Assert(cbSet == cbToRead);
1548 }
1549 else
1550 {
1551 /* Block present in image file, read relevant data. */
1552 uint64_t u64Offset = (uint64_t)pImage->paBlocks[uBlock] * pImage->cbTotalBlockData
1553 + (pImage->offStartData + pImage->offStartBlockData + offRead);
1554
1555 if (u64Offset + cbToRead <= pImage->cbImage)
1556 rc = vdIfIoIntFileReadUser(pImage->pIfIo, pImage->pStorage, u64Offset,
1557 pIoCtx, cbToRead);
1558 else
1559 {
1560 LogRel(("VDI: Out of range access (%llu) in image %s, image size %llu\n",
1561 u64Offset, pImage->pszFilename, pImage->cbImage));
1562 vdIfIoIntIoCtxSet(pImage->pIfIo, pIoCtx, 0, cbToRead);
1563 rc = VERR_VD_READ_OUT_OF_RANGE;
1564 }
1565 }
1566
1567 if (pcbActuallyRead)
1568 *pcbActuallyRead = cbToRead;
1569
1570 LogFlowFunc(("returns %Rrc\n", rc));
1571 return rc;
1572}
1573
1574static DECLCALLBACK(int) vdiWrite(void *pBackendData, uint64_t uOffset, size_t cbToWrite,
1575 PVDIOCTX pIoCtx, size_t *pcbWriteProcess, size_t *pcbPreRead,
1576 size_t *pcbPostRead, unsigned fWrite)
1577{
1578 LogFlowFunc(("pBackendData=%#p uOffset=%llu pIoCtx=%#p cbToWrite=%zu pcbWriteProcess=%#p pcbPreRead=%#p pcbPostRead=%#p\n",
1579 pBackendData, uOffset, pIoCtx, cbToWrite, pcbWriteProcess, pcbPreRead, pcbPostRead));
1580 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1581 unsigned uBlock;
1582 unsigned offWrite;
1583 int rc = VINF_SUCCESS;
1584
1585 AssertPtr(pImage);
1586 Assert(!(uOffset % 512));
1587 Assert(!(cbToWrite % 512));
1588 AssertReturn((VALID_PTR(pIoCtx) && cbToWrite), VERR_INVALID_PARAMETER);
1589
1590 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
1591 {
1592 /* No size check here, will do that later. For dynamic images which are
1593 * not multiples of the block size in length, this would prevent writing to
1594 * the last block. */
1595
1596 /* Calculate starting block number and offset inside it. */
1597 uBlock = (unsigned)(uOffset >> pImage->uShiftOffset2Index);
1598 offWrite = (unsigned)uOffset & pImage->uBlockMask;
1599
1600 /* Clip write range to at most the rest of the block. */
1601 cbToWrite = RT_MIN(cbToWrite, getImageBlockSize(&pImage->Header) - offWrite);
1602 Assert(!(cbToWrite % 512));
1603
1604 do
1605 {
1606 if (!IS_VDI_IMAGE_BLOCK_ALLOCATED(pImage->paBlocks[uBlock]))
1607 {
1608 /* Block is either free or zero. */
1609 if ( !(pImage->uOpenFlags & VD_OPEN_FLAGS_HONOR_ZEROES)
1610 && ( pImage->paBlocks[uBlock] == VDI_IMAGE_BLOCK_ZERO
1611 || cbToWrite == getImageBlockSize(&pImage->Header)))
1612 {
1613 /* If the destination block is unallocated at this point, it's
1614 * either a zero block or a block which hasn't been used so far
1615 * (which also means that it's a zero block. Don't need to write
1616 * anything to this block if the data consists of just zeroes. */
1617 if (vdIfIoIntIoCtxIsZero(pImage->pIfIo, pIoCtx, cbToWrite, true))
1618 {
1619 pImage->paBlocks[uBlock] = VDI_IMAGE_BLOCK_ZERO;
1620 *pcbPreRead = 0;
1621 *pcbPostRead = 0;
1622 break;
1623 }
1624 }
1625
1626 if ( cbToWrite == getImageBlockSize(&pImage->Header)
1627 && !(fWrite & VD_WRITE_NO_ALLOC))
1628 {
1629 /* Full block write to previously unallocated block.
1630 * Allocate block and write data. */
1631 Assert(!offWrite);
1632 PVDIASYNCBLOCKALLOC pBlockAlloc = (PVDIASYNCBLOCKALLOC)RTMemAllocZ(sizeof(VDIASYNCBLOCKALLOC));
1633 if (!pBlockAlloc)
1634 {
1635 rc = VERR_NO_MEMORY;
1636 break;
1637 }
1638
1639 unsigned cBlocksAllocated = getImageBlocksAllocated(&pImage->Header);
1640 uint64_t u64Offset = (uint64_t)cBlocksAllocated * pImage->cbTotalBlockData
1641 + (pImage->offStartData + pImage->offStartBlockData);
1642
1643 pBlockAlloc->cBlocksAllocated = cBlocksAllocated;
1644 pBlockAlloc->uBlock = uBlock;
1645
1646 *pcbPreRead = 0;
1647 *pcbPostRead = 0;
1648
1649 rc = vdIfIoIntFileWriteUser(pImage->pIfIo, pImage->pStorage,
1650 u64Offset, pIoCtx, cbToWrite,
1651 vdiBlockAllocUpdate, pBlockAlloc);
1652 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
1653 break;
1654 else if (RT_FAILURE(rc))
1655 {
1656 RTMemFree(pBlockAlloc);
1657 break;
1658 }
1659
1660 rc = vdiBlockAllocUpdate(pImage, pIoCtx, pBlockAlloc, rc);
1661 }
1662 else
1663 {
1664 /* Trying to do a partial write to an unallocated block. Don't do
1665 * anything except letting the upper layer know what to do. */
1666 *pcbPreRead = offWrite % getImageBlockSize(&pImage->Header);
1667 *pcbPostRead = getImageBlockSize(&pImage->Header) - cbToWrite - *pcbPreRead;
1668 rc = VERR_VD_BLOCK_FREE;
1669 }
1670 }
1671 else
1672 {
1673 /* Block present in image file, write relevant data. */
1674 uint64_t u64Offset = (uint64_t)pImage->paBlocks[uBlock] * pImage->cbTotalBlockData
1675 + (pImage->offStartData + pImage->offStartBlockData + offWrite);
1676 rc = vdIfIoIntFileWriteUser(pImage->pIfIo, pImage->pStorage,
1677 u64Offset, pIoCtx, cbToWrite, NULL, NULL);
1678 }
1679 } while (0);
1680
1681 if (pcbWriteProcess)
1682 *pcbWriteProcess = cbToWrite;
1683 }
1684 else
1685 rc = VERR_VD_IMAGE_READ_ONLY;
1686
1687 LogFlowFunc(("returns %Rrc\n", rc));
1688 return rc;
1689}
1690
1691static DECLCALLBACK(int) vdiFlush(void *pBackendData, PVDIOCTX pIoCtx)
1692{
1693 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
1694 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1695 int rc = VINF_SUCCESS;
1696
1697 Assert(pImage);
1698
1699 rc = vdiFlushImageIoCtx(pImage, pIoCtx);
1700 LogFlowFunc(("returns %Rrc\n", rc));
1701 return rc;
1702}
1703
1704/** @copydoc VDIMAGEBACKEND::pfnGetVersion */
1705static DECLCALLBACK(unsigned) vdiGetVersion(void *pBackendData)
1706{
1707 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
1708 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1709
1710 AssertPtrReturn(pImage, 0);
1711
1712 LogFlowFunc(("returns %#x\n", pImage->PreHeader.u32Version));
1713 return pImage->PreHeader.u32Version;
1714}
1715
1716/** @copydoc VDIMAGEBACKEND::pfnGetSectorSize */
1717static DECLCALLBACK(uint32_t) vdiGetSectorSize(void *pBackendData)
1718{
1719 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
1720 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1721 uint64_t cbSector = 0;
1722
1723 AssertPtrReturn(pImage, 0);
1724
1725 if (pImage->pStorage)
1726 cbSector = 512;
1727
1728 LogFlowFunc(("returns %zu\n", cbSector));
1729 return cbSector;
1730}
1731
1732/** @copydoc VDIMAGEBACKEND::pfnGetSize */
1733static DECLCALLBACK(uint64_t) vdiGetSize(void *pBackendData)
1734{
1735 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
1736 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1737
1738 AssertPtrReturn(pImage, 0);
1739
1740 LogFlowFunc(("returns %llu\n", getImageDiskSize(&pImage->Header)));
1741 return getImageDiskSize(&pImage->Header);
1742}
1743
1744/** @copydoc VDIMAGEBACKEND::pfnGetFileSize */
1745static DECLCALLBACK(uint64_t) vdiGetFileSize(void *pBackendData)
1746{
1747 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
1748 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1749 uint64_t cb = 0;
1750
1751 AssertPtrReturn(pImage, 0);
1752
1753 if (pImage->pStorage)
1754 {
1755 uint64_t cbFile;
1756 int rc = vdIfIoIntFileGetSize(pImage->pIfIo, pImage->pStorage, &cbFile);
1757 if (RT_SUCCESS(rc))
1758 cb += cbFile;
1759 }
1760
1761 LogFlowFunc(("returns %lld\n", cb));
1762 return cb;
1763}
1764
1765/** @copydoc VDIMAGEBACKEND::pfnGetPCHSGeometry */
1766static DECLCALLBACK(int) vdiGetPCHSGeometry(void *pBackendData, PVDGEOMETRY pPCHSGeometry)
1767{
1768 LogFlowFunc(("pBackendData=%#p pPCHSGeometry=%#p\n", pBackendData, pPCHSGeometry));
1769 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1770 int rc = VINF_SUCCESS;
1771
1772 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
1773
1774 if (pImage->PCHSGeometry.cCylinders)
1775 *pPCHSGeometry = pImage->PCHSGeometry;
1776 else
1777 rc = VERR_VD_GEOMETRY_NOT_SET;
1778
1779 LogFlowFunc(("returns %Rrc (PCHS=%u/%u/%u)\n", rc, pPCHSGeometry->cCylinders, pPCHSGeometry->cHeads, pPCHSGeometry->cSectors));
1780 return rc;
1781}
1782
1783/** @copydoc VDIMAGEBACKEND::pfnSetPCHSGeometry */
1784static DECLCALLBACK(int) vdiSetPCHSGeometry(void *pBackendData, PCVDGEOMETRY pPCHSGeometry)
1785{
1786 LogFlowFunc(("pBackendData=%#p pPCHSGeometry=%#p PCHS=%u/%u/%u\n",
1787 pBackendData, pPCHSGeometry, pPCHSGeometry->cCylinders, pPCHSGeometry->cHeads, pPCHSGeometry->cSectors));
1788 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1789 int rc = VINF_SUCCESS;
1790
1791 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
1792
1793 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
1794 rc = VERR_VD_IMAGE_READ_ONLY;
1795 else
1796 pImage->PCHSGeometry = *pPCHSGeometry;
1797
1798 LogFlowFunc(("returns %Rrc\n", rc));
1799 return rc;
1800}
1801
1802/** @copydoc VDIMAGEBACKEND::pfnGetLCHSGeometry */
1803static DECLCALLBACK(int) vdiGetLCHSGeometry(void *pBackendData, PVDGEOMETRY pLCHSGeometry)
1804{
1805 LogFlowFunc(("pBackendData=%#p pLCHSGeometry=%#p\n", pBackendData, pLCHSGeometry));
1806 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1807
1808 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
1809
1810 int rc = VINF_SUCCESS;
1811 VDIDISKGEOMETRY DummyGeo = { 0, 0, 0, VDI_GEOMETRY_SECTOR_SIZE };
1812 PVDIDISKGEOMETRY pGeometry = getImageLCHSGeometry(&pImage->Header);
1813 if (!pGeometry)
1814 pGeometry = &DummyGeo;
1815
1816 if ( pGeometry->cCylinders > 0
1817 && pGeometry->cHeads > 0
1818 && pGeometry->cSectors > 0)
1819 {
1820 pLCHSGeometry->cCylinders = pGeometry->cCylinders;
1821 pLCHSGeometry->cHeads = pGeometry->cHeads;
1822 pLCHSGeometry->cSectors = pGeometry->cSectors;
1823 }
1824 else
1825 rc = VERR_VD_GEOMETRY_NOT_SET;
1826
1827 LogFlowFunc(("returns %Rrc (LCHS=%u/%u/%u)\n", rc, pLCHSGeometry->cCylinders, pLCHSGeometry->cHeads, pLCHSGeometry->cSectors));
1828 return rc;
1829}
1830
1831/** @copydoc VDIMAGEBACKEND::pfnSetLCHSGeometry */
1832static DECLCALLBACK(int) vdiSetLCHSGeometry(void *pBackendData, PCVDGEOMETRY pLCHSGeometry)
1833{
1834 LogFlowFunc(("pBackendData=%#p pLCHSGeometry=%#p LCHS=%u/%u/%u\n",
1835 pBackendData, pLCHSGeometry, pLCHSGeometry->cCylinders, pLCHSGeometry->cHeads, pLCHSGeometry->cSectors));
1836 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1837 PVDIDISKGEOMETRY pGeometry;
1838 int rc = VINF_SUCCESS;
1839
1840 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
1841
1842 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
1843 {
1844 pGeometry = getImageLCHSGeometry(&pImage->Header);
1845 if (pGeometry)
1846 {
1847 pGeometry->cCylinders = pLCHSGeometry->cCylinders;
1848 pGeometry->cHeads = pLCHSGeometry->cHeads;
1849 pGeometry->cSectors = pLCHSGeometry->cSectors;
1850 pGeometry->cbSector = VDI_GEOMETRY_SECTOR_SIZE;
1851
1852 /* Update header information in base image file. */
1853 vdiFlushImage(pImage);
1854 }
1855 }
1856 else
1857 rc = VERR_VD_IMAGE_READ_ONLY;
1858
1859 LogFlowFunc(("returns %Rrc\n", rc));
1860 return rc;
1861}
1862
1863/** @copydoc VDIMAGEBACKEND::pfnGetImageFlags */
1864static DECLCALLBACK(unsigned) vdiGetImageFlags(void *pBackendData)
1865{
1866 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
1867 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1868
1869 AssertPtrReturn(pImage, 0);
1870
1871 LogFlowFunc(("returns %#x\n", pImage->uImageFlags));
1872 return pImage->uImageFlags;
1873}
1874
1875/** @copydoc VDIMAGEBACKEND::pfnGetOpenFlags */
1876static DECLCALLBACK(unsigned) vdiGetOpenFlags(void *pBackendData)
1877{
1878 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
1879 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1880
1881 AssertPtrReturn(pImage, 0);
1882
1883 LogFlowFunc(("returns %#x\n", pImage->uOpenFlags));
1884 return pImage->uOpenFlags;
1885}
1886
1887/** @copydoc VDIMAGEBACKEND::pfnSetOpenFlags */
1888static DECLCALLBACK(int) vdiSetOpenFlags(void *pBackendData, unsigned uOpenFlags)
1889{
1890 LogFlowFunc(("pBackendData=%#p uOpenFlags=%#x\n", pBackendData, uOpenFlags));
1891 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1892 int rc;
1893 const char *pszFilename;
1894
1895 /* Image must be opened and the new flags must be valid. */
1896 if (!pImage || (uOpenFlags & ~( VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_INFO
1897 | VD_OPEN_FLAGS_ASYNC_IO | VD_OPEN_FLAGS_SHAREABLE
1898 | VD_OPEN_FLAGS_SEQUENTIAL | VD_OPEN_FLAGS_DISCARD
1899 | VD_OPEN_FLAGS_SKIP_CONSISTENCY_CHECKS)))
1900 rc = VERR_INVALID_PARAMETER;
1901 else
1902 {
1903 /* Implement this operation via reopening the image. */
1904 pszFilename = pImage->pszFilename;
1905 rc = vdiFreeImage(pImage, false);
1906 if (RT_SUCCESS(rc))
1907 rc = vdiOpenImage(pImage, uOpenFlags);
1908 }
1909
1910 LogFlowFunc(("returns %Rrc\n", rc));
1911 return rc;
1912}
1913
1914/** @copydoc VDIMAGEBACKEND::pfnGetComment */
1915static DECLCALLBACK(int) vdiGetComment(void *pBackendData, char *pszComment,
1916 size_t cbComment)
1917{
1918 LogFlowFunc(("pBackendData=%#p pszComment=%#p cbComment=%zu\n", pBackendData, pszComment, cbComment));
1919 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1920
1921 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
1922
1923 int rc = VINF_SUCCESS;
1924 char *pszTmp = getImageComment(&pImage->Header);
1925 /* Make this foolproof even if the image doesn't have the zero
1926 * termination. With some luck the repaired header will be saved. */
1927 size_t cb = RTStrNLen(pszTmp, VDI_IMAGE_COMMENT_SIZE);
1928 if (cb == VDI_IMAGE_COMMENT_SIZE)
1929 {
1930 pszTmp[VDI_IMAGE_COMMENT_SIZE-1] = '\0';
1931 cb--;
1932 }
1933 if (cb < cbComment)
1934 {
1935 /* memcpy is much better than strncpy. */
1936 memcpy(pszComment, pszTmp, cb + 1);
1937 }
1938 else
1939 rc = VERR_BUFFER_OVERFLOW;
1940
1941 LogFlowFunc(("returns %Rrc comment=\"%s\"\n", rc, pszComment));
1942 return rc;
1943}
1944
1945/** @copydoc VDIMAGEBACKEND::pfnSetComment */
1946static DECLCALLBACK(int) vdiSetComment(void *pBackendData, const char *pszComment)
1947{
1948 LogFlowFunc(("pBackendData=%#p pszComment=\"%s\"\n", pBackendData, pszComment));
1949 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1950 int rc;
1951
1952 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
1953
1954 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
1955 {
1956 size_t cchComment = pszComment ? strlen(pszComment) : 0;
1957 if (cchComment < VDI_IMAGE_COMMENT_SIZE)
1958 {
1959 /* we don't support old style images */
1960 if (GET_MAJOR_HEADER_VERSION(&pImage->Header) == 1)
1961 {
1962 /*
1963 * Update the comment field, making sure to zero out all of the previous comment.
1964 */
1965 memset(pImage->Header.u.v1.szComment, '\0', VDI_IMAGE_COMMENT_SIZE);
1966 memcpy(pImage->Header.u.v1.szComment, pszComment, cchComment);
1967
1968 /* write out new the header */
1969 rc = vdiUpdateHeader(pImage);
1970 }
1971 else
1972 rc = VERR_VD_VDI_UNSUPPORTED_VERSION;
1973 }
1974 else
1975 {
1976 LogFunc(("pszComment is too long, %d bytes!\n", cchComment));
1977 rc = VERR_VD_VDI_COMMENT_TOO_LONG;
1978 }
1979 }
1980 else
1981 rc = VERR_VD_IMAGE_READ_ONLY;
1982
1983 LogFlowFunc(("returns %Rrc\n", rc));
1984 return rc;
1985}
1986
1987/** @copydoc VDIMAGEBACKEND::pfnGetUuid */
1988static DECLCALLBACK(int) vdiGetUuid(void *pBackendData, PRTUUID pUuid)
1989{
1990 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
1991 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1992
1993 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
1994
1995 *pUuid = *getImageCreationUUID(&pImage->Header);
1996
1997 LogFlowFunc(("returns %Rrc (%RTuuid)\n", VINF_SUCCESS, pUuid));
1998 return VINF_SUCCESS;
1999}
2000
2001/** @copydoc VDIMAGEBACKEND::pfnSetUuid */
2002static DECLCALLBACK(int) vdiSetUuid(void *pBackendData, PCRTUUID pUuid)
2003{
2004 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
2005 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
2006
2007 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
2008
2009 int rc = VINF_SUCCESS;
2010 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
2011 {
2012 if (GET_MAJOR_HEADER_VERSION(&pImage->Header) == 1)
2013 pImage->Header.u.v1.uuidCreate = *pUuid;
2014 /* Make it possible to clone old VDIs. */
2015 else if (GET_MAJOR_HEADER_VERSION(&pImage->Header) == 0)
2016 pImage->Header.u.v0.uuidCreate = *pUuid;
2017 else
2018 {
2019 LogFunc(("Version is not supported!\n"));
2020 rc = VERR_VD_VDI_UNSUPPORTED_VERSION;
2021 }
2022 }
2023 else
2024 rc = VERR_VD_IMAGE_READ_ONLY;
2025
2026 LogFlowFunc(("returns %Rrc\n", rc));
2027 return rc;
2028}
2029
2030/** @copydoc VDIMAGEBACKEND::pfnGetModificationUuid */
2031static DECLCALLBACK(int) vdiGetModificationUuid(void *pBackendData, PRTUUID pUuid)
2032{
2033 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
2034 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
2035
2036 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
2037
2038 *pUuid = *getImageModificationUUID(&pImage->Header);
2039
2040 LogFlowFunc(("returns %Rrc (%RTuuid)\n", VINF_SUCCESS, pUuid));
2041 return VINF_SUCCESS;
2042}
2043
2044/** @copydoc VDIMAGEBACKEND::pfnSetModificationUuid */
2045static DECLCALLBACK(int) vdiSetModificationUuid(void *pBackendData, PCRTUUID pUuid)
2046{
2047 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
2048 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
2049
2050 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
2051
2052 int rc = VINF_SUCCESS;
2053 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
2054 {
2055 if (GET_MAJOR_HEADER_VERSION(&pImage->Header) == 1)
2056 pImage->Header.u.v1.uuidModify = *pUuid;
2057 /* Make it possible to clone old VDIs. */
2058 else if (GET_MAJOR_HEADER_VERSION(&pImage->Header) == 0)
2059 pImage->Header.u.v0.uuidModify = *pUuid;
2060 else
2061 {
2062 LogFunc(("Version is not supported!\n"));
2063 rc = VERR_VD_VDI_UNSUPPORTED_VERSION;
2064 }
2065 }
2066 else
2067 rc = VERR_VD_IMAGE_READ_ONLY;
2068
2069 LogFlowFunc(("returns %Rrc\n", rc));
2070 return rc;
2071}
2072
2073/** @copydoc VDIMAGEBACKEND::pfnGetParentUuid */
2074static DECLCALLBACK(int) vdiGetParentUuid(void *pBackendData, PRTUUID pUuid)
2075{
2076 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
2077 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
2078
2079 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
2080
2081 *pUuid = *getImageParentUUID(&pImage->Header);
2082
2083 LogFlowFunc(("returns %Rrc (%RTuuid)\n", VINF_SUCCESS, pUuid));
2084 return VINF_SUCCESS;
2085}
2086
2087/** @copydoc VDIMAGEBACKEND::pfnSetParentUuid */
2088static DECLCALLBACK(int) vdiSetParentUuid(void *pBackendData, PCRTUUID pUuid)
2089{
2090 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
2091 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
2092
2093 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
2094
2095 int rc = VINF_SUCCESS;
2096 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
2097 {
2098 if (GET_MAJOR_HEADER_VERSION(&pImage->Header) == 1)
2099 pImage->Header.u.v1.uuidLinkage = *pUuid;
2100 /* Make it possible to clone old VDIs. */
2101 else if (GET_MAJOR_HEADER_VERSION(&pImage->Header) == 0)
2102 pImage->Header.u.v0.uuidLinkage = *pUuid;
2103 else
2104 {
2105 LogFunc(("Version is not supported!\n"));
2106 rc = VERR_VD_VDI_UNSUPPORTED_VERSION;
2107 }
2108 }
2109 else
2110 rc = VERR_VD_IMAGE_READ_ONLY;
2111
2112 LogFlowFunc(("returns %Rrc\n", rc));
2113 return rc;
2114}
2115
2116/** @copydoc VDIMAGEBACKEND::pfnGetParentModificationUuid */
2117static DECLCALLBACK(int) vdiGetParentModificationUuid(void *pBackendData, PRTUUID pUuid)
2118{
2119 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
2120 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
2121
2122 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
2123
2124 *pUuid = *getImageParentModificationUUID(&pImage->Header);
2125
2126 LogFlowFunc(("returns %Rrc (%RTuuid)\n", VINF_SUCCESS, pUuid));
2127 return VINF_SUCCESS;
2128}
2129
2130/** @copydoc VDIMAGEBACKEND::pfnSetParentModificationUuid */
2131static DECLCALLBACK(int) vdiSetParentModificationUuid(void *pBackendData, PCRTUUID pUuid)
2132{
2133 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
2134 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
2135
2136 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
2137
2138 int rc = VINF_SUCCESS;
2139 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
2140 {
2141 if (GET_MAJOR_HEADER_VERSION(&pImage->Header) == 1)
2142 pImage->Header.u.v1.uuidParentModify = *pUuid;
2143 else
2144 {
2145 LogFunc(("Version is not supported!\n"));
2146 rc = VERR_VD_VDI_UNSUPPORTED_VERSION;
2147 }
2148 }
2149 else
2150 rc = VERR_VD_IMAGE_READ_ONLY;
2151
2152 LogFlowFunc(("returns %Rrc\n", rc));
2153 return rc;
2154}
2155
2156/** @copydoc VDIMAGEBACKEND::pfnDump */
2157static DECLCALLBACK(void) vdiDump(void *pBackendData)
2158{
2159 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
2160
2161 AssertPtrReturnVoid(pImage);
2162 vdIfErrorMessage(pImage->pIfError, "Dumping VDI image \"%s\" mode=%s uOpenFlags=%X File=%#p\n",
2163 pImage->pszFilename,
2164 (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY) ? "r/o" : "r/w",
2165 pImage->uOpenFlags,
2166 pImage->pStorage);
2167 vdIfErrorMessage(pImage->pIfError, "Header: Version=%08X Type=%X Flags=%X Size=%llu\n",
2168 pImage->PreHeader.u32Version,
2169 getImageType(&pImage->Header),
2170 getImageFlags(&pImage->Header),
2171 getImageDiskSize(&pImage->Header));
2172 vdIfErrorMessage(pImage->pIfError, "Header: cbBlock=%u cbBlockExtra=%u cBlocks=%u cBlocksAllocated=%u\n",
2173 getImageBlockSize(&pImage->Header),
2174 getImageExtraBlockSize(&pImage->Header),
2175 getImageBlocks(&pImage->Header),
2176 getImageBlocksAllocated(&pImage->Header));
2177 vdIfErrorMessage(pImage->pIfError, "Header: offBlocks=%u offData=%u\n",
2178 getImageBlocksOffset(&pImage->Header),
2179 getImageDataOffset(&pImage->Header));
2180 PVDIDISKGEOMETRY pg = getImageLCHSGeometry(&pImage->Header);
2181 if (pg)
2182 vdIfErrorMessage(pImage->pIfError, "Header: Geometry: C/H/S=%u/%u/%u cbSector=%u\n",
2183 pg->cCylinders, pg->cHeads, pg->cSectors, pg->cbSector);
2184 vdIfErrorMessage(pImage->pIfError, "Header: uuidCreation={%RTuuid}\n", getImageCreationUUID(&pImage->Header));
2185 vdIfErrorMessage(pImage->pIfError, "Header: uuidModification={%RTuuid}\n", getImageModificationUUID(&pImage->Header));
2186 vdIfErrorMessage(pImage->pIfError, "Header: uuidParent={%RTuuid}\n", getImageParentUUID(&pImage->Header));
2187 if (GET_MAJOR_HEADER_VERSION(&pImage->Header) >= 1)
2188 vdIfErrorMessage(pImage->pIfError, "Header: uuidParentModification={%RTuuid}\n", getImageParentModificationUUID(&pImage->Header));
2189 vdIfErrorMessage(pImage->pIfError, "Image: fFlags=%08X offStartBlocks=%u offStartData=%u\n",
2190 pImage->uImageFlags, pImage->offStartBlocks, pImage->offStartData);
2191 vdIfErrorMessage(pImage->pIfError, "Image: uBlockMask=%08X cbTotalBlockData=%u uShiftOffset2Index=%u offStartBlockData=%u\n",
2192 pImage->uBlockMask,
2193 pImage->cbTotalBlockData,
2194 pImage->uShiftOffset2Index,
2195 pImage->offStartBlockData);
2196
2197 unsigned uBlock, cBlocksNotFree, cBadBlocks, cBlocks = getImageBlocks(&pImage->Header);
2198 for (uBlock=0, cBlocksNotFree=0, cBadBlocks=0; uBlock<cBlocks; uBlock++)
2199 {
2200 if (IS_VDI_IMAGE_BLOCK_ALLOCATED(pImage->paBlocks[uBlock]))
2201 {
2202 cBlocksNotFree++;
2203 if (pImage->paBlocks[uBlock] >= cBlocks)
2204 cBadBlocks++;
2205 }
2206 }
2207 if (cBlocksNotFree != getImageBlocksAllocated(&pImage->Header))
2208 {
2209 vdIfErrorMessage(pImage->pIfError, "!! WARNING: %u blocks actually allocated (cBlocksAllocated=%u) !!\n",
2210 cBlocksNotFree, getImageBlocksAllocated(&pImage->Header));
2211 }
2212 if (cBadBlocks)
2213 {
2214 vdIfErrorMessage(pImage->pIfError, "!! WARNING: %u bad blocks found !!\n",
2215 cBadBlocks);
2216 }
2217}
2218
2219/** @copydoc VDIMAGEBACKEND::pfnCompact */
2220static DECLCALLBACK(int) vdiCompact(void *pBackendData, unsigned uPercentStart,
2221 unsigned uPercentSpan, PVDINTERFACE pVDIfsDisk,
2222 PVDINTERFACE pVDIfsImage, PVDINTERFACE pVDIfsOperation)
2223{
2224 RT_NOREF2(pVDIfsDisk, pVDIfsImage);
2225 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
2226 int rc = VINF_SUCCESS;
2227 void *pvBuf = NULL, *pvTmp = NULL;
2228 unsigned *paBlocks2 = NULL;
2229
2230 DECLCALLBACKMEMBER(int, pfnParentRead)(void *, uint64_t, void *, size_t) = NULL;
2231 void *pvParent = NULL;
2232 PVDINTERFACEPARENTSTATE pIfParentState = VDIfParentStateGet(pVDIfsOperation);
2233 if (pIfParentState)
2234 {
2235 pfnParentRead = pIfParentState->pfnParentRead;
2236 pvParent = pIfParentState->Core.pvUser;
2237 }
2238
2239 PVDINTERFACEPROGRESS pIfProgress = VDIfProgressGet(pVDIfsOperation);
2240 PVDINTERFACEQUERYRANGEUSE pIfQueryRangeUse = VDIfQueryRangeUseGet(pVDIfsOperation);
2241
2242 do
2243 {
2244 AssertBreakStmt(pImage, rc = VERR_INVALID_PARAMETER);
2245
2246 AssertBreakStmt(!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY),
2247 rc = VERR_VD_IMAGE_READ_ONLY);
2248
2249 unsigned cBlocks;
2250 unsigned cBlocksToMove = 0;
2251 size_t cbBlock;
2252 cBlocks = getImageBlocks(&pImage->Header);
2253 cbBlock = getImageBlockSize(&pImage->Header);
2254 if (pfnParentRead)
2255 {
2256 pvBuf = RTMemTmpAlloc(cbBlock);
2257 AssertBreakStmt(pvBuf, rc = VERR_NO_MEMORY);
2258 }
2259 pvTmp = RTMemTmpAlloc(cbBlock);
2260 AssertBreakStmt(pvTmp, rc = VERR_NO_MEMORY);
2261
2262 uint64_t cbFile;
2263 rc = vdIfIoIntFileGetSize(pImage->pIfIo, pImage->pStorage, &cbFile);
2264 AssertRCBreak(rc);
2265 unsigned cBlocksAllocated = (unsigned)((cbFile - pImage->offStartData - pImage->offStartBlockData) >> pImage->uShiftOffset2Index);
2266 if (cBlocksAllocated == 0)
2267 {
2268 /* No data blocks in this image, no need to compact. */
2269 rc = VINF_SUCCESS;
2270 break;
2271 }
2272
2273 /* Allocate block array for back resolving. */
2274 paBlocks2 = (unsigned *)RTMemAlloc(sizeof(unsigned *) * cBlocksAllocated);
2275 AssertBreakStmt(paBlocks2, rc = VERR_NO_MEMORY);
2276 /* Fill out back resolving, check/fix allocation errors before
2277 * compacting the image, just to be on the safe side. Update the
2278 * image contents straight away, as this enables cancelling. */
2279 for (unsigned i = 0; i < cBlocksAllocated; i++)
2280 paBlocks2[i] = VDI_IMAGE_BLOCK_FREE;
2281 rc = VINF_SUCCESS;
2282 for (unsigned i = 0; i < cBlocks; i++)
2283 {
2284 VDIIMAGEBLOCKPOINTER ptrBlock = pImage->paBlocks[i];
2285 if (IS_VDI_IMAGE_BLOCK_ALLOCATED(ptrBlock))
2286 {
2287 if (ptrBlock < cBlocksAllocated)
2288 {
2289 if (paBlocks2[ptrBlock] == VDI_IMAGE_BLOCK_FREE)
2290 paBlocks2[ptrBlock] = i;
2291 else
2292 {
2293 LogFunc(("Freed cross-linked block %u in file \"%s\"\n",
2294 i, pImage->pszFilename));
2295 pImage->paBlocks[i] = VDI_IMAGE_BLOCK_FREE;
2296 rc = vdiUpdateBlockInfo(pImage, i);
2297 if (RT_FAILURE(rc))
2298 break;
2299 }
2300 }
2301 else
2302 {
2303 LogFunc(("Freed out of bounds reference for block %u in file \"%s\"\n",
2304 i, pImage->pszFilename));
2305 pImage->paBlocks[i] = VDI_IMAGE_BLOCK_FREE;
2306 rc = vdiUpdateBlockInfo(pImage, i);
2307 if (RT_FAILURE(rc))
2308 break;
2309 }
2310 }
2311 }
2312 if (RT_FAILURE(rc))
2313 break;
2314
2315 /* Find redundant information and update the block pointers
2316 * accordingly, creating bubbles. Keep disk up to date, as this
2317 * enables cancelling. */
2318 for (unsigned i = 0; i < cBlocks; i++)
2319 {
2320 VDIIMAGEBLOCKPOINTER ptrBlock = pImage->paBlocks[i];
2321 if (IS_VDI_IMAGE_BLOCK_ALLOCATED(ptrBlock))
2322 {
2323 /* Block present in image file, read relevant data. */
2324 uint64_t u64Offset = (uint64_t)ptrBlock * pImage->cbTotalBlockData
2325 + (pImage->offStartData + pImage->offStartBlockData);
2326 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pImage->pStorage, u64Offset, pvTmp, cbBlock);
2327 if (RT_FAILURE(rc))
2328 break;
2329
2330 if (ASMBitFirstSet((volatile void *)pvTmp, (uint32_t)cbBlock * 8) == -1)
2331 {
2332 pImage->paBlocks[i] = VDI_IMAGE_BLOCK_ZERO;
2333 rc = vdiUpdateBlockInfo(pImage, i);
2334 if (RT_FAILURE(rc))
2335 break;
2336 paBlocks2[ptrBlock] = VDI_IMAGE_BLOCK_FREE;
2337 /* Adjust progress info, one block to be relocated. */
2338 cBlocksToMove++;
2339 }
2340 else if (pfnParentRead)
2341 {
2342 rc = pfnParentRead(pvParent, (uint64_t)i * cbBlock, pvBuf, cbBlock);
2343 if (RT_FAILURE(rc))
2344 break;
2345 if (!memcmp(pvTmp, pvBuf, cbBlock))
2346 {
2347 pImage->paBlocks[i] = VDI_IMAGE_BLOCK_FREE;
2348 rc = vdiUpdateBlockInfo(pImage, i);
2349 if (RT_FAILURE(rc))
2350 break;
2351 paBlocks2[ptrBlock] = VDI_IMAGE_BLOCK_FREE;
2352 /* Adjust progress info, one block to be relocated. */
2353 cBlocksToMove++;
2354 }
2355 }
2356 }
2357
2358 /* Check if the range is in use if the block is still allocated. */
2359 ptrBlock = pImage->paBlocks[i];
2360 if ( IS_VDI_IMAGE_BLOCK_ALLOCATED(ptrBlock)
2361 && pIfQueryRangeUse)
2362 {
2363 bool fUsed = true;
2364
2365 rc = vdIfQueryRangeUse(pIfQueryRangeUse, (uint64_t)i * cbBlock, cbBlock, &fUsed);
2366 if (RT_FAILURE(rc))
2367 break;
2368 if (!fUsed)
2369 {
2370 pImage->paBlocks[i] = VDI_IMAGE_BLOCK_ZERO;
2371 rc = vdiUpdateBlockInfo(pImage, i);
2372 if (RT_FAILURE(rc))
2373 break;
2374 paBlocks2[ptrBlock] = VDI_IMAGE_BLOCK_FREE;
2375 /* Adjust progress info, one block to be relocated. */
2376 cBlocksToMove++;
2377 }
2378 }
2379
2380 vdIfProgress(pIfProgress, (uint64_t)i * uPercentSpan / (cBlocks + cBlocksToMove) + uPercentStart);
2381 if (RT_FAILURE(rc))
2382 break;
2383 }
2384 if (RT_FAILURE(rc))
2385 break;
2386
2387 /* Fill bubbles with other data (if available). */
2388 unsigned cBlocksMoved = 0;
2389 unsigned uBlockUsedPos = cBlocksAllocated;
2390 for (unsigned i = 0; i < cBlocksAllocated; i++)
2391 {
2392 unsigned uBlock = paBlocks2[i];
2393 if (uBlock == VDI_IMAGE_BLOCK_FREE)
2394 {
2395 unsigned uBlockData = VDI_IMAGE_BLOCK_FREE;
2396 while (uBlockUsedPos > i && uBlockData == VDI_IMAGE_BLOCK_FREE)
2397 {
2398 uBlockUsedPos--;
2399 uBlockData = paBlocks2[uBlockUsedPos];
2400 }
2401 /* Terminate early if there is no block which needs copying. */
2402 if (uBlockUsedPos == i)
2403 break;
2404 uint64_t u64Offset = (uint64_t)uBlockUsedPos * pImage->cbTotalBlockData
2405 + (pImage->offStartData + pImage->offStartBlockData);
2406 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pImage->pStorage, u64Offset,
2407 pvTmp, cbBlock);
2408 u64Offset = (uint64_t)i * pImage->cbTotalBlockData
2409 + (pImage->offStartData + pImage->offStartBlockData);
2410 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pImage->pStorage, u64Offset,
2411 pvTmp, cbBlock);
2412 pImage->paBlocks[uBlockData] = i;
2413 setImageBlocksAllocated(&pImage->Header, cBlocksAllocated - cBlocksMoved);
2414 rc = vdiUpdateBlockInfo(pImage, uBlockData);
2415 if (RT_FAILURE(rc))
2416 break;
2417 paBlocks2[i] = uBlockData;
2418 paBlocks2[uBlockUsedPos] = VDI_IMAGE_BLOCK_FREE;
2419 cBlocksMoved++;
2420 }
2421
2422 rc = vdIfProgress(pIfProgress, (uint64_t)(cBlocks + cBlocksMoved) * uPercentSpan / (cBlocks + cBlocksToMove) + uPercentStart);
2423 if (RT_FAILURE(rc))
2424 break;
2425 }
2426 if (RT_FAILURE(rc))
2427 break;
2428
2429 /* Update image header. */
2430 setImageBlocksAllocated(&pImage->Header, uBlockUsedPos);
2431 vdiUpdateHeader(pImage);
2432
2433 /* Truncate the image to the proper size to finish compacting. */
2434 rc = vdIfIoIntFileSetSize(pImage->pIfIo, pImage->pStorage,
2435 (uint64_t)uBlockUsedPos * pImage->cbTotalBlockData
2436 + pImage->offStartData + pImage->offStartBlockData);
2437 } while (0);
2438
2439 if (paBlocks2)
2440 RTMemTmpFree(paBlocks2);
2441 if (pvTmp)
2442 RTMemTmpFree(pvTmp);
2443 if (pvBuf)
2444 RTMemTmpFree(pvBuf);
2445
2446 if (RT_SUCCESS(rc))
2447 vdIfProgress(pIfProgress, uPercentStart + uPercentSpan);
2448
2449 LogFlowFunc(("returns %Rrc\n", rc));
2450 return rc;
2451}
2452
2453
2454/** @copydoc VDIMAGEBACKEND::pfnResize */
2455static DECLCALLBACK(int) vdiResize(void *pBackendData, uint64_t cbSize,
2456 PCVDGEOMETRY pPCHSGeometry, PCVDGEOMETRY pLCHSGeometry,
2457 unsigned uPercentStart, unsigned uPercentSpan,
2458 PVDINTERFACE pVDIfsDisk, PVDINTERFACE pVDIfsImage,
2459 PVDINTERFACE pVDIfsOperation)
2460{
2461 RT_NOREF5(uPercentStart, uPercentSpan, pVDIfsDisk, pVDIfsImage, pVDIfsOperation);
2462 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
2463 int rc = VINF_SUCCESS;
2464
2465 /*
2466 * Making the image smaller is not supported at the moment.
2467 * Resizing is also not supported for fixed size images and
2468 * very old images.
2469 */
2470 /** @todo implement making the image smaller, it is the responsibility of
2471 * the user to know what he's doing. */
2472 if ( cbSize < getImageDiskSize(&pImage->Header)
2473 || GET_MAJOR_HEADER_VERSION(&pImage->Header) == 0
2474 || pImage->uImageFlags & VD_IMAGE_FLAGS_FIXED)
2475 rc = VERR_NOT_SUPPORTED;
2476 else if (cbSize > getImageDiskSize(&pImage->Header))
2477 {
2478 unsigned cBlocksAllocated = getImageBlocksAllocated(&pImage->Header); /** < Blocks currently allocated, doesn't change during resize */
2479 uint32_t cBlocksNew = cbSize / getImageBlockSize(&pImage->Header); /** < New number of blocks in the image after the resize */
2480 if (cbSize % getImageBlockSize(&pImage->Header))
2481 cBlocksNew++;
2482
2483 uint32_t cBlocksOld = getImageBlocks(&pImage->Header); /** < Number of blocks before the resize. */
2484 uint64_t cbBlockspaceNew = cBlocksNew * sizeof(VDIIMAGEBLOCKPOINTER); /** < Required space for the block array after the resize. */
2485 uint64_t offStartDataNew = RT_ALIGN_32(pImage->offStartBlocks + cbBlockspaceNew, VDI_DATA_ALIGN); /** < New start offset for block data after the resize */
2486
2487 if ( pImage->offStartData < offStartDataNew
2488 && cBlocksAllocated > 0)
2489 {
2490 /* Calculate how many sectors need to be relocated. */
2491 uint64_t cbOverlapping = offStartDataNew - pImage->offStartData;
2492 unsigned cBlocksReloc = cbOverlapping / getImageBlockSize(&pImage->Header);
2493 if (cbOverlapping % getImageBlockSize(&pImage->Header))
2494 cBlocksReloc++;
2495
2496 /* Since only full blocks can be relocated the new data start is
2497 * determined by moving it block by block. */
2498 cBlocksReloc = RT_MIN(cBlocksReloc, cBlocksAllocated);
2499 offStartDataNew = pImage->offStartData;
2500
2501 /* Do the relocation. */
2502 LogFlow(("Relocating %u blocks\n", cBlocksReloc));
2503
2504 /*
2505 * Get the blocks we need to relocate first, they are appended to the end
2506 * of the image.
2507 */
2508 void *pvBuf = NULL, *pvZero = NULL;
2509 do
2510 {
2511 /* Allocate data buffer. */
2512 pvBuf = RTMemAllocZ(pImage->cbTotalBlockData);
2513 if (!pvBuf)
2514 {
2515 rc = VERR_NO_MEMORY;
2516 break;
2517 }
2518
2519 /* Allocate buffer for overwriting with zeroes. */
2520 pvZero = RTMemAllocZ(pImage->cbTotalBlockData);
2521 if (!pvZero)
2522 {
2523 rc = VERR_NO_MEMORY;
2524 break;
2525 }
2526
2527 for (unsigned i = 0; i < cBlocksReloc; i++)
2528 {
2529 /* Search the index in the block table. */
2530 for (unsigned idxBlock = 0; idxBlock < cBlocksOld; idxBlock++)
2531 {
2532 if (!pImage->paBlocks[idxBlock])
2533 {
2534 /* Read data and append to the end of the image. */
2535 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pImage->pStorage,
2536 offStartDataNew, pvBuf,
2537 pImage->cbTotalBlockData);
2538 if (RT_FAILURE(rc))
2539 break;
2540
2541 uint64_t offBlockAppend;
2542 rc = vdIfIoIntFileGetSize(pImage->pIfIo, pImage->pStorage, &offBlockAppend);
2543 if (RT_FAILURE(rc))
2544 break;
2545
2546 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pImage->pStorage,
2547 offBlockAppend, pvBuf,
2548 pImage->cbTotalBlockData);
2549 if (RT_FAILURE(rc))
2550 break;
2551
2552 /* Zero out the old block area. */
2553 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pImage->pStorage,
2554 offStartDataNew, pvZero,
2555 pImage->cbTotalBlockData);
2556 if (RT_FAILURE(rc))
2557 break;
2558
2559 /* Update block counter. */
2560 pImage->paBlocks[idxBlock] = cBlocksAllocated - 1;
2561
2562 /*
2563 * Decrease the block number of all other entries in the array.
2564 * They were moved one block to the front.
2565 * Doing it as a separate step iterating over the array again
2566 * because an error while relocating the block might end up
2567 * in a corrupted image otherwise.
2568 */
2569 for (unsigned idxBlock2 = 0; idxBlock2 < cBlocksOld; idxBlock2++)
2570 {
2571 if ( idxBlock2 != idxBlock
2572 && IS_VDI_IMAGE_BLOCK_ALLOCATED(pImage->paBlocks[idxBlock2]))
2573 pImage->paBlocks[idxBlock2]--;
2574 }
2575
2576 /* Continue with the next block. */
2577 break;
2578 }
2579 }
2580
2581 if (RT_FAILURE(rc))
2582 break;
2583
2584 offStartDataNew += pImage->cbTotalBlockData;
2585 }
2586 } while (0);
2587
2588 if (pvBuf)
2589 RTMemFree(pvBuf);
2590 if (pvZero)
2591 RTMemFree(pvZero);
2592 }
2593
2594 /*
2595 * We need to update the new offsets for the image data in the out of memory
2596 * case too because we relocated the blocks already.
2597 */
2598 pImage->offStartData = offStartDataNew;
2599 setImageDataOffset(&pImage->Header, offStartDataNew);
2600
2601 /*
2602 * Relocation done, expand the block array and update the header with
2603 * the new data.
2604 */
2605 if (RT_SUCCESS(rc))
2606 {
2607 PVDIIMAGEBLOCKPOINTER paBlocksNew = (PVDIIMAGEBLOCKPOINTER)RTMemRealloc(pImage->paBlocks, cbBlockspaceNew);
2608 if (paBlocksNew)
2609 {
2610 pImage->paBlocks = paBlocksNew;
2611
2612 /* Mark the new blocks as unallocated. */
2613 for (unsigned idxBlock = cBlocksOld; idxBlock < cBlocksNew; idxBlock++)
2614 pImage->paBlocks[idxBlock] = VDI_IMAGE_BLOCK_FREE;
2615 }
2616 else
2617 rc = VERR_NO_MEMORY;
2618
2619 /* Write the block array before updating the rest. */
2620 vdiConvBlocksEndianess(VDIECONV_H2F, pImage->paBlocks, cBlocksNew);
2621 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pImage->pStorage, pImage->offStartBlocks,
2622 pImage->paBlocks, cbBlockspaceNew);
2623 vdiConvBlocksEndianess(VDIECONV_F2H, pImage->paBlocks, cBlocksNew);
2624
2625 if (RT_SUCCESS(rc))
2626 {
2627 /* Update size and new block count. */
2628 setImageDiskSize(&pImage->Header, cbSize);
2629 setImageBlocks(&pImage->Header, cBlocksNew);
2630 /* Update geometry. */
2631 pImage->PCHSGeometry = *pPCHSGeometry;
2632 pImage->cbImage = cbSize;
2633
2634 PVDIDISKGEOMETRY pGeometry = getImageLCHSGeometry(&pImage->Header);
2635 if (pGeometry)
2636 {
2637 pGeometry->cCylinders = pLCHSGeometry->cCylinders;
2638 pGeometry->cHeads = pLCHSGeometry->cHeads;
2639 pGeometry->cSectors = pLCHSGeometry->cSectors;
2640 pGeometry->cbSector = VDI_GEOMETRY_SECTOR_SIZE;
2641 }
2642 }
2643 }
2644
2645 /* Update header information in base image file. */
2646 vdiFlushImage(pImage);
2647 }
2648 /* Same size doesn't change the image at all. */
2649
2650 LogFlowFunc(("returns %Rrc\n", rc));
2651 return rc;
2652}
2653
2654/** @copydoc VDIMAGEBACKEND::pfnDiscard */
2655static DECLCALLBACK(int) vdiDiscard(void *pBackendData, PVDIOCTX pIoCtx,
2656 uint64_t uOffset, size_t cbDiscard,
2657 size_t *pcbPreAllocated, size_t *pcbPostAllocated,
2658 size_t *pcbActuallyDiscarded, void **ppbmAllocationBitmap,
2659 unsigned fDiscard)
2660{
2661 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
2662 unsigned uBlock;
2663 unsigned offDiscard;
2664 int rc = VINF_SUCCESS;
2665 void *pvBlock = NULL;
2666
2667 LogFlowFunc(("pBackendData=%#p pIoCtx=%#p uOffset=%llu cbDiscard=%zu pcbPreAllocated=%#p pcbPostAllocated=%#p pcbActuallyDiscarded=%#p ppbmAllocationBitmap=%#p fDiscard=%#x\n",
2668 pBackendData, pIoCtx, uOffset, cbDiscard, pcbPreAllocated, pcbPostAllocated, pcbActuallyDiscarded, ppbmAllocationBitmap, fDiscard));
2669
2670 AssertPtr(pImage);
2671 Assert(!(uOffset % 512));
2672 Assert(!(cbDiscard % 512));
2673
2674 AssertMsgReturn(!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY),
2675 ("Image is readonly\n"), VERR_VD_IMAGE_READ_ONLY);
2676 AssertMsgReturn( uOffset + cbDiscard <= getImageDiskSize(&pImage->Header)
2677 && cbDiscard,
2678 ("Invalid parameters uOffset=%llu cbDiscard=%zu\n",
2679 uOffset, cbDiscard),
2680 VERR_INVALID_PARAMETER);
2681
2682 do
2683 {
2684 AssertMsgBreakStmt(!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY),
2685 ("Image is opened readonly\n"),
2686 rc = VERR_VD_IMAGE_READ_ONLY);
2687
2688 AssertMsgBreakStmt(cbDiscard,
2689 ("cbDiscard=%u\n", cbDiscard),
2690 rc = VERR_INVALID_PARAMETER);
2691
2692 /* Calculate starting block number and offset inside it. */
2693 uBlock = (unsigned)(uOffset >> pImage->uShiftOffset2Index);
2694 offDiscard = (unsigned)uOffset & pImage->uBlockMask;
2695
2696 /* Clip range to at most the rest of the block. */
2697 cbDiscard = RT_MIN(cbDiscard, getImageBlockSize(&pImage->Header) - offDiscard);
2698 Assert(!(cbDiscard % 512));
2699
2700 if (pcbPreAllocated)
2701 *pcbPreAllocated = 0;
2702
2703 if (pcbPostAllocated)
2704 *pcbPostAllocated = 0;
2705
2706 if (IS_VDI_IMAGE_BLOCK_ALLOCATED(pImage->paBlocks[uBlock]))
2707 {
2708 uint8_t *pbBlockData;
2709 size_t cbPreAllocated, cbPostAllocated;
2710
2711 cbPreAllocated = offDiscard % getImageBlockSize(&pImage->Header);
2712 cbPostAllocated = getImageBlockSize(&pImage->Header) - cbDiscard - cbPreAllocated;
2713
2714 /* Read the block data. */
2715 pvBlock = RTMemAlloc(pImage->cbTotalBlockData);
2716 if (!pvBlock)
2717 {
2718 rc = VERR_NO_MEMORY;
2719 break;
2720 }
2721
2722 if (!cbPreAllocated && !cbPostAllocated)
2723 {
2724 /*
2725 * Discarding a whole block, don't check for allocated sectors.
2726 * It is possible to just remove the whole block which avoids
2727 * one read and checking the whole block for data.
2728 */
2729 rc = vdiDiscardBlockAsync(pImage, pIoCtx, uBlock, pvBlock);
2730 }
2731 else if (fDiscard & VD_DISCARD_MARK_UNUSED)
2732 {
2733 /* Just zero out the given range. */
2734 memset(pvBlock, 0, cbDiscard);
2735
2736 uint64_t u64Offset = (uint64_t)pImage->paBlocks[uBlock] * pImage->cbTotalBlockData + pImage->offStartData + offDiscard;
2737 rc = vdIfIoIntFileWriteMeta(pImage->pIfIo, pImage->pStorage,
2738 u64Offset, pvBlock, cbDiscard, pIoCtx,
2739 NULL, NULL);
2740 RTMemFree(pvBlock);
2741 }
2742 else
2743 {
2744 /*
2745 * Read complete block as metadata, the I/O context has no memory buffer
2746 * and we need to access the content directly anyway.
2747 */
2748 PVDMETAXFER pMetaXfer;
2749 pbBlockData = (uint8_t *)pvBlock + pImage->offStartBlockData;
2750
2751 uint64_t u64Offset = (uint64_t)pImage->paBlocks[uBlock] * pImage->cbTotalBlockData + pImage->offStartData;
2752 rc = vdIfIoIntFileReadMeta(pImage->pIfIo, pImage->pStorage, u64Offset,
2753 pbBlockData, pImage->cbTotalBlockData,
2754 pIoCtx, &pMetaXfer, NULL, NULL);
2755 if (RT_FAILURE(rc))
2756 {
2757 RTMemFree(pvBlock);
2758 break;
2759 }
2760
2761 vdIfIoIntMetaXferRelease(pImage->pIfIo, pMetaXfer);
2762
2763 /* Clear data. */
2764 memset(pbBlockData + offDiscard , 0, cbDiscard);
2765
2766 Assert(!(cbDiscard % 4));
2767 Assert(getImageBlockSize(&pImage->Header) * 8 <= UINT32_MAX);
2768 if (ASMBitFirstSet((volatile void *)pbBlockData, getImageBlockSize(&pImage->Header) * 8) == -1)
2769 rc = vdiDiscardBlockAsync(pImage, pIoCtx, uBlock, pvBlock);
2770 else
2771 {
2772 /* Block has data, create allocation bitmap. */
2773 *pcbPreAllocated = cbPreAllocated;
2774 *pcbPostAllocated = cbPostAllocated;
2775 *ppbmAllocationBitmap = vdiAllocationBitmapCreate(pbBlockData, getImageBlockSize(&pImage->Header));
2776 if (RT_UNLIKELY(!*ppbmAllocationBitmap))
2777 rc = VERR_NO_MEMORY;
2778 else
2779 rc = VERR_VD_DISCARD_ALIGNMENT_NOT_MET;
2780
2781 RTMemFree(pvBlock);
2782 }
2783 } /* if: no complete block discarded */
2784 } /* if: Block is allocated. */
2785 /* else: nothing to do. */
2786 } while (0);
2787
2788 if (pcbActuallyDiscarded)
2789 *pcbActuallyDiscarded = cbDiscard;
2790
2791 LogFlowFunc(("returns %Rrc\n", rc));
2792 return rc;
2793}
2794
2795/** @copydoc VDIMAGEBACKEND::pfnRepair */
2796static DECLCALLBACK(int) vdiRepair(const char *pszFilename, PVDINTERFACE pVDIfsDisk,
2797 PVDINTERFACE pVDIfsImage, uint32_t fFlags)
2798{
2799 LogFlowFunc(("pszFilename=\"%s\" pVDIfsDisk=%#p pVDIfsImage=%#p\n", pszFilename, pVDIfsDisk, pVDIfsImage));
2800 int rc;
2801 PVDINTERFACEERROR pIfError;
2802 PVDINTERFACEIOINT pIfIo;
2803 PVDIOSTORAGE pStorage;
2804 uint64_t cbFile;
2805 PVDIIMAGEBLOCKPOINTER paBlocks = NULL;
2806 uint32_t *pu32BlockBitmap = NULL;
2807 VDIPREHEADER PreHdr;
2808 VDIHEADER Hdr;
2809
2810 pIfIo = VDIfIoIntGet(pVDIfsImage);
2811 AssertPtrReturn(pIfIo, VERR_INVALID_PARAMETER);
2812
2813 pIfError = VDIfErrorGet(pVDIfsDisk);
2814
2815 do
2816 {
2817 bool fRepairBlockArray = false;
2818
2819 rc = vdIfIoIntFileOpen(pIfIo, pszFilename,
2820 VDOpenFlagsToFileOpenFlags( fFlags & VD_REPAIR_DRY_RUN
2821 ? VD_OPEN_FLAGS_READONLY
2822 : 0,
2823 false /* fCreate */),
2824 &pStorage);
2825 if (RT_FAILURE(rc))
2826 {
2827 rc = vdIfError(pIfError, rc, RT_SRC_POS, "VDI: Failed to open image \"%s\"", pszFilename);
2828 break;
2829 }
2830
2831 rc = vdIfIoIntFileGetSize(pIfIo, pStorage, &cbFile);
2832 if (RT_FAILURE(rc))
2833 {
2834 rc = vdIfError(pIfError, rc, RT_SRC_POS, "VDI: Failed to query image size");
2835 break;
2836 }
2837
2838 /* Read pre-header. */
2839 rc = vdIfIoIntFileReadSync(pIfIo, pStorage, 0, &PreHdr, sizeof(PreHdr));
2840 if (RT_FAILURE(rc))
2841 {
2842 rc = vdIfError(pIfError, rc, RT_SRC_POS, N_("VDI: Error reading pre-header in '%s'"), pszFilename);
2843 break;
2844 }
2845 vdiConvPreHeaderEndianess(VDIECONV_F2H, &PreHdr, &PreHdr);
2846 rc = vdiValidatePreHeader(&PreHdr);
2847 if (RT_FAILURE(rc))
2848 {
2849 rc = vdIfError(pIfError, VERR_VD_IMAGE_REPAIR_IMPOSSIBLE, RT_SRC_POS,
2850 N_("VDI: invalid pre-header in '%s'"), pszFilename);
2851 break;
2852 }
2853
2854 /* Read header. */
2855 Hdr.uVersion = PreHdr.u32Version;
2856 switch (GET_MAJOR_HEADER_VERSION(&Hdr))
2857 {
2858 case 0:
2859 rc = vdIfIoIntFileReadSync(pIfIo, pStorage, sizeof(PreHdr),
2860 &Hdr.u.v0, sizeof(Hdr.u.v0));
2861 if (RT_FAILURE(rc))
2862 rc = vdIfError(pIfError, rc, RT_SRC_POS, N_("VDI: error reading v0 header in '%s'"),
2863 pszFilename);
2864 vdiConvHeaderEndianessV0(VDIECONV_F2H, &Hdr.u.v0, &Hdr.u.v0);
2865 break;
2866 case 1:
2867 rc = vdIfIoIntFileReadSync(pIfIo, pStorage, sizeof(PreHdr),
2868 &Hdr.u.v1, sizeof(Hdr.u.v1));
2869 if (RT_FAILURE(rc))
2870 {
2871 rc = vdIfError(pIfError, rc, RT_SRC_POS, N_("VDI: error reading v1 header in '%s'"),
2872 pszFilename);
2873 }
2874 vdiConvHeaderEndianessV1(VDIECONV_F2H, &Hdr.u.v1, &Hdr.u.v1);
2875 if (Hdr.u.v1.cbHeader >= sizeof(Hdr.u.v1plus))
2876 {
2877 /* Read the VDI 1.1+ header completely. */
2878 rc = vdIfIoIntFileReadSync(pIfIo, pStorage, sizeof(PreHdr),
2879 &Hdr.u.v1plus, sizeof(Hdr.u.v1plus));
2880 if (RT_FAILURE(rc))
2881 rc = vdIfError(pIfError, rc, RT_SRC_POS, N_("VDI: error reading v1.1+ header in '%s'"),
2882 pszFilename);
2883 vdiConvHeaderEndianessV1p(VDIECONV_F2H, &Hdr.u.v1plus, &Hdr.u.v1plus);
2884 }
2885 break;
2886 default:
2887 rc = vdIfError(pIfError, VERR_VD_IMAGE_REPAIR_IMPOSSIBLE, RT_SRC_POS,
2888 N_("VDI: unsupported major version %u in '%s'"),
2889 GET_MAJOR_HEADER_VERSION(&Hdr), pszFilename);
2890 break;
2891 }
2892
2893 if (RT_SUCCESS(rc))
2894 {
2895 rc = vdiValidateHeader(&Hdr);
2896 if (RT_FAILURE(rc))
2897 {
2898 rc = vdIfError(pIfError, VERR_VD_IMAGE_REPAIR_IMPOSSIBLE, RT_SRC_POS,
2899 N_("VDI: invalid header in '%s'"), pszFilename);
2900 break;
2901 }
2902 }
2903
2904 /* Setup image parameters by header. */
2905 uint64_t offStartBlocks, offStartData;
2906 size_t cbTotalBlockData;
2907
2908 offStartBlocks = getImageBlocksOffset(&Hdr);
2909 offStartData = getImageDataOffset(&Hdr);
2910 cbTotalBlockData = getImageExtraBlockSize(&Hdr) + getImageBlockSize(&Hdr);
2911
2912 /* Allocate memory for blocks array. */
2913 paBlocks = (PVDIIMAGEBLOCKPOINTER)RTMemAlloc(sizeof(VDIIMAGEBLOCKPOINTER) * getImageBlocks(&Hdr));
2914 if (!paBlocks)
2915 {
2916 rc = vdIfError(pIfError, VERR_NO_MEMORY, RT_SRC_POS,
2917 "Failed to allocate memory for block array");
2918 break;
2919 }
2920
2921 /* Read blocks array. */
2922 rc = vdIfIoIntFileReadSync(pIfIo, pStorage, offStartBlocks, paBlocks,
2923 getImageBlocks(&Hdr) * sizeof(VDIIMAGEBLOCKPOINTER));
2924 if (RT_FAILURE(rc))
2925 {
2926 rc = vdIfError(pIfError, VERR_VD_IMAGE_REPAIR_IMPOSSIBLE, RT_SRC_POS,
2927 "Failed to read block array (at %llu), %Rrc",
2928 offStartBlocks, rc);
2929 break;
2930 }
2931 vdiConvBlocksEndianess(VDIECONV_F2H, paBlocks, getImageBlocks(&Hdr));
2932
2933 pu32BlockBitmap = (uint32_t *)RTMemAllocZ(RT_ALIGN_Z(getImageBlocks(&Hdr) / 8, 4));
2934 if (!pu32BlockBitmap)
2935 {
2936 rc = vdIfError(pIfError, VERR_NO_MEMORY, RT_SRC_POS,
2937 "Failed to allocate memory for block bitmap");
2938 break;
2939 }
2940
2941 for (uint32_t i = 0; i < getImageBlocks(&Hdr); i++)
2942 {
2943 if (IS_VDI_IMAGE_BLOCK_ALLOCATED(paBlocks[i]))
2944 {
2945 uint64_t offBlock = (uint64_t)paBlocks[i] * cbTotalBlockData
2946 + offStartData;
2947
2948 /*
2949 * Check that the offsets are valid (inside of the image) and
2950 * that there are no double references.
2951 */
2952 if (offBlock + cbTotalBlockData > cbFile)
2953 {
2954 vdIfErrorMessage(pIfError, "Entry %u points to invalid offset %llu, clearing\n",
2955 i, offBlock);
2956 paBlocks[i] = VDI_IMAGE_BLOCK_FREE;
2957 fRepairBlockArray = true;
2958 }
2959 else if (ASMBitTestAndSet(pu32BlockBitmap, paBlocks[i]))
2960 {
2961 vdIfErrorMessage(pIfError, "Entry %u points to an already referenced data block, clearing\n",
2962 i);
2963 paBlocks[i] = VDI_IMAGE_BLOCK_FREE;
2964 fRepairBlockArray = true;
2965 }
2966 }
2967 }
2968
2969 /* Write repaired structures now. */
2970 if (!fRepairBlockArray)
2971 vdIfErrorMessage(pIfError, "VDI image is in a consistent state, no repair required\n");
2972 else if (!(fFlags & VD_REPAIR_DRY_RUN))
2973 {
2974 vdIfErrorMessage(pIfError, "Writing repaired block allocation table...\n");
2975
2976 vdiConvBlocksEndianess(VDIECONV_H2F, paBlocks, getImageBlocks(&Hdr));
2977 rc = vdIfIoIntFileWriteSync(pIfIo, pStorage, offStartBlocks, paBlocks,
2978 getImageBlocks(&Hdr) * sizeof(VDIIMAGEBLOCKPOINTER));
2979 if (RT_FAILURE(rc))
2980 {
2981 rc = vdIfError(pIfError, VERR_VD_IMAGE_REPAIR_IMPOSSIBLE, RT_SRC_POS,
2982 "Could not write repaired block allocation table (at %llu), %Rrc",
2983 offStartBlocks, rc);
2984 break;
2985 }
2986 }
2987
2988 vdIfErrorMessage(pIfError, "Corrupted VDI image repaired successfully\n");
2989 } while(0);
2990
2991 if (paBlocks)
2992 RTMemFree(paBlocks);
2993
2994 if (pu32BlockBitmap)
2995 RTMemFree(pu32BlockBitmap);
2996
2997 if (pStorage)
2998 {
2999 int rc2 = vdIfIoIntFileClose(pIfIo, pStorage);
3000 if (RT_SUCCESS(rc))
3001 rc = rc2; /* Propagate error code only if repairing was successful. */
3002 }
3003
3004 LogFlowFunc(("returns %Rrc\n", rc));
3005 return rc;
3006}
3007
3008const VDIMAGEBACKEND g_VDIBackend =
3009{
3010 /* u32Version */
3011 VD_IMGBACKEND_VERSION,
3012 /* pszBackendName */
3013 "VDI",
3014 /* uBackendCaps */
3015 VD_CAP_UUID | VD_CAP_CREATE_FIXED | VD_CAP_CREATE_DYNAMIC
3016 | VD_CAP_DIFF | VD_CAP_FILE | VD_CAP_ASYNC | VD_CAP_VFS | VD_CAP_DISCARD
3017 | VD_CAP_PREFERRED,
3018 /* paFileExtensions */
3019 s_aVdiFileExtensions,
3020 /* paConfigInfo */
3021 NULL,
3022 /* pfnProbe */
3023 vdiProbe,
3024 /* pfnOpen */
3025 vdiOpen,
3026 /* pfnCreate */
3027 vdiCreate,
3028 /* pfnRename */
3029 vdiRename,
3030 /* pfnClose */
3031 vdiClose,
3032 /* pfnRead */
3033 vdiRead,
3034 /* pfnWrite */
3035 vdiWrite,
3036 /* pfnFlush */
3037 vdiFlush,
3038 /* pfnDiscard */
3039 vdiDiscard,
3040 /* pfnGetVersion */
3041 vdiGetVersion,
3042 /* pfnGetSectorSize */
3043 vdiGetSectorSize,
3044 /* pfnGetSize */
3045 vdiGetSize,
3046 /* pfnGetFileSize */
3047 vdiGetFileSize,
3048 /* pfnGetPCHSGeometry */
3049 vdiGetPCHSGeometry,
3050 /* pfnSetPCHSGeometry */
3051 vdiSetPCHSGeometry,
3052 /* pfnGetLCHSGeometry */
3053 vdiGetLCHSGeometry,
3054 /* pfnSetLCHSGeometry */
3055 vdiSetLCHSGeometry,
3056 /* pfnGetImageFlags */
3057 vdiGetImageFlags,
3058 /* pfnGetOpenFlags */
3059 vdiGetOpenFlags,
3060 /* pfnSetOpenFlags */
3061 vdiSetOpenFlags,
3062 /* pfnGetComment */
3063 vdiGetComment,
3064 /* pfnSetComment */
3065 vdiSetComment,
3066 /* pfnGetUuid */
3067 vdiGetUuid,
3068 /* pfnSetUuid */
3069 vdiSetUuid,
3070 /* pfnGetModificationUuid */
3071 vdiGetModificationUuid,
3072 /* pfnSetModificationUuid */
3073 vdiSetModificationUuid,
3074 /* pfnGetParentUuid */
3075 vdiGetParentUuid,
3076 /* pfnSetParentUuid */
3077 vdiSetParentUuid,
3078 /* pfnGetParentModificationUuid */
3079 vdiGetParentModificationUuid,
3080 /* pfnSetParentModificationUuid */
3081 vdiSetParentModificationUuid,
3082 /* pfnDump */
3083 vdiDump,
3084 /* pfnGetTimestamp */
3085 NULL,
3086 /* pfnGetParentTimestamp */
3087 NULL,
3088 /* pfnSetParentTimestamp */
3089 NULL,
3090 /* pfnGetParentFilename */
3091 NULL,
3092 /* pfnSetParentFilename */
3093 NULL,
3094 /* pfnComposeLocation */
3095 genericFileComposeLocation,
3096 /* pfnComposeName */
3097 genericFileComposeName,
3098 /* pfnCompact */
3099 vdiCompact,
3100 /* pfnResize */
3101 vdiResize,
3102 /* pfnRepair */
3103 vdiRepair,
3104 /* pfnTraverseMetadata */
3105 NULL,
3106 /* u32VersionEnd */
3107 VD_IMGBACKEND_VERSION
3108};
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