VirtualBox

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

Last change on this file since 79742 was 79742, checked in by vboxsync, 5 years ago

Changes per #5899 / Comment #14

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