VirtualBox

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

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

Storage/VDI: Silently repair images with a non sector aligned disk size (Until r111992 it was possible to create those because of a missing check and a bug in the OS X version of the Qt frontend), also implement the repair in vdiRepair()

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