VirtualBox

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

Last change on this file since 104620 was 103528, checked in by vboxsync, 9 months ago

Storage/VHD.cpp,VDI.cpp: Build fixes, bugref:3409

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 128.3 KB
Line 
1/* $Id: VDI.cpp 103528 2024-02-22 11:29:39Z 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 PVDIDISKGEOMETRY pLCHSGeom = getImageLCHSGeometry(pHeader);
483 if ( pLCHSGeom
484 && pLCHSGeom->cbSector != VDI_GEOMETRY_SECTOR_SIZE)
485 {
486 LogRel(("VDI: wrong sector size (%d != %d)\n", pLCHSGeom->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 >= _1P * 4 - _1M * 3
1516 || cbSize < VDI_IMAGE_DEFAULT_BLOCK_SIZE
1517 || (cbSize % 512))
1518 return VERR_VD_INVALID_SIZE;
1519
1520 /* Check open flags. All valid flags are supported. */
1521 AssertReturn(!(uOpenFlags & ~VD_OPEN_FLAGS_MASK), VERR_INVALID_PARAMETER);
1522 AssertPtrReturn(pszFilename, VERR_INVALID_POINTER);
1523 AssertReturn(*pszFilename != '\0', VERR_INVALID_PARAMETER);
1524 AssertPtrReturn(pPCHSGeometry, VERR_INVALID_POINTER);
1525 AssertPtrReturn(pLCHSGeometry, VERR_INVALID_POINTER);
1526
1527 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)RTMemAllocZ(RT_UOFFSETOF(VDIIMAGEDESC, RegionList.aRegions[1]));
1528 if (RT_LIKELY(pImage))
1529 {
1530 PVDINTERFACEPROGRESS pIfProgress = VDIfProgressGet(pVDIfsOperation);
1531 PVDINTERFACECONFIG pIfCfg = VDIfConfigGet(pVDIfsOperation);
1532 pImage->pszFilename = pszFilename;
1533 pImage->pStorage = NULL;
1534 pImage->paBlocks = NULL;
1535 pImage->pVDIfsDisk = pVDIfsDisk;
1536 pImage->pVDIfsImage = pVDIfsImage;
1537
1538 rc = vdiCreateImage(pImage, cbSize, uImageFlags, pszComment,
1539 pPCHSGeometry, pLCHSGeometry, pUuid, uOpenFlags,
1540 pIfProgress, uPercentStart, uPercentSpan, pIfCfg);
1541 if (RT_SUCCESS(rc))
1542 {
1543 /* So far the image is opened in read/write mode. Make sure the
1544 * image is opened in read-only mode if the caller requested that. */
1545 if (uOpenFlags & VD_OPEN_FLAGS_READONLY)
1546 {
1547 vdiFreeImage(pImage, false);
1548 rc = vdiOpenImage(pImage, uOpenFlags);
1549 }
1550
1551 if (RT_SUCCESS(rc))
1552 *ppBackendData = pImage;
1553 }
1554
1555 if (RT_FAILURE(rc))
1556 RTMemFree(pImage);
1557 }
1558 else
1559 rc = VERR_NO_MEMORY;
1560
1561 LogFlowFunc(("returns %Rrc (pBackendData=%#p)\n", rc, *ppBackendData));
1562 return rc;
1563}
1564
1565/** @copydoc VDIMAGEBACKEND::pfnRename */
1566static DECLCALLBACK(int) vdiRename(void *pBackendData, const char *pszFilename)
1567{
1568 LogFlowFunc(("pBackendData=%#p pszFilename=%#p\n", pBackendData, pszFilename));
1569 int rc = VINF_SUCCESS;
1570 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1571
1572 /* Check arguments. */
1573 AssertReturn((pImage && pszFilename && *pszFilename), VERR_INVALID_PARAMETER);
1574
1575 /* Close the image. */
1576 rc = vdiFreeImage(pImage, false);
1577 if (RT_SUCCESS(rc))
1578 {
1579 /* Rename the file. */
1580 rc = vdIfIoIntFileMove(pImage->pIfIo, pImage->pszFilename, pszFilename, 0);
1581 if (RT_SUCCESS(rc))
1582 {
1583 /* Update pImage with the new information. */
1584 pImage->pszFilename = pszFilename;
1585
1586 /* Open the new image. */
1587 rc = vdiOpenImage(pImage, pImage->uOpenFlags);
1588 }
1589 else
1590 {
1591 /* The move failed, try to reopen the original image. */
1592 int rc2 = vdiOpenImage(pImage, pImage->uOpenFlags);
1593 if (RT_FAILURE(rc2))
1594 rc = rc2;
1595 }
1596 }
1597
1598 LogFlowFunc(("returns %Rrc\n", rc));
1599 return rc;
1600}
1601
1602/** @copydoc VDIMAGEBACKEND::pfnClose */
1603static DECLCALLBACK(int) vdiClose(void *pBackendData, bool fDelete)
1604{
1605 LogFlowFunc(("pBackendData=%#p fDelete=%d\n", pBackendData, fDelete));
1606 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1607
1608 int rc = vdiFreeImage(pImage, fDelete);
1609 RTMemFree(pImage);
1610
1611 LogFlowFunc(("returns %Rrc\n", rc));
1612 return rc;
1613}
1614
1615static DECLCALLBACK(int) vdiRead(void *pBackendData, uint64_t uOffset, size_t cbToRead,
1616 PVDIOCTX pIoCtx, size_t *pcbActuallyRead)
1617{
1618 LogFlowFunc(("pBackendData=%#p uOffset=%llu pIoCtx=%#p cbToRead=%zu pcbActuallyRead=%#p\n",
1619 pBackendData, uOffset, pIoCtx, cbToRead, pcbActuallyRead));
1620 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1621 unsigned uBlock;
1622 unsigned offRead;
1623 int rc = VINF_SUCCESS;
1624
1625 AssertPtr(pImage);
1626 Assert(!(uOffset % 512));
1627 Assert(!(cbToRead % 512));
1628 AssertPtrReturn(pIoCtx, VERR_INVALID_POINTER);
1629 AssertReturn(cbToRead, VERR_INVALID_PARAMETER);
1630 AssertReturn(uOffset + cbToRead <= getImageDiskSize(&pImage->Header), VERR_INVALID_PARAMETER);
1631
1632 /* Calculate starting block number and offset inside it. */
1633 uBlock = (unsigned)(uOffset >> pImage->uShiftOffset2Index);
1634 offRead = (unsigned)uOffset & pImage->uBlockMask;
1635
1636 /* Clip read range to at most the rest of the block. */
1637 size_t cbBlockRem = getImageBlockSize(&pImage->Header) - offRead;
1638 cbToRead = RT_MIN(cbToRead, cbBlockRem);
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 = vdIfIoIntIoCtxSet(pImage->pIfIo, pIoCtx, 0, cbToRead);
1646 Assert(cbSet == cbToRead); RT_NOREF(cbSet);
1647 }
1648 else
1649 {
1650 /* Block present in image file, read relevant data. */
1651 uint64_t u64Offset = (uint64_t)pImage->paBlocks[uBlock] * pImage->cbTotalBlockData
1652 + (pImage->offStartData + pImage->offStartBlockData + offRead);
1653
1654 if (u64Offset + cbToRead <= pImage->cbImage)
1655 rc = vdIfIoIntFileReadUser(pImage->pIfIo, pImage->pStorage, u64Offset,
1656 pIoCtx, cbToRead);
1657 else
1658 {
1659 LogRel(("VDI: Out of range access (%llu) in image %s, image size %llu\n",
1660 u64Offset, pImage->pszFilename, pImage->cbImage));
1661 vdIfIoIntIoCtxSet(pImage->pIfIo, pIoCtx, 0, cbToRead);
1662 rc = VERR_VD_READ_OUT_OF_RANGE;
1663 }
1664 }
1665
1666 if (pcbActuallyRead)
1667 *pcbActuallyRead = cbToRead;
1668
1669 LogFlowFunc(("returns %Rrc\n", rc));
1670 return rc;
1671}
1672
1673static DECLCALLBACK(int) vdiWrite(void *pBackendData, uint64_t uOffset, size_t cbToWrite,
1674 PVDIOCTX pIoCtx, size_t *pcbWriteProcess, size_t *pcbPreRead,
1675 size_t *pcbPostRead, unsigned fWrite)
1676{
1677 LogFlowFunc(("pBackendData=%#p uOffset=%llu pIoCtx=%#p cbToWrite=%zu pcbWriteProcess=%#p pcbPreRead=%#p pcbPostRead=%#p\n",
1678 pBackendData, uOffset, pIoCtx, cbToWrite, pcbWriteProcess, pcbPreRead, pcbPostRead));
1679 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1680 unsigned uBlock;
1681 unsigned offWrite;
1682 int rc = VINF_SUCCESS;
1683
1684 AssertPtr(pImage);
1685 Assert(!(uOffset % 512));
1686 Assert(!(cbToWrite % 512));
1687 AssertPtrReturn(pIoCtx, VERR_INVALID_POINTER);
1688 AssertReturn(cbToWrite, VERR_INVALID_PARAMETER);
1689
1690 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
1691 {
1692 /* No size check here, will do that later. For dynamic images which are
1693 * not multiples of the block size in length, this would prevent writing to
1694 * the last block. */
1695
1696 /* Calculate starting block number and offset inside it. */
1697 uBlock = (unsigned)(uOffset >> pImage->uShiftOffset2Index);
1698 offWrite = (unsigned)uOffset & pImage->uBlockMask;
1699
1700 /* Clip write range to at most the rest of the block. */
1701 size_t cbBlockRem = getImageBlockSize(&pImage->Header) - offWrite;
1702 cbToWrite = RT_MIN(cbToWrite, cbBlockRem);
1703 Assert(!(cbToWrite % 512));
1704
1705 do
1706 {
1707 if (!IS_VDI_IMAGE_BLOCK_ALLOCATED(pImage->paBlocks[uBlock]))
1708 {
1709 /* Block is either free or zero. */
1710 if ( !(pImage->uOpenFlags & VD_OPEN_FLAGS_HONOR_ZEROES)
1711 && ( pImage->paBlocks[uBlock] == VDI_IMAGE_BLOCK_ZERO
1712 || cbToWrite == getImageBlockSize(&pImage->Header)))
1713 {
1714 /* If the destination block is unallocated at this point, it's
1715 * either a zero block or a block which hasn't been used so far
1716 * (which also means that it's a zero block. Don't need to write
1717 * anything to this block if the data consists of just zeroes. */
1718 if (vdIfIoIntIoCtxIsZero(pImage->pIfIo, pIoCtx, cbToWrite, true))
1719 {
1720 pImage->paBlocks[uBlock] = VDI_IMAGE_BLOCK_ZERO;
1721 *pcbPreRead = 0;
1722 *pcbPostRead = 0;
1723 break;
1724 }
1725 }
1726
1727 if ( cbToWrite == getImageBlockSize(&pImage->Header)
1728 && !(fWrite & VD_WRITE_NO_ALLOC))
1729 {
1730 /* Full block write to previously unallocated block.
1731 * Allocate block and write data. */
1732 Assert(!offWrite);
1733 PVDIASYNCBLOCKALLOC pBlockAlloc = (PVDIASYNCBLOCKALLOC)RTMemAllocZ(sizeof(VDIASYNCBLOCKALLOC));
1734 if (!pBlockAlloc)
1735 {
1736 rc = VERR_NO_MEMORY;
1737 break;
1738 }
1739
1740 unsigned cBlocksAllocated = getImageBlocksAllocated(&pImage->Header);
1741 uint64_t u64Offset = (uint64_t)cBlocksAllocated * pImage->cbTotalBlockData
1742 + (pImage->offStartData + pImage->offStartBlockData);
1743
1744 pBlockAlloc->cBlocksAllocated = cBlocksAllocated;
1745 pBlockAlloc->uBlock = uBlock;
1746
1747 *pcbPreRead = 0;
1748 *pcbPostRead = 0;
1749
1750 rc = vdIfIoIntFileWriteUser(pImage->pIfIo, pImage->pStorage,
1751 u64Offset, pIoCtx, cbToWrite,
1752 vdiBlockAllocUpdate, pBlockAlloc);
1753 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
1754 break;
1755 else if (RT_FAILURE(rc))
1756 {
1757 RTMemFree(pBlockAlloc);
1758 break;
1759 }
1760
1761 rc = vdiBlockAllocUpdate(pImage, pIoCtx, pBlockAlloc, rc);
1762 }
1763 else
1764 {
1765 /* Trying to do a partial write to an unallocated block. Don't do
1766 * anything except letting the upper layer know what to do. */
1767 *pcbPreRead = offWrite % getImageBlockSize(&pImage->Header);
1768 *pcbPostRead = getImageBlockSize(&pImage->Header) - cbToWrite - *pcbPreRead;
1769 rc = VERR_VD_BLOCK_FREE;
1770 }
1771 }
1772 else
1773 {
1774 /* Block present in image file, write relevant data. */
1775 uint64_t u64Offset = (uint64_t)pImage->paBlocks[uBlock] * pImage->cbTotalBlockData
1776 + (pImage->offStartData + pImage->offStartBlockData + offWrite);
1777 rc = vdIfIoIntFileWriteUser(pImage->pIfIo, pImage->pStorage,
1778 u64Offset, pIoCtx, cbToWrite, NULL, NULL);
1779 }
1780 } while (0);
1781
1782 if (pcbWriteProcess)
1783 *pcbWriteProcess = cbToWrite;
1784 }
1785 else
1786 rc = VERR_VD_IMAGE_READ_ONLY;
1787
1788 LogFlowFunc(("returns %Rrc\n", rc));
1789 return rc;
1790}
1791
1792static DECLCALLBACK(int) vdiFlush(void *pBackendData, PVDIOCTX pIoCtx)
1793{
1794 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
1795 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1796 int rc = VINF_SUCCESS;
1797
1798 Assert(pImage);
1799
1800 rc = vdiFlushImageIoCtx(pImage, pIoCtx);
1801 LogFlowFunc(("returns %Rrc\n", rc));
1802 return rc;
1803}
1804
1805/** @copydoc VDIMAGEBACKEND::pfnGetVersion */
1806static DECLCALLBACK(unsigned) vdiGetVersion(void *pBackendData)
1807{
1808 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
1809 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1810
1811 AssertPtrReturn(pImage, 0);
1812
1813 LogFlowFunc(("returns %#x\n", pImage->PreHeader.u32Version));
1814 return pImage->PreHeader.u32Version;
1815}
1816
1817/** @copydoc VDIMAGEBACKEND::pfnGetFileSize */
1818static DECLCALLBACK(uint64_t) vdiGetFileSize(void *pBackendData)
1819{
1820 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
1821 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1822 uint64_t cb = 0;
1823
1824 AssertPtrReturn(pImage, 0);
1825
1826 if (pImage->pStorage)
1827 {
1828 uint64_t cbFile;
1829 int rc = vdIfIoIntFileGetSize(pImage->pIfIo, pImage->pStorage, &cbFile);
1830 if (RT_SUCCESS(rc))
1831 cb += cbFile;
1832 }
1833
1834 LogFlowFunc(("returns %lld\n", cb));
1835 return cb;
1836}
1837
1838/** @copydoc VDIMAGEBACKEND::pfnGetPCHSGeometry */
1839static DECLCALLBACK(int) vdiGetPCHSGeometry(void *pBackendData, PVDGEOMETRY pPCHSGeometry)
1840{
1841 LogFlowFunc(("pBackendData=%#p pPCHSGeometry=%#p\n", pBackendData, pPCHSGeometry));
1842 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1843 int rc = VINF_SUCCESS;
1844
1845 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
1846
1847 if (pImage->PCHSGeometry.cCylinders)
1848 *pPCHSGeometry = pImage->PCHSGeometry;
1849 else
1850 rc = VERR_VD_GEOMETRY_NOT_SET;
1851
1852 LogFlowFunc(("returns %Rrc (PCHS=%u/%u/%u)\n", rc, pPCHSGeometry->cCylinders, pPCHSGeometry->cHeads, pPCHSGeometry->cSectors));
1853 return rc;
1854}
1855
1856/** @copydoc VDIMAGEBACKEND::pfnSetPCHSGeometry */
1857static DECLCALLBACK(int) vdiSetPCHSGeometry(void *pBackendData, PCVDGEOMETRY pPCHSGeometry)
1858{
1859 LogFlowFunc(("pBackendData=%#p pPCHSGeometry=%#p PCHS=%u/%u/%u\n",
1860 pBackendData, pPCHSGeometry, pPCHSGeometry->cCylinders, pPCHSGeometry->cHeads, pPCHSGeometry->cSectors));
1861 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1862 int rc = VINF_SUCCESS;
1863
1864 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
1865
1866 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
1867 rc = VERR_VD_IMAGE_READ_ONLY;
1868 else
1869 pImage->PCHSGeometry = *pPCHSGeometry;
1870
1871 LogFlowFunc(("returns %Rrc\n", rc));
1872 return rc;
1873}
1874
1875/** @copydoc VDIMAGEBACKEND::pfnGetLCHSGeometry */
1876static DECLCALLBACK(int) vdiGetLCHSGeometry(void *pBackendData, PVDGEOMETRY pLCHSGeometry)
1877{
1878 LogFlowFunc(("pBackendData=%#p pLCHSGeometry=%#p\n", pBackendData, pLCHSGeometry));
1879 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1880
1881 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
1882
1883 int rc = VINF_SUCCESS;
1884 VDIDISKGEOMETRY DummyGeo = { 0, 0, 0, VDI_GEOMETRY_SECTOR_SIZE };
1885 PVDIDISKGEOMETRY pGeometry = getImageLCHSGeometry(&pImage->Header);
1886 if (!pGeometry)
1887 pGeometry = &DummyGeo;
1888
1889 if ( pGeometry->cCylinders > 0
1890 && pGeometry->cHeads > 0
1891 && pGeometry->cSectors > 0)
1892 {
1893 pLCHSGeometry->cCylinders = pGeometry->cCylinders;
1894 pLCHSGeometry->cHeads = pGeometry->cHeads;
1895 pLCHSGeometry->cSectors = pGeometry->cSectors;
1896 }
1897 else
1898 rc = VERR_VD_GEOMETRY_NOT_SET;
1899
1900 LogFlowFunc(("returns %Rrc (LCHS=%u/%u/%u)\n", rc, pLCHSGeometry->cCylinders, pLCHSGeometry->cHeads, pLCHSGeometry->cSectors));
1901 return rc;
1902}
1903
1904/** @copydoc VDIMAGEBACKEND::pfnSetLCHSGeometry */
1905static DECLCALLBACK(int) vdiSetLCHSGeometry(void *pBackendData, PCVDGEOMETRY pLCHSGeometry)
1906{
1907 LogFlowFunc(("pBackendData=%#p pLCHSGeometry=%#p LCHS=%u/%u/%u\n",
1908 pBackendData, pLCHSGeometry, pLCHSGeometry->cCylinders, pLCHSGeometry->cHeads, pLCHSGeometry->cSectors));
1909 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1910 PVDIDISKGEOMETRY pGeometry;
1911 int rc = VINF_SUCCESS;
1912
1913 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
1914
1915 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
1916 {
1917 pGeometry = getImageLCHSGeometry(&pImage->Header);
1918 if (pGeometry)
1919 {
1920 pGeometry->cCylinders = pLCHSGeometry->cCylinders;
1921 pGeometry->cHeads = pLCHSGeometry->cHeads;
1922 pGeometry->cSectors = pLCHSGeometry->cSectors;
1923 pGeometry->cbSector = VDI_GEOMETRY_SECTOR_SIZE;
1924
1925 /* Update header information in base image file. */
1926 vdiFlushImage(pImage);
1927 }
1928 }
1929 else
1930 rc = VERR_VD_IMAGE_READ_ONLY;
1931
1932 LogFlowFunc(("returns %Rrc\n", rc));
1933 return rc;
1934}
1935
1936/** @copydoc VDIMAGEBACKEND::pfnQueryRegions */
1937static DECLCALLBACK(int) vdiQueryRegions(void *pBackendData, PCVDREGIONLIST *ppRegionList)
1938{
1939 LogFlowFunc(("pBackendData=%#p ppRegionList=%#p\n", pBackendData, ppRegionList));
1940 PVDIIMAGEDESC pThis = (PVDIIMAGEDESC)pBackendData;
1941
1942 AssertPtrReturn(pThis, VERR_VD_NOT_OPENED);
1943
1944 *ppRegionList = &pThis->RegionList;
1945 LogFlowFunc(("returns %Rrc\n", VINF_SUCCESS));
1946 return VINF_SUCCESS;
1947}
1948
1949/** @copydoc VDIMAGEBACKEND::pfnRegionListRelease */
1950static DECLCALLBACK(void) vdiRegionListRelease(void *pBackendData, PCVDREGIONLIST pRegionList)
1951{
1952 RT_NOREF1(pRegionList);
1953 LogFlowFunc(("pBackendData=%#p pRegionList=%#p\n", pBackendData, pRegionList));
1954 PVDIIMAGEDESC pThis = (PVDIIMAGEDESC)pBackendData;
1955 AssertPtr(pThis); RT_NOREF(pThis);
1956
1957 /* Nothing to do here. */
1958}
1959
1960/** @copydoc VDIMAGEBACKEND::pfnGetImageFlags */
1961static DECLCALLBACK(unsigned) vdiGetImageFlags(void *pBackendData)
1962{
1963 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
1964 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1965
1966 AssertPtrReturn(pImage, 0);
1967
1968 LogFlowFunc(("returns %#x\n", pImage->uImageFlags));
1969 return pImage->uImageFlags;
1970}
1971
1972/** @copydoc VDIMAGEBACKEND::pfnGetOpenFlags */
1973static DECLCALLBACK(unsigned) vdiGetOpenFlags(void *pBackendData)
1974{
1975 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
1976 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1977
1978 AssertPtrReturn(pImage, 0);
1979
1980 LogFlowFunc(("returns %#x\n", pImage->uOpenFlags));
1981 return pImage->uOpenFlags;
1982}
1983
1984/** @copydoc VDIMAGEBACKEND::pfnSetOpenFlags */
1985static DECLCALLBACK(int) vdiSetOpenFlags(void *pBackendData, unsigned uOpenFlags)
1986{
1987 LogFlowFunc(("pBackendData=%#p uOpenFlags=%#x\n", pBackendData, uOpenFlags));
1988 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1989 int rc;
1990
1991 /* Image must be opened and the new flags must be valid. */
1992 if (!pImage || (uOpenFlags & ~( VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_INFO
1993 | VD_OPEN_FLAGS_ASYNC_IO | VD_OPEN_FLAGS_SHAREABLE
1994 | VD_OPEN_FLAGS_SEQUENTIAL | VD_OPEN_FLAGS_DISCARD
1995 | VD_OPEN_FLAGS_SKIP_CONSISTENCY_CHECKS)))
1996 rc = VERR_INVALID_PARAMETER;
1997 else
1998 {
1999 /* Implement this operation via reopening the image. */
2000 rc = vdiFreeImage(pImage, false);
2001 if (RT_SUCCESS(rc))
2002 rc = vdiOpenImage(pImage, uOpenFlags);
2003 }
2004
2005 LogFlowFunc(("returns %Rrc\n", rc));
2006 return rc;
2007}
2008
2009/** @copydoc VDIMAGEBACKEND::pfnGetComment */
2010static DECLCALLBACK(int) vdiGetComment(void *pBackendData, char *pszComment,
2011 size_t cbComment)
2012{
2013 LogFlowFunc(("pBackendData=%#p pszComment=%#p cbComment=%zu\n", pBackendData, pszComment, cbComment));
2014 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
2015
2016 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
2017
2018 int rc = VINF_SUCCESS;
2019 char *pszTmp = getImageComment(&pImage->Header);
2020 /* Make this foolproof even if the image doesn't have the zero
2021 * termination. With some luck the repaired header will be saved. */
2022 size_t cb = RTStrNLen(pszTmp, VDI_IMAGE_COMMENT_SIZE);
2023 if (cb == VDI_IMAGE_COMMENT_SIZE)
2024 {
2025 pszTmp[VDI_IMAGE_COMMENT_SIZE-1] = '\0';
2026 cb--;
2027 }
2028 if (cb < cbComment)
2029 {
2030 /* memcpy is much better than strncpy. */
2031 memcpy(pszComment, pszTmp, cb + 1);
2032 }
2033 else
2034 rc = VERR_BUFFER_OVERFLOW;
2035
2036 LogFlowFunc(("returns %Rrc comment=\"%s\"\n", rc, pszComment));
2037 return rc;
2038}
2039
2040/** @copydoc VDIMAGEBACKEND::pfnSetComment */
2041static DECLCALLBACK(int) vdiSetComment(void *pBackendData, const char *pszComment)
2042{
2043 LogFlowFunc(("pBackendData=%#p pszComment=\"%s\"\n", pBackendData, pszComment));
2044 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
2045 int rc;
2046
2047 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
2048
2049 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
2050 {
2051 size_t cchComment = pszComment ? strlen(pszComment) : 0;
2052 if (cchComment < VDI_IMAGE_COMMENT_SIZE)
2053 {
2054 /* we don't support old style images */
2055 if (GET_MAJOR_HEADER_VERSION(&pImage->Header) == 1)
2056 {
2057 /*
2058 * Update the comment field, making sure to zero out all of the previous comment.
2059 */
2060 memset(pImage->Header.u.v1.szComment, '\0', VDI_IMAGE_COMMENT_SIZE);
2061 memcpy(pImage->Header.u.v1.szComment, pszComment, cchComment);
2062
2063 /* write out new the header */
2064 rc = vdiUpdateHeader(pImage);
2065 }
2066 else
2067 rc = VERR_VD_VDI_UNSUPPORTED_VERSION;
2068 }
2069 else
2070 {
2071 LogFunc(("pszComment is too long, %d bytes!\n", cchComment));
2072 rc = VERR_VD_VDI_COMMENT_TOO_LONG;
2073 }
2074 }
2075 else
2076 rc = VERR_VD_IMAGE_READ_ONLY;
2077
2078 LogFlowFunc(("returns %Rrc\n", rc));
2079 return rc;
2080}
2081
2082/** @copydoc VDIMAGEBACKEND::pfnGetUuid */
2083static DECLCALLBACK(int) vdiGetUuid(void *pBackendData, PRTUUID pUuid)
2084{
2085 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
2086 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
2087
2088 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
2089
2090 *pUuid = *getImageCreationUUID(&pImage->Header);
2091
2092 LogFlowFunc(("returns %Rrc (%RTuuid)\n", VINF_SUCCESS, pUuid));
2093 return VINF_SUCCESS;
2094}
2095
2096/** @copydoc VDIMAGEBACKEND::pfnSetUuid */
2097static DECLCALLBACK(int) vdiSetUuid(void *pBackendData, PCRTUUID pUuid)
2098{
2099 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
2100 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
2101
2102 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
2103
2104 int rc = VINF_SUCCESS;
2105 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
2106 {
2107 if (GET_MAJOR_HEADER_VERSION(&pImage->Header) == 1)
2108 pImage->Header.u.v1.uuidCreate = *pUuid;
2109 /* Make it possible to clone old VDIs. */
2110 else if (GET_MAJOR_HEADER_VERSION(&pImage->Header) == 0)
2111 pImage->Header.u.v0.uuidCreate = *pUuid;
2112 else
2113 {
2114 LogFunc(("Version is not supported!\n"));
2115 rc = VERR_VD_VDI_UNSUPPORTED_VERSION;
2116 }
2117 }
2118 else
2119 rc = VERR_VD_IMAGE_READ_ONLY;
2120
2121 LogFlowFunc(("returns %Rrc\n", rc));
2122 return rc;
2123}
2124
2125/** @copydoc VDIMAGEBACKEND::pfnGetModificationUuid */
2126static DECLCALLBACK(int) vdiGetModificationUuid(void *pBackendData, PRTUUID pUuid)
2127{
2128 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
2129 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
2130
2131 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
2132
2133 *pUuid = *getImageModificationUUID(&pImage->Header);
2134
2135 LogFlowFunc(("returns %Rrc (%RTuuid)\n", VINF_SUCCESS, pUuid));
2136 return VINF_SUCCESS;
2137}
2138
2139/** @copydoc VDIMAGEBACKEND::pfnSetModificationUuid */
2140static DECLCALLBACK(int) vdiSetModificationUuid(void *pBackendData, PCRTUUID pUuid)
2141{
2142 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
2143 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
2144
2145 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
2146
2147 int rc = VINF_SUCCESS;
2148 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
2149 {
2150 if (GET_MAJOR_HEADER_VERSION(&pImage->Header) == 1)
2151 pImage->Header.u.v1.uuidModify = *pUuid;
2152 /* Make it possible to clone old VDIs. */
2153 else if (GET_MAJOR_HEADER_VERSION(&pImage->Header) == 0)
2154 pImage->Header.u.v0.uuidModify = *pUuid;
2155 else
2156 {
2157 LogFunc(("Version is not supported!\n"));
2158 rc = VERR_VD_VDI_UNSUPPORTED_VERSION;
2159 }
2160 }
2161 else
2162 rc = VERR_VD_IMAGE_READ_ONLY;
2163
2164 LogFlowFunc(("returns %Rrc\n", rc));
2165 return rc;
2166}
2167
2168/** @copydoc VDIMAGEBACKEND::pfnGetParentUuid */
2169static DECLCALLBACK(int) vdiGetParentUuid(void *pBackendData, PRTUUID pUuid)
2170{
2171 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
2172 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
2173
2174 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
2175
2176 *pUuid = *getImageParentUUID(&pImage->Header);
2177
2178 LogFlowFunc(("returns %Rrc (%RTuuid)\n", VINF_SUCCESS, pUuid));
2179 return VINF_SUCCESS;
2180}
2181
2182/** @copydoc VDIMAGEBACKEND::pfnSetParentUuid */
2183static DECLCALLBACK(int) vdiSetParentUuid(void *pBackendData, PCRTUUID pUuid)
2184{
2185 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
2186 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
2187
2188 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
2189
2190 int rc = VINF_SUCCESS;
2191 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
2192 {
2193 if (GET_MAJOR_HEADER_VERSION(&pImage->Header) == 1)
2194 pImage->Header.u.v1.uuidLinkage = *pUuid;
2195 /* Make it possible to clone old VDIs. */
2196 else if (GET_MAJOR_HEADER_VERSION(&pImage->Header) == 0)
2197 pImage->Header.u.v0.uuidLinkage = *pUuid;
2198 else
2199 {
2200 LogFunc(("Version is not supported!\n"));
2201 rc = VERR_VD_VDI_UNSUPPORTED_VERSION;
2202 }
2203 }
2204 else
2205 rc = VERR_VD_IMAGE_READ_ONLY;
2206
2207 LogFlowFunc(("returns %Rrc\n", rc));
2208 return rc;
2209}
2210
2211/** @copydoc VDIMAGEBACKEND::pfnGetParentModificationUuid */
2212static DECLCALLBACK(int) vdiGetParentModificationUuid(void *pBackendData, PRTUUID pUuid)
2213{
2214 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
2215 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
2216
2217 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
2218
2219 *pUuid = *getImageParentModificationUUID(&pImage->Header);
2220
2221 LogFlowFunc(("returns %Rrc (%RTuuid)\n", VINF_SUCCESS, pUuid));
2222 return VINF_SUCCESS;
2223}
2224
2225/** @copydoc VDIMAGEBACKEND::pfnSetParentModificationUuid */
2226static DECLCALLBACK(int) vdiSetParentModificationUuid(void *pBackendData, PCRTUUID pUuid)
2227{
2228 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
2229 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
2230
2231 AssertPtrReturn(pImage, VERR_VD_NOT_OPENED);
2232
2233 int rc = VINF_SUCCESS;
2234 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
2235 {
2236 if (GET_MAJOR_HEADER_VERSION(&pImage->Header) == 1)
2237 pImage->Header.u.v1.uuidParentModify = *pUuid;
2238 else
2239 {
2240 LogFunc(("Version is not supported!\n"));
2241 rc = VERR_VD_VDI_UNSUPPORTED_VERSION;
2242 }
2243 }
2244 else
2245 rc = VERR_VD_IMAGE_READ_ONLY;
2246
2247 LogFlowFunc(("returns %Rrc\n", rc));
2248 return rc;
2249}
2250
2251/** @copydoc VDIMAGEBACKEND::pfnDump */
2252static DECLCALLBACK(void) vdiDump(void *pBackendData)
2253{
2254 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
2255
2256 AssertPtrReturnVoid(pImage);
2257 vdIfErrorMessage(pImage->pIfError, "Dumping VDI image \"%s\" mode=%s uOpenFlags=%X File=%#p\n",
2258 pImage->pszFilename,
2259 (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY) ? "r/o" : "r/w",
2260 pImage->uOpenFlags,
2261 pImage->pStorage);
2262 vdIfErrorMessage(pImage->pIfError, "Header: Version=%08X Type=%X Flags=%X Size=%llu\n",
2263 pImage->PreHeader.u32Version,
2264 getImageType(&pImage->Header),
2265 getImageFlags(&pImage->Header),
2266 getImageDiskSize(&pImage->Header));
2267 vdIfErrorMessage(pImage->pIfError, "Header: cbBlock=%u cbBlockExtra=%u cBlocks=%u cBlocksAllocated=%u\n",
2268 getImageBlockSize(&pImage->Header),
2269 getImageExtraBlockSize(&pImage->Header),
2270 getImageBlocks(&pImage->Header),
2271 getImageBlocksAllocated(&pImage->Header));
2272 vdIfErrorMessage(pImage->pIfError, "Header: offBlocks=%u offData=%u\n",
2273 getImageBlocksOffset(&pImage->Header),
2274 getImageDataOffset(&pImage->Header));
2275 PVDIDISKGEOMETRY pg = getImageLCHSGeometry(&pImage->Header);
2276 if (pg)
2277 vdIfErrorMessage(pImage->pIfError, "Header: Geometry: C/H/S=%u/%u/%u cbSector=%u\n",
2278 pg->cCylinders, pg->cHeads, pg->cSectors, pg->cbSector);
2279 vdIfErrorMessage(pImage->pIfError, "Header: uuidCreation={%RTuuid}\n", getImageCreationUUID(&pImage->Header));
2280 vdIfErrorMessage(pImage->pIfError, "Header: uuidModification={%RTuuid}\n", getImageModificationUUID(&pImage->Header));
2281 vdIfErrorMessage(pImage->pIfError, "Header: uuidParent={%RTuuid}\n", getImageParentUUID(&pImage->Header));
2282 if (GET_MAJOR_HEADER_VERSION(&pImage->Header) >= 1)
2283 vdIfErrorMessage(pImage->pIfError, "Header: uuidParentModification={%RTuuid}\n", getImageParentModificationUUID(&pImage->Header));
2284 vdIfErrorMessage(pImage->pIfError, "Image: fFlags=%08X offStartBlocks=%u offStartData=%u\n",
2285 pImage->uImageFlags, pImage->offStartBlocks, pImage->offStartData);
2286 vdIfErrorMessage(pImage->pIfError, "Image: uBlockMask=%08X cbTotalBlockData=%u uShiftOffset2Index=%u offStartBlockData=%u\n",
2287 pImage->uBlockMask,
2288 pImage->cbTotalBlockData,
2289 pImage->uShiftOffset2Index,
2290 pImage->offStartBlockData);
2291
2292 unsigned uBlock, cBlocksNotFree, cBadBlocks, cBlocks = getImageBlocks(&pImage->Header);
2293 for (uBlock=0, cBlocksNotFree=0, cBadBlocks=0; uBlock<cBlocks; uBlock++)
2294 {
2295 if (IS_VDI_IMAGE_BLOCK_ALLOCATED(pImage->paBlocks[uBlock]))
2296 {
2297 cBlocksNotFree++;
2298 if (pImage->paBlocks[uBlock] >= cBlocks)
2299 cBadBlocks++;
2300 }
2301 }
2302 if (cBlocksNotFree != getImageBlocksAllocated(&pImage->Header))
2303 {
2304 vdIfErrorMessage(pImage->pIfError, "!! WARNING: %u blocks actually allocated (cBlocksAllocated=%u) !!\n",
2305 cBlocksNotFree, getImageBlocksAllocated(&pImage->Header));
2306 }
2307 if (cBadBlocks)
2308 {
2309 vdIfErrorMessage(pImage->pIfError, "!! WARNING: %u bad blocks found !!\n",
2310 cBadBlocks);
2311 }
2312}
2313
2314/** @copydoc VDIMAGEBACKEND::pfnCompact */
2315static DECLCALLBACK(int) vdiCompact(void *pBackendData, unsigned uPercentStart,
2316 unsigned uPercentSpan, PVDINTERFACE pVDIfsDisk,
2317 PVDINTERFACE pVDIfsImage, PVDINTERFACE pVDIfsOperation)
2318{
2319 RT_NOREF2(pVDIfsDisk, pVDIfsImage);
2320 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
2321 int rc = VINF_SUCCESS;
2322 void *pvBuf = NULL, *pvTmp = NULL;
2323 unsigned *paBlocks2 = NULL;
2324
2325 PFNVDPARENTREAD pfnParentRead = NULL;
2326 void *pvParent = NULL;
2327 PVDINTERFACEPARENTSTATE pIfParentState = VDIfParentStateGet(pVDIfsOperation);
2328 if (pIfParentState)
2329 {
2330 pfnParentRead = pIfParentState->pfnParentRead;
2331 pvParent = pIfParentState->Core.pvUser;
2332 }
2333
2334 PVDINTERFACEPROGRESS pIfProgress = VDIfProgressGet(pVDIfsOperation);
2335 PVDINTERFACEQUERYRANGEUSE pIfQueryRangeUse = VDIfQueryRangeUseGet(pVDIfsOperation);
2336
2337 do
2338 {
2339 AssertBreakStmt(pImage, rc = VERR_INVALID_PARAMETER);
2340
2341 AssertBreakStmt(!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY),
2342 rc = VERR_VD_IMAGE_READ_ONLY);
2343
2344 unsigned cBlocks;
2345 unsigned cBlocksToMove = 0;
2346 size_t cbBlock;
2347 cBlocks = getImageBlocks(&pImage->Header);
2348 cbBlock = getImageBlockSize(&pImage->Header);
2349 if (pfnParentRead)
2350 {
2351 pvBuf = RTMemTmpAlloc(cbBlock);
2352 AssertBreakStmt(pvBuf, rc = VERR_NO_MEMORY);
2353 }
2354 pvTmp = RTMemTmpAlloc(cbBlock);
2355 AssertBreakStmt(pvTmp, rc = VERR_NO_MEMORY);
2356
2357 uint64_t cbFile;
2358 rc = vdIfIoIntFileGetSize(pImage->pIfIo, pImage->pStorage, &cbFile);
2359 AssertRCBreak(rc);
2360 unsigned cBlocksAllocated = (unsigned)((cbFile - pImage->offStartData - pImage->offStartBlockData) >> pImage->uShiftOffset2Index);
2361 if (cBlocksAllocated == 0)
2362 {
2363 /* No data blocks in this image, no need to compact. */
2364 rc = VINF_SUCCESS;
2365 break;
2366 }
2367
2368 /* Allocate block array for back resolving. */
2369 paBlocks2 = (unsigned *)RTMemAlloc(sizeof(unsigned *) * cBlocksAllocated);
2370 AssertBreakStmt(paBlocks2, rc = VERR_NO_MEMORY);
2371 /* Fill out back resolving, check/fix allocation errors before
2372 * compacting the image, just to be on the safe side. Update the
2373 * image contents straight away, as this enables cancelling. */
2374 for (unsigned i = 0; i < cBlocksAllocated; i++)
2375 paBlocks2[i] = VDI_IMAGE_BLOCK_FREE;
2376 rc = VINF_SUCCESS;
2377 for (unsigned i = 0; i < cBlocks; i++)
2378 {
2379 VDIIMAGEBLOCKPOINTER ptrBlock = pImage->paBlocks[i];
2380 if (IS_VDI_IMAGE_BLOCK_ALLOCATED(ptrBlock))
2381 {
2382 if (ptrBlock < cBlocksAllocated)
2383 {
2384 if (paBlocks2[ptrBlock] == VDI_IMAGE_BLOCK_FREE)
2385 paBlocks2[ptrBlock] = i;
2386 else
2387 {
2388 LogFunc(("Freed cross-linked block %u in file \"%s\"\n",
2389 i, pImage->pszFilename));
2390 pImage->paBlocks[i] = VDI_IMAGE_BLOCK_FREE;
2391 rc = vdiUpdateBlockInfo(pImage, i);
2392 if (RT_FAILURE(rc))
2393 break;
2394 }
2395 }
2396 else
2397 {
2398 LogFunc(("Freed out of bounds reference for block %u in file \"%s\"\n",
2399 i, pImage->pszFilename));
2400 pImage->paBlocks[i] = VDI_IMAGE_BLOCK_FREE;
2401 rc = vdiUpdateBlockInfo(pImage, i);
2402 if (RT_FAILURE(rc))
2403 break;
2404 }
2405 }
2406 }
2407 if (RT_FAILURE(rc))
2408 break;
2409
2410 /* Find redundant information and update the block pointers
2411 * accordingly, creating bubbles. Keep disk up to date, as this
2412 * enables cancelling. */
2413 for (unsigned i = 0; i < cBlocks; i++)
2414 {
2415 VDIIMAGEBLOCKPOINTER ptrBlock = pImage->paBlocks[i];
2416 if (IS_VDI_IMAGE_BLOCK_ALLOCATED(ptrBlock))
2417 {
2418 /* Block present in image file, read relevant data. */
2419 uint64_t u64Offset = (uint64_t)ptrBlock * pImage->cbTotalBlockData
2420 + (pImage->offStartData + pImage->offStartBlockData);
2421 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pImage->pStorage, u64Offset, pvTmp, cbBlock);
2422 if (RT_FAILURE(rc))
2423 break;
2424
2425 if (ASMBitFirstSet((volatile void *)pvTmp, (uint32_t)cbBlock * 8) == -1)
2426 {
2427 pImage->paBlocks[i] = VDI_IMAGE_BLOCK_ZERO;
2428 rc = vdiUpdateBlockInfo(pImage, i);
2429 if (RT_FAILURE(rc))
2430 break;
2431 paBlocks2[ptrBlock] = VDI_IMAGE_BLOCK_FREE;
2432 /* Adjust progress info, one block to be relocated. */
2433 cBlocksToMove++;
2434 }
2435 else if (pfnParentRead)
2436 {
2437 rc = pfnParentRead(pvParent, (uint64_t)i * cbBlock, pvBuf, cbBlock);
2438 if (RT_FAILURE(rc))
2439 break;
2440 if (!memcmp(pvTmp, pvBuf, cbBlock))
2441 {
2442 pImage->paBlocks[i] = VDI_IMAGE_BLOCK_FREE;
2443 rc = vdiUpdateBlockInfo(pImage, i);
2444 if (RT_FAILURE(rc))
2445 break;
2446 paBlocks2[ptrBlock] = VDI_IMAGE_BLOCK_FREE;
2447 /* Adjust progress info, one block to be relocated. */
2448 cBlocksToMove++;
2449 }
2450 }
2451 }
2452
2453 /* Check if the range is in use if the block is still allocated. */
2454 ptrBlock = pImage->paBlocks[i];
2455 if ( IS_VDI_IMAGE_BLOCK_ALLOCATED(ptrBlock)
2456 && pIfQueryRangeUse)
2457 {
2458 bool fUsed = true;
2459
2460 rc = vdIfQueryRangeUse(pIfQueryRangeUse, (uint64_t)i * cbBlock, cbBlock, &fUsed);
2461 if (RT_FAILURE(rc))
2462 break;
2463 if (!fUsed)
2464 {
2465 pImage->paBlocks[i] = VDI_IMAGE_BLOCK_ZERO;
2466 rc = vdiUpdateBlockInfo(pImage, i);
2467 if (RT_FAILURE(rc))
2468 break;
2469 paBlocks2[ptrBlock] = VDI_IMAGE_BLOCK_FREE;
2470 /* Adjust progress info, one block to be relocated. */
2471 cBlocksToMove++;
2472 }
2473 }
2474
2475 vdIfProgress(pIfProgress, (uint64_t)i * uPercentSpan / (cBlocks + cBlocksToMove) + uPercentStart);
2476 if (RT_FAILURE(rc))
2477 break;
2478 }
2479 if (RT_FAILURE(rc))
2480 break;
2481
2482 /* Fill bubbles with other data (if available). */
2483 unsigned cBlocksMoved = 0;
2484 unsigned uBlockUsedPos = cBlocksAllocated;
2485 for (unsigned i = 0; i < cBlocksAllocated; i++)
2486 {
2487 unsigned uBlock = paBlocks2[i];
2488 if (uBlock == VDI_IMAGE_BLOCK_FREE)
2489 {
2490 unsigned uBlockData = VDI_IMAGE_BLOCK_FREE;
2491 while (uBlockUsedPos > i && uBlockData == VDI_IMAGE_BLOCK_FREE)
2492 {
2493 uBlockUsedPos--;
2494 uBlockData = paBlocks2[uBlockUsedPos];
2495 }
2496 /* Terminate early if there is no block which needs copying. */
2497 if (uBlockUsedPos == i)
2498 break;
2499 uint64_t u64Offset = (uint64_t)uBlockUsedPos * pImage->cbTotalBlockData
2500 + (pImage->offStartData + pImage->offStartBlockData);
2501 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pImage->pStorage, u64Offset,
2502 pvTmp, cbBlock);
2503 if (RT_FAILURE(rc))
2504 break;
2505
2506 u64Offset = (uint64_t)i * pImage->cbTotalBlockData
2507 + (pImage->offStartData + pImage->offStartBlockData);
2508 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pImage->pStorage, u64Offset,
2509 pvTmp, cbBlock);
2510 if (RT_FAILURE(rc))
2511 break;
2512
2513 pImage->paBlocks[uBlockData] = i;
2514 setImageBlocksAllocated(&pImage->Header, cBlocksAllocated - cBlocksMoved);
2515 rc = vdiUpdateBlockInfo(pImage, uBlockData);
2516 if (RT_FAILURE(rc))
2517 break;
2518 paBlocks2[i] = uBlockData;
2519 paBlocks2[uBlockUsedPos] = VDI_IMAGE_BLOCK_FREE;
2520 cBlocksMoved++;
2521 }
2522
2523 rc = vdIfProgress(pIfProgress, (uint64_t)(cBlocks + cBlocksMoved) * uPercentSpan / (cBlocks + cBlocksToMove) + uPercentStart);
2524 if (RT_FAILURE(rc))
2525 break;
2526 }
2527 if (RT_FAILURE(rc))
2528 break;
2529
2530 /* Update image header. */
2531 setImageBlocksAllocated(&pImage->Header, uBlockUsedPos);
2532 vdiUpdateHeader(pImage);
2533
2534 /* Truncate the image to the proper size to finish compacting. */
2535 rc = vdIfIoIntFileSetSize(pImage->pIfIo, pImage->pStorage,
2536 (uint64_t)uBlockUsedPos * pImage->cbTotalBlockData
2537 + pImage->offStartData + pImage->offStartBlockData);
2538 } while (0);
2539
2540 if (paBlocks2)
2541 RTMemTmpFree(paBlocks2);
2542 if (pvTmp)
2543 RTMemTmpFree(pvTmp);
2544 if (pvBuf)
2545 RTMemTmpFree(pvBuf);
2546
2547 if (RT_SUCCESS(rc))
2548 vdIfProgress(pIfProgress, uPercentStart + uPercentSpan);
2549
2550 LogFlowFunc(("returns %Rrc\n", rc));
2551 return rc;
2552}
2553
2554
2555/** @copydoc VDIMAGEBACKEND::pfnResize */
2556static DECLCALLBACK(int) vdiResize(void *pBackendData, uint64_t cbSize,
2557 PCVDGEOMETRY pPCHSGeometry, PCVDGEOMETRY pLCHSGeometry,
2558 unsigned uPercentStart, unsigned uPercentSpan,
2559 PVDINTERFACE pVDIfsDisk, PVDINTERFACE pVDIfsImage,
2560 PVDINTERFACE pVDIfsOperation)
2561{
2562 RT_NOREF5(uPercentStart, uPercentSpan, pVDIfsDisk, pVDIfsImage, pVDIfsOperation);
2563 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
2564 int rc = VINF_SUCCESS;
2565
2566 /* Check size. Maximum 4PB-3M. No tricks with adjusting the 1M block size
2567 * so far, which would extend the size. */
2568 if ( cbSize >= _1P * 4 - _1M * 3
2569 || cbSize < VDI_IMAGE_DEFAULT_BLOCK_SIZE)
2570 return VERR_VD_INVALID_SIZE;
2571
2572 /*
2573 * Making the image smaller is not supported at the moment.
2574 * Resizing is also not supported for fixed size images and
2575 * very old images.
2576 */
2577 /** @todo implement making the image smaller, it is the responsibility of
2578 * the user to know what he's doing. */
2579 if (cbSize < getImageDiskSize(&pImage->Header))
2580 rc = VERR_VD_SHRINK_NOT_SUPPORTED;
2581 else if ( GET_MAJOR_HEADER_VERSION(&pImage->Header) == 0
2582 || pImage->uImageFlags & VD_IMAGE_FLAGS_FIXED)
2583 rc = VERR_NOT_SUPPORTED;
2584 else if (cbSize > getImageDiskSize(&pImage->Header))
2585 {
2586 unsigned cBlocksAllocated = getImageBlocksAllocated(&pImage->Header); /** < Blocks currently allocated, doesn't change during resize */
2587 unsigned const cbBlock = getImageBlockSize(&pImage->Header);
2588 uint32_t cBlocksNew = cbSize / cbBlock; /** < New number of blocks in the image after the resize */
2589 if (cbSize % cbBlock)
2590 cBlocksNew++;
2591
2592 uint32_t cBlocksOld = getImageBlocks(&pImage->Header); /** < Number of blocks before the resize. */
2593 uint64_t cbBlockspaceNew = cBlocksNew * sizeof(VDIIMAGEBLOCKPOINTER); /** < Required space for the block array after the resize. */
2594 uint64_t offStartDataNew = RT_ALIGN_32(pImage->offStartBlocks + cbBlockspaceNew, VDI_DATA_ALIGN); /** < New start offset for block data after the resize */
2595
2596 if (pImage->offStartData < offStartDataNew)
2597 {
2598 if (cBlocksAllocated > 0)
2599 {
2600 /* Calculate how many sectors need to be relocated. */
2601 uint64_t cbOverlapping = offStartDataNew - pImage->offStartData;
2602 unsigned cBlocksReloc = cbOverlapping / cbBlock;
2603 if (cbOverlapping % cbBlock)
2604 cBlocksReloc++;
2605
2606 /* Since only full blocks can be relocated the new data start is
2607 * determined by moving it block by block. */
2608 cBlocksReloc = RT_MIN(cBlocksReloc, cBlocksAllocated);
2609 offStartDataNew = pImage->offStartData;
2610
2611 /* Do the relocation. */
2612 LogFlow(("Relocating %u blocks\n", cBlocksReloc));
2613
2614 /*
2615 * Get the blocks we need to relocate first, they are appended to the end
2616 * of the image.
2617 */
2618 void *pvBuf = NULL, *pvZero = NULL;
2619 do
2620 {
2621 /* Allocate data buffer. */
2622 pvBuf = RTMemAllocZ(pImage->cbTotalBlockData);
2623 if (!pvBuf)
2624 {
2625 rc = VERR_NO_MEMORY;
2626 break;
2627 }
2628
2629 /* Allocate buffer for overwriting with zeroes. */
2630 pvZero = RTMemAllocZ(pImage->cbTotalBlockData);
2631 if (!pvZero)
2632 {
2633 rc = VERR_NO_MEMORY;
2634 break;
2635 }
2636
2637 for (unsigned i = 0; i < cBlocksReloc; i++)
2638 {
2639 /* Search the index in the block table. */
2640 for (unsigned idxBlock = 0; idxBlock < cBlocksOld; idxBlock++)
2641 {
2642 if (!pImage->paBlocks[idxBlock])
2643 {
2644 /* Read data and append to the end of the image. */
2645 rc = vdIfIoIntFileReadSync(pImage->pIfIo, pImage->pStorage,
2646 offStartDataNew, pvBuf,
2647 pImage->cbTotalBlockData);
2648 if (RT_FAILURE(rc))
2649 break;
2650
2651 uint64_t offBlockAppend;
2652 rc = vdIfIoIntFileGetSize(pImage->pIfIo, pImage->pStorage, &offBlockAppend);
2653 if (RT_FAILURE(rc))
2654 break;
2655
2656 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pImage->pStorage,
2657 offBlockAppend, pvBuf,
2658 pImage->cbTotalBlockData);
2659 if (RT_FAILURE(rc))
2660 break;
2661
2662 /* Zero out the old block area. */
2663 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pImage->pStorage,
2664 offStartDataNew, pvZero,
2665 pImage->cbTotalBlockData);
2666 if (RT_FAILURE(rc))
2667 break;
2668
2669 /* Update block counter. */
2670 pImage->paBlocks[idxBlock] = cBlocksAllocated - 1;
2671
2672 /*
2673 * Decrease the block number of all other entries in the array.
2674 * They were moved one block to the front.
2675 * Doing it as a separate step iterating over the array again
2676 * because an error while relocating the block might end up
2677 * in a corrupted image otherwise.
2678 */
2679 for (unsigned idxBlock2 = 0; idxBlock2 < cBlocksOld; idxBlock2++)
2680 {
2681 if ( idxBlock2 != idxBlock
2682 && IS_VDI_IMAGE_BLOCK_ALLOCATED(pImage->paBlocks[idxBlock2]))
2683 pImage->paBlocks[idxBlock2]--;
2684 }
2685
2686 /* Continue with the next block. */
2687 break;
2688 }
2689 }
2690
2691 if (RT_FAILURE(rc))
2692 break;
2693
2694 offStartDataNew += pImage->cbTotalBlockData;
2695 }
2696 } while (0);
2697
2698 if (pvBuf)
2699 RTMemFree(pvBuf);
2700 if (pvZero)
2701 RTMemFree(pvZero);
2702 }
2703
2704 /*
2705 * We need to update the new offsets for the image data in the out of memory
2706 * case too because we relocated the blocks already.
2707 */
2708 pImage->offStartData = offStartDataNew;
2709 setImageDataOffset(&pImage->Header, offStartDataNew);
2710 }
2711
2712 /*
2713 * Relocation done, expand the block array and update the header with
2714 * the new data.
2715 */
2716 if (RT_SUCCESS(rc))
2717 {
2718 PVDIIMAGEBLOCKPOINTER paBlocksNew = (PVDIIMAGEBLOCKPOINTER)RTMemRealloc(pImage->paBlocks, cbBlockspaceNew);
2719 if (paBlocksNew)
2720 {
2721 pImage->paBlocks = paBlocksNew;
2722
2723 /* Mark the new blocks as unallocated. */
2724 for (unsigned idxBlock = cBlocksOld; idxBlock < cBlocksNew; idxBlock++)
2725 pImage->paBlocks[idxBlock] = VDI_IMAGE_BLOCK_FREE;
2726
2727 /* Write the block array before updating the rest. */
2728 vdiConvBlocksEndianess(VDIECONV_H2F, pImage->paBlocks, cBlocksNew);
2729 rc = vdIfIoIntFileWriteSync(pImage->pIfIo, pImage->pStorage, pImage->offStartBlocks,
2730 pImage->paBlocks, cbBlockspaceNew);
2731 vdiConvBlocksEndianess(VDIECONV_F2H, pImage->paBlocks, cBlocksNew);
2732
2733 if (RT_SUCCESS(rc))
2734 {
2735 /* Update size and new block count. */
2736 setImageDiskSize(&pImage->Header, cbSize);
2737 setImageBlocks(&pImage->Header, cBlocksNew);
2738 /* Update geometry. */
2739 pImage->PCHSGeometry = *pPCHSGeometry;
2740 pImage->cbImage = cbSize;
2741
2742 PVDIDISKGEOMETRY pGeometry = getImageLCHSGeometry(&pImage->Header);
2743 if (pGeometry)
2744 {
2745 pGeometry->cCylinders = pLCHSGeometry->cCylinders;
2746 pGeometry->cHeads = pLCHSGeometry->cHeads;
2747 pGeometry->cSectors = pLCHSGeometry->cSectors;
2748 pGeometry->cbSector = VDI_GEOMETRY_SECTOR_SIZE;
2749 }
2750 }
2751 }
2752 else
2753 rc = VERR_NO_MEMORY;
2754 }
2755
2756 /* Update header information in base image file. */
2757 vdiFlushImage(pImage);
2758 }
2759 /* Same size doesn't change the image at all. */
2760
2761 LogFlowFunc(("returns %Rrc\n", rc));
2762 return rc;
2763}
2764
2765/** @copydoc VDIMAGEBACKEND::pfnDiscard */
2766static DECLCALLBACK(int) vdiDiscard(void *pBackendData, PVDIOCTX pIoCtx,
2767 uint64_t uOffset, size_t cbDiscard,
2768 size_t *pcbPreAllocated, size_t *pcbPostAllocated,
2769 size_t *pcbActuallyDiscarded, void **ppbmAllocationBitmap,
2770 unsigned fDiscard)
2771{
2772 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
2773 unsigned uBlock;
2774 unsigned offDiscard;
2775 int rc = VINF_SUCCESS;
2776 void *pvBlock = NULL;
2777
2778 LogFlowFunc(("pBackendData=%#p pIoCtx=%#p uOffset=%llu cbDiscard=%zu pcbPreAllocated=%#p pcbPostAllocated=%#p pcbActuallyDiscarded=%#p ppbmAllocationBitmap=%#p fDiscard=%#x\n",
2779 pBackendData, pIoCtx, uOffset, cbDiscard, pcbPreAllocated, pcbPostAllocated, pcbActuallyDiscarded, ppbmAllocationBitmap, fDiscard));
2780
2781 AssertPtr(pImage);
2782 Assert(!(uOffset % 512));
2783 Assert(!(cbDiscard % 512));
2784
2785 AssertMsgReturn(!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY),
2786 ("Image is readonly\n"), VERR_VD_IMAGE_READ_ONLY);
2787 AssertMsgReturn( uOffset + cbDiscard <= getImageDiskSize(&pImage->Header)
2788 && cbDiscard,
2789 ("Invalid parameters uOffset=%llu cbDiscard=%zu\n",
2790 uOffset, cbDiscard),
2791 VERR_INVALID_PARAMETER);
2792
2793 do
2794 {
2795 AssertMsgBreakStmt(!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY),
2796 ("Image is opened readonly\n"),
2797 rc = VERR_VD_IMAGE_READ_ONLY);
2798
2799 AssertMsgBreakStmt(cbDiscard,
2800 ("cbDiscard=%u\n", cbDiscard),
2801 rc = VERR_INVALID_PARAMETER);
2802
2803 /* Calculate starting block number and offset inside it. */
2804 uBlock = (unsigned)(uOffset >> pImage->uShiftOffset2Index);
2805 offDiscard = (unsigned)uOffset & pImage->uBlockMask;
2806
2807 /* Clip range to at most the rest of the block. */
2808 size_t cbBlockRem = getImageBlockSize(&pImage->Header) - offDiscard;
2809 cbDiscard = RT_MIN(cbDiscard, cbBlockRem);
2810 Assert(!(cbDiscard % 512));
2811
2812 if (pcbPreAllocated)
2813 *pcbPreAllocated = 0;
2814
2815 if (pcbPostAllocated)
2816 *pcbPostAllocated = 0;
2817
2818 if (IS_VDI_IMAGE_BLOCK_ALLOCATED(pImage->paBlocks[uBlock]))
2819 {
2820 unsigned const cbBlock = getImageBlockSize(&pImage->Header);
2821 size_t const cbPreAllocated = offDiscard % RT_MAX(cbBlock, 1); /* MSVC thinks it is clever and says there is a potential mod by 0 here, hence the RT_MAX... */
2822 size_t const cbPostAllocated = getImageBlockSize(&pImage->Header) - cbDiscard - cbPreAllocated;
2823 uint8_t *pbBlockData;
2824
2825 /* Read the block data. */
2826 pvBlock = RTMemAlloc(pImage->cbTotalBlockData);
2827 if (!pvBlock)
2828 {
2829 rc = VERR_NO_MEMORY;
2830 break;
2831 }
2832
2833 if (!cbPreAllocated && !cbPostAllocated)
2834 {
2835 /*
2836 * Discarding a whole block, don't check for allocated sectors.
2837 * It is possible to just remove the whole block which avoids
2838 * one read and checking the whole block for data.
2839 */
2840 rc = vdiDiscardBlockAsync(pImage, pIoCtx, uBlock, pvBlock);
2841 }
2842 else if (fDiscard & VD_DISCARD_MARK_UNUSED)
2843 {
2844 /* Just zero out the given range. */
2845 memset(pvBlock, 0, cbDiscard);
2846
2847 uint64_t u64Offset = (uint64_t)pImage->paBlocks[uBlock] * pImage->cbTotalBlockData + pImage->offStartData + offDiscard;
2848 rc = vdIfIoIntFileWriteMeta(pImage->pIfIo, pImage->pStorage,
2849 u64Offset, pvBlock, cbDiscard, pIoCtx,
2850 NULL, NULL);
2851 RTMemFree(pvBlock);
2852 }
2853 else
2854 {
2855 /*
2856 * Read complete block as metadata, the I/O context has no memory buffer
2857 * and we need to access the content directly anyway.
2858 */
2859 PVDMETAXFER pMetaXfer;
2860 pbBlockData = (uint8_t *)pvBlock + pImage->offStartBlockData;
2861
2862 uint64_t u64Offset = (uint64_t)pImage->paBlocks[uBlock] * pImage->cbTotalBlockData + pImage->offStartData;
2863 rc = vdIfIoIntFileReadMeta(pImage->pIfIo, pImage->pStorage, u64Offset,
2864 pbBlockData, pImage->cbTotalBlockData,
2865 pIoCtx, &pMetaXfer, NULL, NULL);
2866 if (RT_FAILURE(rc))
2867 {
2868 RTMemFree(pvBlock);
2869 break;
2870 }
2871
2872 vdIfIoIntMetaXferRelease(pImage->pIfIo, pMetaXfer);
2873
2874 /* Clear data. */
2875 memset(pbBlockData + offDiscard , 0, cbDiscard);
2876
2877 Assert(!(cbDiscard % 4));
2878 Assert(getImageBlockSize(&pImage->Header) * 8 <= UINT32_MAX);
2879 if (ASMBitFirstSet((volatile void *)pbBlockData, getImageBlockSize(&pImage->Header) * 8) == -1)
2880 rc = vdiDiscardBlockAsync(pImage, pIoCtx, uBlock, pvBlock);
2881 else
2882 {
2883 /* Block has data, create allocation bitmap. */
2884 *pcbPreAllocated = cbPreAllocated;
2885 *pcbPostAllocated = cbPostAllocated;
2886 *ppbmAllocationBitmap = vdiAllocationBitmapCreate(pbBlockData, getImageBlockSize(&pImage->Header));
2887 if (RT_UNLIKELY(!*ppbmAllocationBitmap))
2888 rc = VERR_NO_MEMORY;
2889 else
2890 rc = VERR_VD_DISCARD_ALIGNMENT_NOT_MET;
2891
2892 RTMemFree(pvBlock);
2893 }
2894 } /* if: no complete block discarded */
2895 } /* if: Block is allocated. */
2896 /* else: nothing to do. */
2897 } while (0);
2898
2899 if (pcbActuallyDiscarded)
2900 *pcbActuallyDiscarded = cbDiscard;
2901
2902 LogFlowFunc(("returns %Rrc\n", rc));
2903 return rc;
2904}
2905
2906/** @copydoc VDIMAGEBACKEND::pfnRepair */
2907static DECLCALLBACK(int) vdiRepair(const char *pszFilename, PVDINTERFACE pVDIfsDisk,
2908 PVDINTERFACE pVDIfsImage, uint32_t fFlags)
2909{
2910 LogFlowFunc(("pszFilename=\"%s\" pVDIfsDisk=%#p pVDIfsImage=%#p\n", pszFilename, pVDIfsDisk, pVDIfsImage));
2911 int rc;
2912 PVDINTERFACEERROR pIfError;
2913 PVDINTERFACEIOINT pIfIo;
2914 PVDIOSTORAGE pStorage = NULL;
2915 uint64_t cbFile;
2916 PVDIIMAGEBLOCKPOINTER paBlocks = NULL;
2917 uint32_t *pu32BlockBitmap = NULL;
2918 VDIPREHEADER PreHdr;
2919 VDIHEADER Hdr;
2920
2921 pIfIo = VDIfIoIntGet(pVDIfsImage);
2922 AssertPtrReturn(pIfIo, VERR_INVALID_PARAMETER);
2923
2924 pIfError = VDIfErrorGet(pVDIfsDisk);
2925
2926 do
2927 {
2928 bool fRepairBlockArray = false;
2929 bool fRepairHdr = false;
2930
2931 rc = vdIfIoIntFileOpen(pIfIo, pszFilename,
2932 VDOpenFlagsToFileOpenFlags( fFlags & VD_REPAIR_DRY_RUN
2933 ? VD_OPEN_FLAGS_READONLY
2934 : 0,
2935 false /* fCreate */),
2936 &pStorage);
2937 if (RT_FAILURE(rc))
2938 {
2939 rc = vdIfError(pIfError, rc, RT_SRC_POS, "VDI: Failed to open image \"%s\"", pszFilename);
2940 break;
2941 }
2942
2943 rc = vdIfIoIntFileGetSize(pIfIo, pStorage, &cbFile);
2944 if (RT_FAILURE(rc))
2945 {
2946 rc = vdIfError(pIfError, rc, RT_SRC_POS, "VDI: Failed to query image size");
2947 break;
2948 }
2949
2950 /* Read pre-header. */
2951 rc = vdIfIoIntFileReadSync(pIfIo, pStorage, 0, &PreHdr, sizeof(PreHdr));
2952 if (RT_FAILURE(rc))
2953 {
2954 rc = vdIfError(pIfError, rc, RT_SRC_POS, N_("VDI: Error reading pre-header in '%s'"), pszFilename);
2955 break;
2956 }
2957 vdiConvPreHeaderEndianess(VDIECONV_F2H, &PreHdr, &PreHdr);
2958 rc = vdiValidatePreHeader(&PreHdr);
2959 if (RT_FAILURE(rc))
2960 {
2961 rc = vdIfError(pIfError, VERR_VD_IMAGE_REPAIR_IMPOSSIBLE, RT_SRC_POS,
2962 N_("VDI: invalid pre-header in '%s'"), pszFilename);
2963 break;
2964 }
2965
2966 /* Read header. */
2967 Hdr.uVersion = PreHdr.u32Version;
2968 switch (GET_MAJOR_HEADER_VERSION(&Hdr))
2969 {
2970 case 0:
2971 rc = vdIfIoIntFileReadSync(pIfIo, pStorage, sizeof(PreHdr),
2972 &Hdr.u.v0, sizeof(Hdr.u.v0));
2973 if (RT_FAILURE(rc))
2974 rc = vdIfError(pIfError, rc, RT_SRC_POS, N_("VDI: error reading v0 header in '%s'"),
2975 pszFilename);
2976 vdiConvHeaderEndianessV0(VDIECONV_F2H, &Hdr.u.v0, &Hdr.u.v0);
2977 break;
2978 case 1:
2979 rc = vdIfIoIntFileReadSync(pIfIo, pStorage, sizeof(PreHdr),
2980 &Hdr.u.v1, sizeof(Hdr.u.v1));
2981 if (RT_FAILURE(rc))
2982 {
2983 rc = vdIfError(pIfError, rc, RT_SRC_POS, N_("VDI: error reading v1 header in '%s'"),
2984 pszFilename);
2985 }
2986 vdiConvHeaderEndianessV1(VDIECONV_F2H, &Hdr.u.v1, &Hdr.u.v1);
2987 if (Hdr.u.v1.cbHeader >= sizeof(Hdr.u.v1plus))
2988 {
2989 /* Read the VDI 1.1+ header completely. */
2990 rc = vdIfIoIntFileReadSync(pIfIo, pStorage, sizeof(PreHdr),
2991 &Hdr.u.v1plus, sizeof(Hdr.u.v1plus));
2992 if (RT_FAILURE(rc))
2993 rc = vdIfError(pIfError, rc, RT_SRC_POS, N_("VDI: error reading v1.1+ header in '%s'"),
2994 pszFilename);
2995 vdiConvHeaderEndianessV1p(VDIECONV_F2H, &Hdr.u.v1plus, &Hdr.u.v1plus);
2996 }
2997 break;
2998 default:
2999 rc = vdIfError(pIfError, VERR_VD_IMAGE_REPAIR_IMPOSSIBLE, RT_SRC_POS,
3000 N_("VDI: unsupported major version %u in '%s'"),
3001 GET_MAJOR_HEADER_VERSION(&Hdr), pszFilename);
3002 break;
3003 }
3004
3005 if (RT_SUCCESS(rc))
3006 {
3007 rc = vdiValidateHeader(&Hdr);
3008 if (RT_FAILURE(rc))
3009 {
3010 rc = vdIfError(pIfError, VERR_VD_IMAGE_REPAIR_IMPOSSIBLE, RT_SRC_POS,
3011 N_("VDI: invalid header in '%s'"), pszFilename);
3012 break;
3013 }
3014 }
3015
3016 /*
3017 * Check that the disk size is correctly aligned,
3018 * see comment above the same check in vdiImageReadHeader().
3019 */
3020 uint64_t cbDisk = getImageDiskSize(&Hdr);
3021 if (cbDisk & 0x1ff)
3022 {
3023 uint64_t cbDiskNew = cbDisk & ~UINT64_C(0x1ff);
3024 vdIfErrorMessage(pIfError, "Disk size in the header is not sector aligned, rounding down (%llu -> %llu)\n",
3025 cbDisk, cbDiskNew);
3026 setImageDiskSize(&Hdr, cbDiskNew);
3027 fRepairHdr = true;
3028 }
3029
3030 /* Setup image parameters by header. */
3031 uint64_t offStartBlocks, offStartData;
3032 size_t cbTotalBlockData;
3033
3034 offStartBlocks = getImageBlocksOffset(&Hdr);
3035 offStartData = getImageDataOffset(&Hdr);
3036 cbTotalBlockData = getImageExtraBlockSize(&Hdr) + getImageBlockSize(&Hdr);
3037
3038 /* Allocate memory for blocks array. */
3039 paBlocks = (PVDIIMAGEBLOCKPOINTER)RTMemAlloc(sizeof(VDIIMAGEBLOCKPOINTER) * getImageBlocks(&Hdr));
3040 if (!paBlocks)
3041 {
3042 rc = vdIfError(pIfError, VERR_NO_MEMORY, RT_SRC_POS,
3043 "Failed to allocate memory for block array");
3044 break;
3045 }
3046
3047 /* Read blocks array. */
3048 rc = vdIfIoIntFileReadSync(pIfIo, pStorage, offStartBlocks, paBlocks,
3049 getImageBlocks(&Hdr) * sizeof(VDIIMAGEBLOCKPOINTER));
3050 if (RT_FAILURE(rc))
3051 {
3052 rc = vdIfError(pIfError, VERR_VD_IMAGE_REPAIR_IMPOSSIBLE, RT_SRC_POS,
3053 "Failed to read block array (at %llu), %Rrc",
3054 offStartBlocks, rc);
3055 break;
3056 }
3057 vdiConvBlocksEndianess(VDIECONV_F2H, paBlocks, getImageBlocks(&Hdr));
3058
3059 pu32BlockBitmap = (uint32_t *)RTMemAllocZ(RT_ALIGN_Z(getImageBlocks(&Hdr) / 8, 4));
3060 if (!pu32BlockBitmap)
3061 {
3062 rc = vdIfError(pIfError, VERR_NO_MEMORY, RT_SRC_POS,
3063 "Failed to allocate memory for block bitmap");
3064 break;
3065 }
3066
3067 for (uint32_t i = 0; i < getImageBlocks(&Hdr); i++)
3068 {
3069 if (IS_VDI_IMAGE_BLOCK_ALLOCATED(paBlocks[i]))
3070 {
3071 uint64_t offBlock = (uint64_t)paBlocks[i] * cbTotalBlockData
3072 + offStartData;
3073
3074 /*
3075 * Check that the offsets are valid (inside of the image) and
3076 * that there are no double references.
3077 */
3078 if (offBlock + cbTotalBlockData > cbFile)
3079 {
3080 vdIfErrorMessage(pIfError, "Entry %u points to invalid offset %llu, clearing\n",
3081 i, offBlock);
3082 paBlocks[i] = VDI_IMAGE_BLOCK_FREE;
3083 fRepairBlockArray = true;
3084 }
3085 else if (ASMBitTestAndSet(pu32BlockBitmap, paBlocks[i]))
3086 {
3087 vdIfErrorMessage(pIfError, "Entry %u points to an already referenced data block, clearing\n",
3088 i);
3089 paBlocks[i] = VDI_IMAGE_BLOCK_FREE;
3090 fRepairBlockArray = true;
3091 }
3092 }
3093 }
3094
3095 /* Write repaired structures now. */
3096 if (!fRepairBlockArray && !fRepairHdr)
3097 vdIfErrorMessage(pIfError, "VDI image is in a consistent state, no repair required\n");
3098 else if (!(fFlags & VD_REPAIR_DRY_RUN))
3099 {
3100 if (fRepairHdr)
3101 {
3102 switch (GET_MAJOR_HEADER_VERSION(&Hdr))
3103 {
3104 case 0:
3105 {
3106 VDIHEADER0 Hdr0;
3107 vdiConvHeaderEndianessV0(VDIECONV_H2F, &Hdr0, &Hdr.u.v0);
3108 rc = vdIfIoIntFileWriteSync(pIfIo, pStorage, sizeof(VDIPREHEADER),
3109 &Hdr0, sizeof(Hdr0));
3110 break;
3111 }
3112 case 1:
3113 if (Hdr.u.v1plus.cbHeader < sizeof(Hdr.u.v1plus))
3114 {
3115 VDIHEADER1 Hdr1;
3116 vdiConvHeaderEndianessV1(VDIECONV_H2F, &Hdr1, &Hdr.u.v1);
3117 rc = vdIfIoIntFileWriteSync(pIfIo, pStorage, sizeof(VDIPREHEADER),
3118 &Hdr1, sizeof(Hdr1));
3119 }
3120 else
3121 {
3122 VDIHEADER1PLUS Hdr1plus;
3123 vdiConvHeaderEndianessV1p(VDIECONV_H2F, &Hdr1plus, &Hdr.u.v1plus);
3124 rc = vdIfIoIntFileWriteSync(pIfIo, pStorage, sizeof(VDIPREHEADER),
3125 &Hdr1plus, sizeof(Hdr1plus));
3126 }
3127 break;
3128 default:
3129 AssertMsgFailed(("Header indicates unsupported version which should not happen here!\n"));
3130 rc = VERR_VD_VDI_UNSUPPORTED_VERSION;
3131 break;
3132 }
3133 }
3134
3135 if (fRepairBlockArray)
3136 {
3137 vdIfErrorMessage(pIfError, "Writing repaired block allocation table...\n");
3138
3139 vdiConvBlocksEndianess(VDIECONV_H2F, paBlocks, getImageBlocks(&Hdr));
3140 rc = vdIfIoIntFileWriteSync(pIfIo, pStorage, offStartBlocks, paBlocks,
3141 getImageBlocks(&Hdr) * sizeof(VDIIMAGEBLOCKPOINTER));
3142 if (RT_FAILURE(rc))
3143 {
3144 rc = vdIfError(pIfError, VERR_VD_IMAGE_REPAIR_IMPOSSIBLE, RT_SRC_POS,
3145 "Could not write repaired block allocation table (at %llu), %Rrc",
3146 offStartBlocks, rc);
3147 break;
3148 }
3149 }
3150 }
3151
3152 vdIfErrorMessage(pIfError, "Corrupted VDI image repaired successfully\n");
3153 } while(0);
3154
3155 if (paBlocks)
3156 RTMemFree(paBlocks);
3157
3158 if (pu32BlockBitmap)
3159 RTMemFree(pu32BlockBitmap);
3160
3161 if (pStorage)
3162 {
3163 int rc2 = vdIfIoIntFileClose(pIfIo, pStorage);
3164 if (RT_SUCCESS(rc))
3165 rc = rc2; /* Propagate error code only if repairing was successful. */
3166 }
3167
3168 LogFlowFunc(("returns %Rrc\n", rc));
3169 return rc;
3170}
3171
3172const VDIMAGEBACKEND g_VDIBackend =
3173{
3174 /* u32Version */
3175 VD_IMGBACKEND_VERSION,
3176 /* pszBackendName */
3177 "VDI",
3178 /* uBackendCaps */
3179 VD_CAP_UUID | VD_CAP_CREATE_FIXED | VD_CAP_CREATE_DYNAMIC
3180 | VD_CAP_DIFF | VD_CAP_FILE | VD_CAP_ASYNC | VD_CAP_VFS | VD_CAP_DISCARD
3181 | VD_CAP_PREFERRED,
3182 /* paFileExtensions */
3183 s_aVdiFileExtensions,
3184 /* paConfigInfo */
3185 vdiConfigInfo,
3186 /* pfnProbe */
3187 vdiProbe,
3188 /* pfnOpen */
3189 vdiOpen,
3190 /* pfnCreate */
3191 vdiCreate,
3192 /* pfnRename */
3193 vdiRename,
3194 /* pfnClose */
3195 vdiClose,
3196 /* pfnRead */
3197 vdiRead,
3198 /* pfnWrite */
3199 vdiWrite,
3200 /* pfnFlush */
3201 vdiFlush,
3202 /* pfnDiscard */
3203 vdiDiscard,
3204 /* pfnGetVersion */
3205 vdiGetVersion,
3206 /* pfnGetFileSize */
3207 vdiGetFileSize,
3208 /* pfnGetPCHSGeometry */
3209 vdiGetPCHSGeometry,
3210 /* pfnSetPCHSGeometry */
3211 vdiSetPCHSGeometry,
3212 /* pfnGetLCHSGeometry */
3213 vdiGetLCHSGeometry,
3214 /* pfnSetLCHSGeometry */
3215 vdiSetLCHSGeometry,
3216 /* pfnQueryRegions */
3217 vdiQueryRegions,
3218 /* pfnRegionListRelease */
3219 vdiRegionListRelease,
3220 /* pfnGetImageFlags */
3221 vdiGetImageFlags,
3222 /* pfnGetOpenFlags */
3223 vdiGetOpenFlags,
3224 /* pfnSetOpenFlags */
3225 vdiSetOpenFlags,
3226 /* pfnGetComment */
3227 vdiGetComment,
3228 /* pfnSetComment */
3229 vdiSetComment,
3230 /* pfnGetUuid */
3231 vdiGetUuid,
3232 /* pfnSetUuid */
3233 vdiSetUuid,
3234 /* pfnGetModificationUuid */
3235 vdiGetModificationUuid,
3236 /* pfnSetModificationUuid */
3237 vdiSetModificationUuid,
3238 /* pfnGetParentUuid */
3239 vdiGetParentUuid,
3240 /* pfnSetParentUuid */
3241 vdiSetParentUuid,
3242 /* pfnGetParentModificationUuid */
3243 vdiGetParentModificationUuid,
3244 /* pfnSetParentModificationUuid */
3245 vdiSetParentModificationUuid,
3246 /* pfnDump */
3247 vdiDump,
3248 /* pfnGetTimestamp */
3249 NULL,
3250 /* pfnGetParentTimestamp */
3251 NULL,
3252 /* pfnSetParentTimestamp */
3253 NULL,
3254 /* pfnGetParentFilename */
3255 NULL,
3256 /* pfnSetParentFilename */
3257 NULL,
3258 /* pfnComposeLocation */
3259 genericFileComposeLocation,
3260 /* pfnComposeName */
3261 genericFileComposeName,
3262 /* pfnCompact */
3263 vdiCompact,
3264 /* pfnResize */
3265 vdiResize,
3266 /* pfnRepair */
3267 vdiRepair,
3268 /* pfnTraverseMetadata */
3269 NULL,
3270 /* u32VersionEnd */
3271 VD_IMGBACKEND_VERSION
3272};
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