VirtualBox

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

Last change on this file since 45733 was 45486, checked in by vboxsync, 12 years ago

Storage: Fix unused label and variable warnings

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