VirtualBox

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

Last change on this file since 97405 was 96407, checked in by vboxsync, 2 years ago

scm copyright and license note update

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