VirtualBox

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

Last change on this file since 102654 was 99739, checked in by vboxsync, 19 months ago

*: doxygen corrections (mostly about removing @returns from functions returning void).

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