VirtualBox

source: vbox/trunk/src/VBox/Devices/Storage/VDIHDDCore.cpp@ 31184

Last change on this file since 31184 was 31184, checked in by vboxsync, 15 years ago

Fix assertion in drvvdSetReadonly

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 88.2 KB
Line 
1/** @file
2 * Virtual Disk Image (VDI), Core Code.
3 */
4
5/*
6 * Copyright (C) 2006-2010 Oracle Corporation
7 *
8 * This file is part of VirtualBox Open Source Edition (OSE), as
9 * available from http://www.virtualbox.org. This file is free software;
10 * you can redistribute it and/or modify it under the terms of the GNU
11 * General Public License (GPL) as published by the Free Software
12 * Foundation, in version 2 as it comes in the "COPYING" file of the
13 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
14 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
15 */
16
17/*******************************************************************************
18* Header Files *
19*******************************************************************************/
20#define LOG_GROUP LOG_GROUP_VD_VDI
21#include <VBox/VBoxHDD-Plugin.h>
22#define VBOX_VDICORE_VD /* Signal that the header is included from here. */
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/file.h>
31#include <iprt/string.h>
32#include <iprt/asm.h>
33
34#define VDI_IMAGE_DEFAULT_BLOCK_SIZE _1M
35
36/*******************************************************************************
37* Static Variables *
38*******************************************************************************/
39
40/** NULL-terminated array of supported file extensions. */
41static const char *const s_apszVdiFileExtensions[] =
42{
43 "vdi",
44 NULL
45};
46
47/*******************************************************************************
48* Internal Functions *
49*******************************************************************************/
50static unsigned getPowerOfTwo(unsigned uNumber);
51static void vdiInitPreHeader(PVDIPREHEADER pPreHdr);
52static int vdiValidatePreHeader(PVDIPREHEADER pPreHdr);
53static void vdiInitHeader(PVDIHEADER pHeader, uint32_t uImageFlags,
54 const char *pszComment, uint64_t cbDisk,
55 uint32_t cbBlock, uint32_t cbBlockExtra);
56static int vdiValidateHeader(PVDIHEADER pHeader);
57static void vdiSetupImageDesc(PVDIIMAGEDESC pImage);
58static int vdiUpdateHeader(PVDIIMAGEDESC pImage);
59static int vdiUpdateBlockInfo(PVDIIMAGEDESC pImage, unsigned uBlock);
60static void vdiFreeImage(PVDIIMAGEDESC pImage, bool fDelete);
61static int vdiUpdateHeaderAsync(PVDIIMAGEDESC pImage, PVDIOCTX pIoCtx);
62static int vdiUpdateBlockInfoAsync(PVDIIMAGEDESC pImage, unsigned uBlock, PVDIOCTX pIoCtx);
63
64/**
65 * Internal: signal an error to the frontend.
66 */
67DECLINLINE(int) vdiError(PVDIIMAGEDESC pImage, int rc, RT_SRC_POS_DECL,
68 const char *pszFormat, ...)
69{
70 va_list va;
71 va_start(va, pszFormat);
72 if (pImage->pInterfaceError && pImage->pInterfaceErrorCallbacks)
73 pImage->pInterfaceErrorCallbacks->pfnError(pImage->pInterfaceError->pvUser,
74 rc, RT_SRC_POS_ARGS,
75 pszFormat, va);
76 va_end(va);
77 return rc;
78}
79
80
81static int vdiFileOpen(PVDIIMAGEDESC pImage, bool fReadonly, bool fShareable,
82 bool fCreate)
83{
84 int rc = VINF_SUCCESS;
85
86 AssertMsg(!(fReadonly && fCreate), ("Image can't be opened readonly while being created\n"));
87
88#ifndef VBOX_WITH_NEW_IO_CODE
89 uint32_t fDeny = fReadonly | fShareable ? RTFILE_O_DENY_NONE : RTFILE_O_DENY_WRITE;
90 uint32_t fOpen = fReadonly ? RTFILE_O_READ : RTFILE_O_READWRITE;
91 fOpen |= fDeny;
92
93 if (fCreate)
94 fOpen |= RTFILE_O_CREATE;
95 else
96 fOpen |= RTFILE_O_OPEN;
97
98 rc = RTFileOpen(&pImage->File, pImage->pszFilename, fOpen);
99#else
100 unsigned uOpenFlags = fReadonly ? VD_INTERFACEASYNCIO_OPEN_FLAGS_READONLY : 0;
101
102 if (fCreate)
103 uOpenFlags |= VD_INTERFACEASYNCIO_OPEN_FLAGS_CREATE;
104
105 rc = pImage->pInterfaceIOCallbacks->pfnOpen(pImage->pInterfaceIO->pvUser,
106 pImage->pszFilename,
107 uOpenFlags,
108 &pImage->pStorage);
109#endif
110
111 return rc;
112}
113
114static int vdiFileClose(PVDIIMAGEDESC pImage)
115{
116 int rc = VINF_SUCCESS;
117
118#ifndef VBOX_WITH_NEW_IO_CODE
119 if (pImage->File != NIL_RTFILE)
120 rc = RTFileClose(pImage->File);
121
122 pImage->File = NIL_RTFILE;
123#else
124 rc = pImage->pInterfaceIOCallbacks->pfnClose(pImage->pInterfaceIO->pvUser,
125 pImage->pStorage);
126
127 pImage->pStorage = NULL;
128#endif
129
130 return rc;
131}
132
133static int vdiFileFlushSync(PVDIIMAGEDESC pImage)
134{
135 int rc = VINF_SUCCESS;
136
137#ifndef VBOX_WITH_NEW_IO_CODE
138 rc = RTFileFlush(pImage->File);
139#else
140 rc = pImage->pInterfaceIOCallbacks->pfnFlushSync(pImage->pInterfaceIO->pvUser,
141 pImage->pStorage);
142#endif
143
144 return rc;
145}
146
147static int vdiFileGetSize(PVDIIMAGEDESC pImage, uint64_t *pcbSize)
148{
149 int rc = VINF_SUCCESS;
150
151#ifndef VBOX_WITH_NEW_IO_CODE
152 rc = RTFileGetSize(pImage->File, pcbSize);
153#else
154 rc = pImage->pInterfaceIOCallbacks->pfnGetSize(pImage->pInterfaceIO->pvUser,
155 pImage->pStorage,
156 pcbSize);
157#endif
158
159 return rc;
160}
161
162static int vdiFileSetSize(PVDIIMAGEDESC pImage, uint64_t cbSize)
163{
164 int rc = VINF_SUCCESS;
165
166#ifndef VBOX_WITH_NEW_IO_CODE
167 rc = RTFileSetSize(pImage->File, cbSize);
168#else
169 rc = pImage->pInterfaceIOCallbacks->pfnSetSize(pImage->pInterfaceIO->pvUser,
170 pImage->pStorage,
171 cbSize);
172#endif
173
174 return rc;
175}
176
177static int vdiFileWriteSync(PVDIIMAGEDESC pImage, uint64_t off, const void *pcvBuf, size_t cbWrite, size_t *pcbWritten)
178{
179 int rc = VINF_SUCCESS;
180
181#ifndef VBOX_WITH_NEW_IO_CODE
182 rc = RTFileWriteAt(pImage->File, off, pcvBuf, cbWrite, pcbWritten);
183#else
184 rc = pImage->pInterfaceIOCallbacks->pfnWriteSync(pImage->pInterfaceIO->pvUser,
185 pImage->pStorage,
186 off, cbWrite, pcvBuf,
187 pcbWritten);
188#endif
189
190 return rc;
191}
192
193static int vdiFileReadSync(PVDIIMAGEDESC pImage, uint64_t off, void *pvBuf, size_t cbRead, size_t *pcbRead)
194{
195 int rc = VINF_SUCCESS;
196
197#ifndef VBOX_WITH_NEW_IO_CODE
198 rc = RTFileReadAt(pImage->File, off, pvBuf, cbRead, pcbRead);
199#else
200 rc = pImage->pInterfaceIOCallbacks->pfnReadSync(pImage->pInterfaceIO->pvUser,
201 pImage->pStorage,
202 off, cbRead, pvBuf,
203 pcbRead);
204#endif
205
206 return rc;
207}
208
209static int vdiFileWriteMetaAsync(PVDIIMAGEDESC pImage, uint64_t off, void *pcvBuf, size_t cbWrite,
210 PVDIOCTX pIoCtx)
211{
212 return pImage->pInterfaceIOCallbacks->pfnWriteMetaAsync(pImage->pInterfaceIO->pvUser,
213 pImage->pStorage,
214 off, pcvBuf, cbWrite, pIoCtx,
215 NULL, NULL);
216}
217
218static int vdiFileReadMetaAsync(PVDIIMAGEDESC pImage, uint64_t off, void *pvBuf, size_t cbRead,
219 PVDIOCTX pIoCtx)
220{
221 return pImage->pInterfaceIOCallbacks->pfnReadMetaAsync(pImage->pInterfaceIO->pvUser,
222 pImage->pStorage,
223 off, pvBuf, cbRead, pIoCtx,
224 NULL, NULL, NULL);
225}
226
227static bool vdiFileOpened(PVDIIMAGEDESC pImage)
228{
229#ifndef VBOX_WITH_NEW_IO_CODE
230 return pImage->File != NIL_RTFILE;
231#else
232 return pImage->pStorage != NULL;
233#endif
234}
235
236static int vdiFileFlushAsync(PVDIIMAGEDESC pImage, PVDIOCTX pIoCtx)
237{
238 return pImage->pInterfaceIOCallbacks->pfnFlushAsync(pImage->pInterfaceIO->pvUser,
239 pImage->pStorage, pIoCtx,
240 NULL, NULL);
241}
242
243
244/**
245 * internal: return power of 2 or 0 if num error.
246 */
247static unsigned getPowerOfTwo(unsigned uNumber)
248{
249 if (uNumber == 0)
250 return 0;
251 unsigned uPower2 = 0;
252 while ((uNumber & 1) == 0)
253 {
254 uNumber >>= 1;
255 uPower2++;
256 }
257 return uNumber == 1 ? uPower2 : 0;
258}
259
260
261/**
262 * Internal: Init VDI preheader.
263 */
264static void vdiInitPreHeader(PVDIPREHEADER pPreHdr)
265{
266 pPreHdr->u32Signature = VDI_IMAGE_SIGNATURE;
267 pPreHdr->u32Version = VDI_IMAGE_VERSION;
268 memset(pPreHdr->szFileInfo, 0, sizeof(pPreHdr->szFileInfo));
269 strncat(pPreHdr->szFileInfo, VDI_IMAGE_FILE_INFO, sizeof(pPreHdr->szFileInfo));
270}
271
272/**
273 * Internal: check VDI preheader.
274 */
275static int vdiValidatePreHeader(PVDIPREHEADER pPreHdr)
276{
277 if (pPreHdr->u32Signature != VDI_IMAGE_SIGNATURE)
278 return VERR_VD_VDI_INVALID_HEADER;
279
280 if ( VDI_GET_VERSION_MAJOR(pPreHdr->u32Version) != VDI_IMAGE_VERSION_MAJOR
281 && pPreHdr->u32Version != 0x00000002) /* old version. */
282 return VERR_VD_VDI_UNSUPPORTED_VERSION;
283
284 return VINF_SUCCESS;
285}
286
287/**
288 * Internal: translate VD image flags to VDI image type enum.
289 */
290static VDIIMAGETYPE vdiTranslateImageFlags2VDI(unsigned uImageFlags)
291{
292 if (uImageFlags & VD_IMAGE_FLAGS_FIXED)
293 return VDI_IMAGE_TYPE_FIXED;
294 else if (uImageFlags & VD_IMAGE_FLAGS_DIFF)
295 return VDI_IMAGE_TYPE_DIFF;
296 else
297 return VDI_IMAGE_TYPE_NORMAL;
298}
299
300/**
301 * Internal: translate VDI image type enum to VD image type enum.
302 */
303static unsigned vdiTranslateVDI2ImageFlags(VDIIMAGETYPE enmType)
304{
305 switch (enmType)
306 {
307 case VDI_IMAGE_TYPE_NORMAL:
308 return VD_IMAGE_FLAGS_NONE;
309 case VDI_IMAGE_TYPE_FIXED:
310 return VD_IMAGE_FLAGS_FIXED;
311 case VDI_IMAGE_TYPE_DIFF:
312 return VD_IMAGE_FLAGS_DIFF;
313 default:
314 AssertMsgFailed(("invalid VDIIMAGETYPE enmType=%d\n", (int)enmType));
315 return VD_IMAGE_FLAGS_NONE;
316 }
317}
318
319/**
320 * Internal: Init VDI header. Always use latest header version.
321 * @param pHeader Assumes it was initially initialized to all zeros.
322 */
323static void vdiInitHeader(PVDIHEADER pHeader, uint32_t uImageFlags,
324 const char *pszComment, uint64_t cbDisk,
325 uint32_t cbBlock, uint32_t cbBlockExtra)
326{
327 pHeader->uVersion = VDI_IMAGE_VERSION;
328 pHeader->u.v1.cbHeader = sizeof(VDIHEADER1);
329 pHeader->u.v1.u32Type = (uint32_t)vdiTranslateImageFlags2VDI(uImageFlags);
330 pHeader->u.v1.fFlags = (uImageFlags & VD_VDI_IMAGE_FLAGS_ZERO_EXPAND) ? 1 : 0;
331#ifdef VBOX_STRICT
332 char achZero[VDI_IMAGE_COMMENT_SIZE] = {0};
333 Assert(!memcmp(pHeader->u.v1.szComment, achZero, VDI_IMAGE_COMMENT_SIZE));
334#endif
335 pHeader->u.v1.szComment[0] = '\0';
336 if (pszComment)
337 {
338 AssertMsg(strlen(pszComment) < sizeof(pHeader->u.v1.szComment),
339 ("HDD Comment is too long, cb=%d\n", strlen(pszComment)));
340 strncat(pHeader->u.v1.szComment, pszComment, sizeof(pHeader->u.v1.szComment));
341 }
342
343 /* Mark the legacy geometry not-calculated. */
344 pHeader->u.v1.LegacyGeometry.cCylinders = 0;
345 pHeader->u.v1.LegacyGeometry.cHeads = 0;
346 pHeader->u.v1.LegacyGeometry.cSectors = 0;
347 pHeader->u.v1.LegacyGeometry.cbSector = VDI_GEOMETRY_SECTOR_SIZE;
348 pHeader->u.v1.u32Dummy = 0; /* used to be the translation value */
349
350 pHeader->u.v1.cbDisk = cbDisk;
351 pHeader->u.v1.cbBlock = cbBlock;
352 pHeader->u.v1.cBlocks = (uint32_t)(cbDisk / cbBlock);
353 if (cbDisk % cbBlock)
354 pHeader->u.v1.cBlocks++;
355 pHeader->u.v1.cbBlockExtra = cbBlockExtra;
356 pHeader->u.v1.cBlocksAllocated = 0;
357
358 /* Init offsets. */
359 pHeader->u.v1.offBlocks = RT_ALIGN_32(sizeof(VDIPREHEADER) + sizeof(VDIHEADER1), VDI_GEOMETRY_SECTOR_SIZE);
360 pHeader->u.v1.offData = RT_ALIGN_32(pHeader->u.v1.offBlocks + (pHeader->u.v1.cBlocks * sizeof(VDIIMAGEBLOCKPOINTER)), VDI_GEOMETRY_SECTOR_SIZE);
361
362 /* Init uuids. */
363 RTUuidCreate(&pHeader->u.v1.uuidCreate);
364 RTUuidClear(&pHeader->u.v1.uuidModify);
365 RTUuidClear(&pHeader->u.v1.uuidLinkage);
366 RTUuidClear(&pHeader->u.v1.uuidParentModify);
367
368 /* Mark LCHS geometry not-calculated. */
369 pHeader->u.v1plus.LCHSGeometry.cCylinders = 0;
370 pHeader->u.v1plus.LCHSGeometry.cHeads = 0;
371 pHeader->u.v1plus.LCHSGeometry.cSectors = 0;
372 pHeader->u.v1plus.LCHSGeometry.cbSector = VDI_GEOMETRY_SECTOR_SIZE;
373}
374
375/**
376 * Internal: Check VDI header.
377 */
378static int vdiValidateHeader(PVDIHEADER pHeader)
379{
380 /* Check version-dependend header parameters. */
381 switch (GET_MAJOR_HEADER_VERSION(pHeader))
382 {
383 case 0:
384 {
385 /* Old header version. */
386 break;
387 }
388 case 1:
389 {
390 /* Current header version. */
391
392 if (pHeader->u.v1.cbHeader < sizeof(VDIHEADER1))
393 {
394 LogRel(("VDI: v1 header size wrong (%d < %d)\n",
395 pHeader->u.v1.cbHeader, sizeof(VDIHEADER1)));
396 return VERR_VD_VDI_INVALID_HEADER;
397 }
398
399 if (getImageBlocksOffset(pHeader) < (sizeof(VDIPREHEADER) + sizeof(VDIHEADER1)))
400 {
401 LogRel(("VDI: v1 blocks offset wrong (%d < %d)\n",
402 getImageBlocksOffset(pHeader), sizeof(VDIPREHEADER) + sizeof(VDIHEADER1)));
403 return VERR_VD_VDI_INVALID_HEADER;
404 }
405
406 if (getImageDataOffset(pHeader) < (getImageBlocksOffset(pHeader) + getImageBlocks(pHeader) * sizeof(VDIIMAGEBLOCKPOINTER)))
407 {
408 LogRel(("VDI: v1 image data offset wrong (%d < %d)\n",
409 getImageDataOffset(pHeader), getImageBlocksOffset(pHeader) + getImageBlocks(pHeader) * sizeof(VDIIMAGEBLOCKPOINTER)));
410 return VERR_VD_VDI_INVALID_HEADER;
411 }
412
413 break;
414 }
415 default:
416 /* Unsupported. */
417 return VERR_VD_VDI_UNSUPPORTED_VERSION;
418 }
419
420 /* Check common header parameters. */
421
422 bool fFailed = false;
423
424 if ( getImageType(pHeader) < VDI_IMAGE_TYPE_FIRST
425 || getImageType(pHeader) > VDI_IMAGE_TYPE_LAST)
426 {
427 LogRel(("VDI: bad image type %d\n", getImageType(pHeader)));
428 fFailed = true;
429 }
430
431 if (getImageFlags(pHeader) & ~VD_VDI_IMAGE_FLAGS_MASK)
432 {
433 LogRel(("VDI: bad image flags %08x\n", getImageFlags(pHeader)));
434 fFailed = true;
435 }
436
437 if ( getImageLCHSGeometry(pHeader)
438 && (getImageLCHSGeometry(pHeader))->cbSector != VDI_GEOMETRY_SECTOR_SIZE)
439 {
440 LogRel(("VDI: wrong sector size (%d != %d)\n",
441 (getImageLCHSGeometry(pHeader))->cbSector, VDI_GEOMETRY_SECTOR_SIZE));
442 fFailed = true;
443 }
444
445 if ( getImageDiskSize(pHeader) == 0
446 || getImageBlockSize(pHeader) == 0
447 || getImageBlocks(pHeader) == 0
448 || getPowerOfTwo(getImageBlockSize(pHeader)) == 0)
449 {
450 LogRel(("VDI: wrong size (%lld, %d, %d, %d)\n",
451 getImageDiskSize(pHeader), getImageBlockSize(pHeader),
452 getImageBlocks(pHeader), getPowerOfTwo(getImageBlockSize(pHeader))));
453 fFailed = true;
454 }
455
456 if (getImageBlocksAllocated(pHeader) > getImageBlocks(pHeader))
457 {
458 LogRel(("VDI: too many blocks allocated (%d > %d)\n"
459 " blocksize=%d disksize=%lld\n",
460 getImageBlocksAllocated(pHeader), getImageBlocks(pHeader),
461 getImageBlockSize(pHeader), getImageDiskSize(pHeader)));
462 fFailed = true;
463 }
464
465 if ( getImageExtraBlockSize(pHeader) != 0
466 && getPowerOfTwo(getImageExtraBlockSize(pHeader)) == 0)
467 {
468 LogRel(("VDI: wrong extra size (%d, %d)\n",
469 getImageExtraBlockSize(pHeader), getPowerOfTwo(getImageExtraBlockSize(pHeader))));
470 fFailed = true;
471 }
472
473 if ((uint64_t)getImageBlockSize(pHeader) * getImageBlocks(pHeader) < getImageDiskSize(pHeader))
474 {
475 LogRel(("VDI: wrong disk size (%d, %d, %lld)\n",
476 getImageBlockSize(pHeader), getImageBlocks(pHeader), getImageDiskSize(pHeader)));
477 fFailed = true;
478 }
479
480 if (RTUuidIsNull(getImageCreationUUID(pHeader)))
481 {
482 LogRel(("VDI: uuid of creator is 0\n"));
483 fFailed = true;
484 }
485
486 if (RTUuidIsNull(getImageModificationUUID(pHeader)))
487 {
488 LogRel(("VDI: uuid of modificator is 0\n"));
489 fFailed = true;
490 }
491
492 return fFailed ? VERR_VD_VDI_INVALID_HEADER : VINF_SUCCESS;
493}
494
495/**
496 * Internal: Set up VDIIMAGEDESC structure by image header.
497 */
498static void vdiSetupImageDesc(PVDIIMAGEDESC pImage)
499{
500 pImage->uImageFlags = getImageFlags(&pImage->Header);
501 pImage->uImageFlags |= vdiTranslateVDI2ImageFlags(getImageType(&pImage->Header));
502 pImage->offStartBlocks = getImageBlocksOffset(&pImage->Header);
503 pImage->offStartData = getImageDataOffset(&pImage->Header);
504 pImage->uBlockMask = getImageBlockSize(&pImage->Header) - 1;
505 pImage->uShiftOffset2Index = getPowerOfTwo(getImageBlockSize(&pImage->Header));
506 pImage->offStartBlockData = getImageExtraBlockSize(&pImage->Header);
507 pImage->cbTotalBlockData = pImage->offStartBlockData
508 + getImageBlockSize(&pImage->Header);
509}
510
511/**
512 * Internal: Create VDI image file.
513 */
514static int vdiCreateImage(PVDIIMAGEDESC pImage, uint64_t cbSize,
515 unsigned uImageFlags, const char *pszComment,
516 PCPDMMEDIAGEOMETRY pPCHSGeometry,
517 PCPDMMEDIAGEOMETRY pLCHSGeometry, PCRTUUID pUuid,
518 unsigned uOpenFlags, PFNVDPROGRESS pfnProgress,
519 void *pvUser, unsigned uPercentStart,
520 unsigned uPercentSpan)
521{
522 int rc;
523 uint64_t cbTotal;
524 uint64_t cbFill;
525 uint64_t uOff;
526
527 /* Special check for comment length. */
528 if ( VALID_PTR(pszComment)
529 && strlen(pszComment) >= VDI_IMAGE_COMMENT_SIZE)
530 {
531 rc = vdiError(pImage, VERR_VD_VDI_COMMENT_TOO_LONG, RT_SRC_POS, N_("VDI: comment is too long for '%s'"), pImage->pszFilename);
532 goto out;
533 }
534 AssertPtr(pPCHSGeometry);
535 AssertPtr(pLCHSGeometry);
536
537 pImage->pInterfaceError = VDInterfaceGet(pImage->pVDIfsDisk, VDINTERFACETYPE_ERROR);
538 if (pImage->pInterfaceError)
539 pImage->pInterfaceErrorCallbacks = VDGetInterfaceError(pImage->pInterfaceError);
540
541#ifdef VBOX_WITH_NEW_IO_CODE
542 /* Try to get I/O interface. */
543 pImage->pInterfaceIO = VDInterfaceGet(pImage->pVDIfsImage, VDINTERFACETYPE_IO);
544 AssertPtr(pImage->pInterfaceIO);
545 pImage->pInterfaceIOCallbacks = VDGetInterfaceIO(pImage->pInterfaceIO);
546 AssertPtr(pImage->pInterfaceIOCallbacks);
547#endif
548
549 vdiInitPreHeader(&pImage->PreHeader);
550 vdiInitHeader(&pImage->Header, uImageFlags, pszComment, cbSize, VDI_IMAGE_DEFAULT_BLOCK_SIZE, 0);
551 /* Save PCHS geometry. Not much work, and makes the flow of information
552 * quite a bit clearer - relying on the higher level isn't obvious. */
553 pImage->PCHSGeometry = *pPCHSGeometry;
554 /* Set LCHS geometry (legacy geometry is ignored for the current 1.1+). */
555 pImage->Header.u.v1plus.LCHSGeometry.cCylinders = pLCHSGeometry->cCylinders;
556 pImage->Header.u.v1plus.LCHSGeometry.cHeads = pLCHSGeometry->cHeads;
557 pImage->Header.u.v1plus.LCHSGeometry.cSectors = pLCHSGeometry->cSectors;
558 pImage->Header.u.v1plus.LCHSGeometry.cbSector = VDI_GEOMETRY_SECTOR_SIZE;
559
560 pImage->paBlocks = (PVDIIMAGEBLOCKPOINTER)RTMemAlloc(sizeof(VDIIMAGEBLOCKPOINTER) * getImageBlocks(&pImage->Header));
561 if (!pImage->paBlocks)
562 {
563 rc = VERR_NO_MEMORY;
564 goto out;
565 }
566
567 if (!(uImageFlags & VD_IMAGE_FLAGS_FIXED))
568 {
569 /* for growing images mark all blocks in paBlocks as free. */
570 for (unsigned i = 0; i < pImage->Header.u.v1.cBlocks; i++)
571 pImage->paBlocks[i] = VDI_IMAGE_BLOCK_FREE;
572 }
573 else
574 {
575 /* for fixed images mark all blocks in paBlocks as allocated */
576 for (unsigned i = 0; i < pImage->Header.u.v1.cBlocks; i++)
577 pImage->paBlocks[i] = i;
578 pImage->Header.u.v1.cBlocksAllocated = pImage->Header.u.v1.cBlocks;
579 }
580
581 /* Setup image parameters. */
582 vdiSetupImageDesc(pImage);
583
584 /* Create image file. */
585 rc = vdiFileOpen(pImage, false /* fReadonly */,
586 !!(uOpenFlags & VD_OPEN_FLAGS_SHAREABLE),
587 true /* fCreate */);
588 if (RT_FAILURE(rc))
589 {
590 rc = vdiError(pImage, rc, RT_SRC_POS, N_("VDI: cannot create image '%s'"), pImage->pszFilename);
591 goto out;
592 }
593
594 cbTotal = pImage->offStartData
595 + (uint64_t)getImageBlocks(&pImage->Header) * pImage->cbTotalBlockData;
596
597 if (uImageFlags & VD_IMAGE_FLAGS_FIXED)
598 {
599 /* Check the free space on the disk and leave early if there is not
600 * sufficient space available. */
601 RTFOFF cbFree = 0;
602 rc = RTFsQuerySizes(pImage->pszFilename, NULL, &cbFree, NULL, NULL);
603 if (RT_SUCCESS(rc) /* ignore errors */ && ((uint64_t)cbFree < cbTotal))
604 {
605 rc = vdiError(pImage, VERR_DISK_FULL, RT_SRC_POS, N_("VDI: disk would overflow creating image '%s'"), pImage->pszFilename);
606 goto out;
607 }
608 }
609
610 if (uImageFlags & VD_IMAGE_FLAGS_FIXED)
611 {
612 /*
613 * Allocate & commit whole file if fixed image, it must be more
614 * effective than expanding file by write operations.
615 */
616 rc = vdiFileSetSize(pImage, cbTotal);
617 }
618 else
619 {
620 /* Set file size to hold header and blocks array. */
621 rc = vdiFileSetSize(pImage, pImage->offStartData);
622 }
623 if (RT_FAILURE(rc))
624 {
625 rc = vdiError(pImage, rc, RT_SRC_POS, N_("VDI: setting image size failed for '%s'"), pImage->pszFilename);
626 goto out;
627 }
628
629 /* Use specified image uuid */
630 *getImageCreationUUID(&pImage->Header) = *pUuid;
631
632 /* Generate image last-modify uuid */
633 RTUuidCreate(getImageModificationUUID(&pImage->Header));
634
635 /* Write pre-header. */
636 rc = vdiFileWriteSync(pImage, 0, &pImage->PreHeader, sizeof(pImage->PreHeader), NULL);
637 if (RT_FAILURE(rc))
638 {
639 rc = vdiError(pImage, rc, RT_SRC_POS, N_("VDI: writing pre-header failed for '%s'"), pImage->pszFilename);
640 goto out;
641 }
642
643 /* Write header. */
644 rc = vdiFileWriteSync(pImage, sizeof(pImage->PreHeader), &pImage->Header.u.v1plus, sizeof(pImage->Header.u.v1plus), NULL);
645 if (RT_FAILURE(rc))
646 {
647 rc = vdiError(pImage, rc, RT_SRC_POS, N_("VDI: writing header failed for '%s'"), pImage->pszFilename);
648 goto out;
649 }
650
651 rc = vdiFileWriteSync(pImage, pImage->offStartBlocks,
652 pImage->paBlocks,
653 getImageBlocks(&pImage->Header) * sizeof(VDIIMAGEBLOCKPOINTER),
654 NULL);
655 if (RT_FAILURE(rc))
656 {
657 rc = vdiError(pImage, rc, RT_SRC_POS, N_("VDI: writing block pointers failed for '%s'"), pImage->pszFilename);
658 goto out;
659 }
660
661 if (uImageFlags & VD_IMAGE_FLAGS_FIXED)
662 {
663 /* Fill image with zeroes. We do this for every fixed-size image since on some systems
664 * (for example Windows Vista), it takes ages to write a block near the end of a sparse
665 * file and the guest could complain about an ATA timeout. */
666
667 /** @todo Starting with Linux 2.6.23, there is an fallocate() system call.
668 * Currently supported file systems are ext4 and ocfs2. */
669
670 /* Allocate a temporary zero-filled buffer. Use a bigger block size to optimize writing */
671 const size_t cbBuf = 128 * _1K;
672 void *pvBuf = RTMemTmpAllocZ(cbBuf);
673 if (!pvBuf)
674 {
675 rc = VERR_NO_MEMORY;
676 goto out;
677 }
678
679 cbFill = (uint64_t)getImageBlocks(&pImage->Header) * pImage->cbTotalBlockData;
680 uOff = 0;
681 /* Write data to all image blocks. */
682 while (uOff < cbFill)
683 {
684 unsigned cbChunk = (unsigned)RT_MIN(cbFill, cbBuf);
685
686 rc = vdiFileWriteSync(pImage, pImage->offStartData + uOff,
687 pvBuf, cbChunk, NULL);
688 if (RT_FAILURE(rc))
689 {
690 rc = vdiError(pImage, rc, RT_SRC_POS, N_("VDI: writing block failed for '%s'"), pImage->pszFilename);
691 goto out;
692 }
693
694 uOff += cbChunk;
695
696 if (pfnProgress)
697 {
698 rc = pfnProgress(pvUser,
699 uPercentStart + uOff * uPercentSpan / cbFill);
700 if (RT_FAILURE(rc))
701 goto out;
702 }
703 }
704 RTMemTmpFree(pvBuf);
705 }
706
707out:
708 if (RT_SUCCESS(rc) && pfnProgress)
709 pfnProgress(pvUser, uPercentStart + uPercentSpan);
710
711 if (RT_FAILURE(rc))
712 vdiFreeImage(pImage, rc != VERR_ALREADY_EXISTS);
713 return rc;
714}
715
716/**
717 * Internal: Open a VDI image.
718 */
719static int vdiOpenImage(PVDIIMAGEDESC pImage, unsigned uOpenFlags)
720{
721 int rc;
722
723 pImage->uOpenFlags = uOpenFlags;
724
725 pImage->pInterfaceError = VDInterfaceGet(pImage->pVDIfsDisk, VDINTERFACETYPE_ERROR);
726 if (pImage->pInterfaceError)
727 pImage->pInterfaceErrorCallbacks = VDGetInterfaceError(pImage->pInterfaceError);
728
729#ifdef VBOX_WITH_NEW_IO_CODE
730 /* Try to get I/O interface. */
731 pImage->pInterfaceIO = VDInterfaceGet(pImage->pVDIfsImage, VDINTERFACETYPE_IO);
732 AssertPtr(pImage->pInterfaceIO);
733 pImage->pInterfaceIOCallbacks = VDGetInterfaceIO(pImage->pInterfaceIO);
734 AssertPtr(pImage->pInterfaceIOCallbacks);
735#endif
736
737 /*
738 * Open the image.
739 */
740 rc = vdiFileOpen(pImage,
741 !!(uOpenFlags & VD_OPEN_FLAGS_READONLY),
742 !!(uOpenFlags & VD_OPEN_FLAGS_SHAREABLE),
743 false /* fCreate */);
744 if (RT_FAILURE(rc))
745 {
746 /* Do NOT signal an appropriate error here, as the VD layer has the
747 * choice of retrying the open if it failed. */
748 goto out;
749 }
750
751 /* Read pre-header. */
752 rc = vdiFileReadSync(pImage, 0, &pImage->PreHeader, sizeof(pImage->PreHeader),
753 NULL);
754 if (RT_FAILURE(rc))
755 {
756 rc = vdiError(pImage, rc, RT_SRC_POS, N_("VDI: error reading pre-header in '%s'"), pImage->pszFilename);
757 goto out;
758 }
759 rc = vdiValidatePreHeader(&pImage->PreHeader);
760 if (RT_FAILURE(rc))
761 {
762 rc = vdiError(pImage, rc, RT_SRC_POS, N_("VDI: invalid pre-header in '%s'"), pImage->pszFilename);
763 goto out;
764 }
765
766 /* Read header. */
767 pImage->Header.uVersion = pImage->PreHeader.u32Version;
768 switch (GET_MAJOR_HEADER_VERSION(&pImage->Header))
769 {
770 case 0:
771 rc = vdiFileReadSync(pImage, sizeof(pImage->PreHeader),
772 &pImage->Header.u.v0, sizeof(pImage->Header.u.v0),
773 NULL);
774 if (RT_FAILURE(rc))
775 {
776 rc = vdiError(pImage, rc, RT_SRC_POS, N_("VDI: error reading v0 header in '%s'"), pImage->pszFilename);
777 goto out;
778 }
779 break;
780 case 1:
781 rc = vdiFileReadSync(pImage, sizeof(pImage->PreHeader),
782 &pImage->Header.u.v1, sizeof(pImage->Header.u.v1),
783 NULL);
784 if (RT_FAILURE(rc))
785 {
786 rc = vdiError(pImage, rc, RT_SRC_POS, N_("VDI: error reading v1 header in '%s'"), pImage->pszFilename);
787 goto out;
788 }
789 /* Convert VDI 1.1 images to VDI 1.1+ on open in read/write mode.
790 * Conversion is harmless, as any VirtualBox version supporting VDI
791 * 1.1 doesn't touch fields it doesn't know about. */
792 if ( !(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
793 && GET_MINOR_HEADER_VERSION(&pImage->Header) == 1
794 && pImage->Header.u.v1.cbHeader < sizeof(pImage->Header.u.v1plus))
795 {
796 pImage->Header.u.v1plus.cbHeader = sizeof(pImage->Header.u.v1plus);
797 /* Mark LCHS geometry not-calculated. */
798 pImage->Header.u.v1plus.LCHSGeometry.cCylinders = 0;
799 pImage->Header.u.v1plus.LCHSGeometry.cHeads = 0;
800 pImage->Header.u.v1plus.LCHSGeometry.cSectors = 0;
801 pImage->Header.u.v1plus.LCHSGeometry.cbSector = VDI_GEOMETRY_SECTOR_SIZE;
802 }
803 else if (pImage->Header.u.v1.cbHeader >= sizeof(pImage->Header.u.v1plus))
804 {
805 /* Read the actual VDI 1.1+ header completely. */
806 rc = vdiFileReadSync(pImage, sizeof(pImage->PreHeader), &pImage->Header.u.v1plus, sizeof(pImage->Header.u.v1plus), NULL);
807 if (RT_FAILURE(rc))
808 {
809 rc = vdiError(pImage, rc, RT_SRC_POS, N_("VDI: error reading v1.1+ header in '%s'"), pImage->pszFilename);
810 goto out;
811 }
812 }
813 break;
814 default:
815 rc = vdiError(pImage, VERR_VD_VDI_UNSUPPORTED_VERSION, RT_SRC_POS, N_("VDI: unsupported major version %u in '%s'"), GET_MAJOR_HEADER_VERSION(&pImage->Header), pImage->pszFilename);
816 goto out;
817 }
818
819 rc = vdiValidateHeader(&pImage->Header);
820 if (RT_FAILURE(rc))
821 {
822 rc = vdiError(pImage, VERR_VD_VDI_INVALID_HEADER, RT_SRC_POS, N_("VDI: invalid header in '%s'"), pImage->pszFilename);
823 goto out;
824 }
825
826 /* Setup image parameters by header. */
827 vdiSetupImageDesc(pImage);
828
829 /* Allocate memory for blocks array. */
830 pImage->paBlocks = (PVDIIMAGEBLOCKPOINTER)RTMemAlloc(sizeof(VDIIMAGEBLOCKPOINTER) * getImageBlocks(&pImage->Header));
831 if (!pImage->paBlocks)
832 {
833 rc = VERR_NO_MEMORY;
834 goto out;
835 }
836
837 /* Read blocks array. */
838 rc = vdiFileReadSync(pImage, pImage->offStartBlocks, pImage->paBlocks,
839 getImageBlocks(&pImage->Header) * sizeof(VDIIMAGEBLOCKPOINTER),
840 NULL);
841
842out:
843 if (RT_FAILURE(rc))
844 vdiFreeImage(pImage, false);
845 return rc;
846}
847
848/**
849 * Internal: Save header to file.
850 */
851static int vdiUpdateHeader(PVDIIMAGEDESC pImage)
852{
853 int rc;
854 switch (GET_MAJOR_HEADER_VERSION(&pImage->Header))
855 {
856 case 0:
857 rc = vdiFileWriteSync(pImage, sizeof(VDIPREHEADER), &pImage->Header.u.v0, sizeof(pImage->Header.u.v0), NULL);
858 break;
859 case 1:
860 if (pImage->Header.u.v1plus.cbHeader < sizeof(pImage->Header.u.v1plus))
861 rc = vdiFileWriteSync(pImage, sizeof(VDIPREHEADER), &pImage->Header.u.v1, sizeof(pImage->Header.u.v1), NULL);
862 else
863 rc = vdiFileWriteSync(pImage, sizeof(VDIPREHEADER), &pImage->Header.u.v1plus, sizeof(pImage->Header.u.v1plus), NULL);
864 break;
865 default:
866 rc = VERR_VD_VDI_UNSUPPORTED_VERSION;
867 break;
868 }
869 AssertMsgRC(rc, ("vdiUpdateHeader failed, filename=\"%s\" rc=%Rrc\n", pImage->pszFilename, rc));
870 return rc;
871}
872
873/**
874 * Internal: Save header to file - async version.
875 */
876static int vdiUpdateHeaderAsync(PVDIIMAGEDESC pImage, PVDIOCTX pIoCtx)
877{
878 int rc;
879 switch (GET_MAJOR_HEADER_VERSION(&pImage->Header))
880 {
881 case 0:
882 rc = vdiFileWriteMetaAsync(pImage, sizeof(VDIPREHEADER),
883 &pImage->Header.u.v0, sizeof(pImage->Header.u.v0),
884 pIoCtx);
885
886 break;
887 case 1:
888 if (pImage->Header.u.v1plus.cbHeader < sizeof(pImage->Header.u.v1plus))
889 rc = vdiFileWriteMetaAsync(pImage, sizeof(VDIPREHEADER),
890 &pImage->Header.u.v1, sizeof(pImage->Header.u.v1),
891 pIoCtx);
892 else
893 rc = vdiFileWriteMetaAsync(pImage, sizeof(VDIPREHEADER),
894 &pImage->Header.u.v1plus, sizeof(pImage->Header.u.v1plus),
895 pIoCtx);
896 break;
897 default:
898 rc = VERR_VD_VDI_UNSUPPORTED_VERSION;
899 break;
900 }
901 AssertMsg(RT_SUCCESS(rc) || rc == VERR_VD_ASYNC_IO_IN_PROGRESS,
902 ("vdiUpdateHeader failed, filename=\"%s\" rc=%Rrc\n", pImage->pszFilename, rc));
903 return rc;
904}
905
906/**
907 * Internal: Save block pointer to file, save header to file.
908 */
909static int vdiUpdateBlockInfo(PVDIIMAGEDESC pImage, unsigned uBlock)
910{
911 /* Update image header. */
912 int rc = vdiUpdateHeader(pImage);
913 if (RT_SUCCESS(rc))
914 {
915 /* write only one block pointer. */
916 rc = vdiFileWriteSync(pImage,
917 pImage->offStartBlocks + uBlock * sizeof(VDIIMAGEBLOCKPOINTER),
918 &pImage->paBlocks[uBlock],
919 sizeof(VDIIMAGEBLOCKPOINTER),
920 NULL);
921 AssertMsgRC(rc, ("vdiUpdateBlockInfo failed to update block=%u, filename=\"%s\", rc=%Rrc\n",
922 uBlock, pImage->pszFilename, rc));
923 }
924 return rc;
925}
926
927/**
928 * Internal: Save block pointer to file, save header to file - async version.
929 */
930static int vdiUpdateBlockInfoAsync(PVDIIMAGEDESC pImage, unsigned uBlock,
931 PVDIOCTX pIoCtx)
932{
933 /* Update image header. */
934 int rc = vdiUpdateHeaderAsync(pImage, pIoCtx);
935 if (RT_SUCCESS(rc) || rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
936 {
937 /* write only one block pointer. */
938 rc = vdiFileWriteMetaAsync(pImage,
939 pImage->offStartBlocks + uBlock * sizeof(VDIIMAGEBLOCKPOINTER),
940 &pImage->paBlocks[uBlock],
941 sizeof(VDIIMAGEBLOCKPOINTER),
942 pIoCtx);
943 AssertMsg(RT_SUCCESS(rc) || rc == VERR_VD_ASYNC_IO_IN_PROGRESS,
944 ("vdiUpdateBlockInfo failed to update block=%u, filename=\"%s\", rc=%Rrc\n",
945 uBlock, pImage->pszFilename, rc));
946 }
947 return rc;
948}
949
950/**
951 * Internal: Flush the image file to disk.
952 */
953static void vdiFlushImage(PVDIIMAGEDESC pImage)
954{
955 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
956 {
957 /* Save header. */
958 int rc = vdiUpdateHeader(pImage);
959 AssertMsgRC(rc, ("vdiUpdateHeader() failed, filename=\"%s\", rc=%Rrc\n",
960 pImage->pszFilename, rc));
961 vdiFileFlushSync(pImage);
962 }
963}
964
965/**
966 * Internal: Flush the image file to disk - async version.
967 */
968static int vdiFlushImageAsync(PVDIIMAGEDESC pImage, PVDIOCTX pIoCtx)
969{
970 int rc = VINF_SUCCESS;
971
972 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
973 {
974 /* Save header. */
975 rc = vdiUpdateHeaderAsync(pImage, pIoCtx);
976 AssertMsg(RT_SUCCESS(rc) || rc == VERR_VD_ASYNC_IO_IN_PROGRESS,
977 ("vdiUpdateHeaderAsync() failed, filename=\"%s\", rc=%Rrc\n",
978 pImage->pszFilename, rc));
979 rc = vdiFileFlushAsync(pImage, pIoCtx);
980 AssertMsg(RT_SUCCESS(rc) || rc == VERR_VD_ASYNC_IO_IN_PROGRESS,
981 ("Flushing data to disk failed rc=%Rrc\n", rc));
982 }
983
984 return rc;
985}
986
987/**
988 * Internal: Free all allocated space for representing an image, and optionally
989 * delete the image from disk.
990 */
991static void vdiFreeImage(PVDIIMAGEDESC pImage, bool fDelete)
992{
993 AssertPtr(pImage);
994
995 if (vdiFileOpened(pImage))
996 {
997 vdiFlushImage(pImage);
998 vdiFileClose(pImage);
999 }
1000 if (pImage->paBlocks)
1001 {
1002 RTMemFree(pImage->paBlocks);
1003 pImage->paBlocks = NULL;
1004 }
1005 if (fDelete && pImage->pszFilename)
1006 RTFileDelete(pImage->pszFilename);
1007}
1008
1009
1010/** @copydoc VBOXHDDBACKEND::pfnCheckIfValid */
1011static int vdiCheckIfValid(const char *pszFilename, PVDINTERFACE pVDIfsDisk)
1012{
1013 LogFlowFunc(("pszFilename=\"%s\"\n", pszFilename));
1014 int rc = VINF_SUCCESS;
1015 PVDIIMAGEDESC pImage;
1016
1017 if ( !VALID_PTR(pszFilename)
1018 || !*pszFilename)
1019 {
1020 rc = VERR_INVALID_PARAMETER;
1021 goto out;
1022 }
1023
1024 pImage = (PVDIIMAGEDESC)RTMemAllocZ(sizeof(VDIIMAGEDESC));
1025 if (!pImage)
1026 {
1027 rc = VERR_NO_MEMORY;
1028 goto out;
1029 }
1030 pImage->pszFilename = pszFilename;
1031#ifndef VBOX_WITH_NEW_IO_CODE
1032 pImage->File = NIL_RTFILE;
1033#else
1034 pImage->pStorage = NULL;
1035#endif
1036 pImage->paBlocks = NULL;
1037 pImage->pVDIfsDisk = pVDIfsDisk;
1038 /* For the async I/O interface which is normally retrieved from the image interface list. */
1039 pImage->pVDIfsImage = pVDIfsDisk;
1040
1041 rc = vdiOpenImage(pImage, VD_OPEN_FLAGS_INFO | VD_OPEN_FLAGS_READONLY);
1042 vdiFreeImage(pImage, false);
1043 RTMemFree(pImage);
1044
1045out:
1046 LogFlowFunc(("returns %Rrc\n", rc));
1047 return rc;
1048}
1049
1050/** @copydoc VBOXHDDBACKEND::pfnOpen */
1051static int vdiOpen(const char *pszFilename, unsigned uOpenFlags,
1052 PVDINTERFACE pVDIfsDisk, PVDINTERFACE pVDIfsImage,
1053 void **ppBackendData)
1054{
1055 LogFlowFunc(("pszFilename=\"%s\" uOpenFlags=%#x pVDIfsDisk=%#p pVDIfsImage=%#p ppBackendData=%#p\n", pszFilename, uOpenFlags, pVDIfsDisk, pVDIfsImage, ppBackendData));
1056 int rc;
1057 PVDIIMAGEDESC pImage;
1058
1059 /* Check open flags. All valid flags are supported. */
1060 if (uOpenFlags & ~VD_OPEN_FLAGS_MASK)
1061 {
1062 rc = VERR_INVALID_PARAMETER;
1063 goto out;
1064 }
1065
1066 /* Check remaining arguments. */
1067 if ( !VALID_PTR(pszFilename)
1068 || !*pszFilename)
1069 {
1070 rc = VERR_INVALID_PARAMETER;
1071 goto out;
1072 }
1073
1074 pImage = (PVDIIMAGEDESC)RTMemAllocZ(sizeof(VDIIMAGEDESC));
1075 if (!pImage)
1076 {
1077 rc = VERR_NO_MEMORY;
1078 goto out;
1079 }
1080 pImage->pszFilename = pszFilename;
1081#ifndef VBOX_WITH_NEW_IO_CODE
1082 pImage->File = NIL_RTFILE;
1083#else
1084 pImage->pStorage = NULL;
1085#endif
1086 pImage->paBlocks = NULL;
1087 pImage->pVDIfsDisk = pVDIfsDisk;
1088 pImage->pVDIfsImage = pVDIfsImage;
1089
1090 rc = vdiOpenImage(pImage, uOpenFlags);
1091 if (RT_SUCCESS(rc))
1092 *ppBackendData = pImage;
1093
1094out:
1095 LogFlowFunc(("returns %Rrc (pBackendData=%#p)\n", rc, *ppBackendData));
1096 return rc;
1097}
1098
1099/** @copydoc VBOXHDDBACKEND::pfnCreate */
1100static int vdiCreate(const char *pszFilename, uint64_t cbSize,
1101 unsigned uImageFlags, const char *pszComment,
1102 PCPDMMEDIAGEOMETRY pPCHSGeometry,
1103 PCPDMMEDIAGEOMETRY pLCHSGeometry, PCRTUUID pUuid,
1104 unsigned uOpenFlags, unsigned uPercentStart,
1105 unsigned uPercentSpan, PVDINTERFACE pVDIfsDisk,
1106 PVDINTERFACE pVDIfsImage, PVDINTERFACE pVDIfsOperation,
1107 void **ppBackendData)
1108{
1109 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", pszFilename, cbSize, uImageFlags, pszComment, pPCHSGeometry, pLCHSGeometry, pUuid, uOpenFlags, uPercentStart, uPercentSpan, pVDIfsDisk, pVDIfsImage, pVDIfsOperation, ppBackendData));
1110 int rc;
1111 PVDIIMAGEDESC pImage;
1112
1113 PFNVDPROGRESS pfnProgress = NULL;
1114 void *pvUser = NULL;
1115 PVDINTERFACE pIfProgress = VDInterfaceGet(pVDIfsOperation,
1116 VDINTERFACETYPE_PROGRESS);
1117 PVDINTERFACEPROGRESS pCbProgress = NULL;
1118 if (pIfProgress)
1119 {
1120 pCbProgress = VDGetInterfaceProgress(pIfProgress);
1121 if (pCbProgress)
1122 pfnProgress = pCbProgress->pfnProgress;
1123 pvUser = pIfProgress->pvUser;
1124 }
1125
1126 /* Check open flags. All valid flags are supported. */
1127 if (uOpenFlags & ~VD_OPEN_FLAGS_MASK)
1128 {
1129 rc = VERR_INVALID_PARAMETER;
1130 goto out;
1131 }
1132
1133 /* Check size. Maximum 2PB-3M (to be on the safe side). No tricks with
1134 * adjusting the 1M block size so far, which would extend the size. */
1135 if ( !cbSize
1136 || cbSize >= _1P * 2 - _1M * 3)
1137 {
1138 rc = VERR_VD_INVALID_SIZE;
1139 goto out;
1140 }
1141
1142 /* Check remaining arguments. */
1143 if ( !VALID_PTR(pszFilename)
1144 || !*pszFilename
1145 || cbSize < VDI_IMAGE_DEFAULT_BLOCK_SIZE
1146 || !VALID_PTR(pPCHSGeometry)
1147 || !VALID_PTR(pLCHSGeometry))
1148 {
1149 rc = VERR_INVALID_PARAMETER;
1150 goto out;
1151 }
1152
1153 pImage = (PVDIIMAGEDESC)RTMemAllocZ(sizeof(VDIIMAGEDESC));
1154 if (!pImage)
1155 {
1156 rc = VERR_NO_MEMORY;
1157 goto out;
1158 }
1159 pImage->pszFilename = pszFilename;
1160#ifndef VBOX_WITH_NEW_IO_CODE
1161 pImage->File = NIL_RTFILE;
1162#else
1163 pImage->pStorage = NULL;
1164#endif
1165 pImage->paBlocks = NULL;
1166 pImage->pVDIfsDisk = pVDIfsDisk;
1167 pImage->pVDIfsImage = pVDIfsImage;
1168
1169 rc = vdiCreateImage(pImage, cbSize, uImageFlags, pszComment,
1170 pPCHSGeometry, pLCHSGeometry, pUuid, uOpenFlags,
1171 pfnProgress, pvUser, uPercentStart, uPercentSpan);
1172 if (RT_SUCCESS(rc))
1173 {
1174 /* So far the image is opened in read/write mode. Make sure the
1175 * image is opened in read-only mode if the caller requested that. */
1176 if (uOpenFlags & VD_OPEN_FLAGS_READONLY)
1177 {
1178 vdiFreeImage(pImage, false);
1179 rc = vdiOpenImage(pImage, uOpenFlags);
1180 if (RT_FAILURE(rc))
1181 goto out;
1182 }
1183 *ppBackendData = pImage;
1184 }
1185 else
1186 RTMemFree(pImage);
1187
1188out:
1189 LogFlowFunc(("returns %Rrc (pBackendData=%#p)\n", rc, *ppBackendData));
1190 return rc;
1191}
1192
1193/** @copydoc VBOXHDDBACKEND::pfnRename */
1194static int vdiRename(void *pBackendData, const char *pszFilename)
1195{
1196 LogFlowFunc(("pBackendData=%#p pszFilename=%#p\n", pBackendData, pszFilename));
1197
1198 int rc = VINF_SUCCESS;
1199 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1200
1201 /* Check arguments. */
1202 if ( !pImage
1203 || !pszFilename
1204 || !*pszFilename)
1205 {
1206 rc = VERR_INVALID_PARAMETER;
1207 goto out;
1208 }
1209
1210 /* Close the image. */
1211 vdiFreeImage(pImage, false);
1212
1213 /* Rename the file. */
1214 rc = RTFileMove(pImage->pszFilename, pszFilename, 0);
1215 if (RT_FAILURE(rc))
1216 {
1217 /* The move failed, try to reopen the original image. */
1218 int rc2 = vdiOpenImage(pImage, pImage->uOpenFlags);
1219 if (RT_FAILURE(rc2))
1220 rc = rc2;
1221
1222 goto out;
1223 }
1224
1225 /* Update pImage with the new information. */
1226 pImage->pszFilename = pszFilename;
1227
1228 /* Open the new image. */
1229 rc = vdiOpenImage(pImage, pImage->uOpenFlags);
1230 if (RT_FAILURE(rc))
1231 goto out;
1232
1233out:
1234 LogFlowFunc(("returns %Rrc\n", rc));
1235 return rc;
1236}
1237
1238/** @copydoc VBOXHDDBACKEND::pfnClose */
1239static int vdiClose(void *pBackendData, bool fDelete)
1240{
1241 LogFlowFunc(("pBackendData=%#p fDelete=%d\n", pBackendData, fDelete));
1242 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1243 int rc = VINF_SUCCESS;
1244
1245 /* Freeing a never allocated image (e.g. because the open failed) is
1246 * not signalled as an error. After all nothing bad happens. */
1247 if (pImage)
1248 {
1249 vdiFreeImage(pImage, fDelete);
1250 RTMemFree(pImage);
1251 }
1252
1253 LogFlowFunc(("returns %Rrc\n", rc));
1254 return rc;
1255}
1256
1257/** @copydoc VBOXHDDBACKEND::pfnRead */
1258static int vdiRead(void *pBackendData, uint64_t uOffset, void *pvBuf,
1259 size_t cbToRead, size_t *pcbActuallyRead)
1260{
1261 LogFlowFunc(("pBackendData=%#p uOffset=%llu pvBuf=%#p cbToRead=%zu pcbActuallyRead=%#p\n", pBackendData, uOffset, pvBuf, cbToRead, pcbActuallyRead));
1262 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1263 unsigned uBlock;
1264 unsigned offRead;
1265 int rc;
1266
1267 AssertPtr(pImage);
1268 Assert(!(uOffset % 512));
1269 Assert(!(cbToRead % 512));
1270
1271 if ( uOffset + cbToRead > getImageDiskSize(&pImage->Header)
1272 || !VALID_PTR(pvBuf)
1273 || !cbToRead)
1274 {
1275 rc = VERR_INVALID_PARAMETER;
1276 goto out;
1277 }
1278
1279 /* Calculate starting block number and offset inside it. */
1280 uBlock = (unsigned)(uOffset >> pImage->uShiftOffset2Index);
1281 offRead = (unsigned)uOffset & pImage->uBlockMask;
1282
1283 /* Clip read range to at most the rest of the block. */
1284 cbToRead = RT_MIN(cbToRead, getImageBlockSize(&pImage->Header) - offRead);
1285 Assert(!(cbToRead % 512));
1286
1287 if (pImage->paBlocks[uBlock] == VDI_IMAGE_BLOCK_FREE)
1288 rc = VERR_VD_BLOCK_FREE;
1289 else if (pImage->paBlocks[uBlock] == VDI_IMAGE_BLOCK_ZERO)
1290 {
1291 memset(pvBuf, 0, cbToRead);
1292 rc = VINF_SUCCESS;
1293 }
1294 else
1295 {
1296 /* Block present in image file, read relevant data. */
1297 uint64_t u64Offset = (uint64_t)pImage->paBlocks[uBlock] * pImage->cbTotalBlockData
1298 + (pImage->offStartData + pImage->offStartBlockData + offRead);
1299 rc = vdiFileReadSync(pImage, u64Offset, pvBuf, cbToRead, NULL);
1300 }
1301
1302 if (pcbActuallyRead)
1303 *pcbActuallyRead = cbToRead;
1304
1305out:
1306 LogFlowFunc(("returns %Rrc\n", rc));
1307 return rc;
1308}
1309
1310/**@copydoc VBOXHDDBACKEND::pfnWrite */
1311static int vdiWrite(void *pBackendData, uint64_t uOffset, const void *pvBuf,
1312 size_t cbToWrite, size_t *pcbWriteProcess,
1313 size_t *pcbPreRead, size_t *pcbPostRead, unsigned fWrite)
1314{
1315 LogFlowFunc(("pBackendData=%#p uOffset=%llu pvBuf=%#p cbToWrite=%zu pcbWriteProcess=%#p pcbPreRead=%#p pcbPostRead=%#p\n", pBackendData, uOffset, pvBuf, cbToWrite, pcbWriteProcess, pcbPreRead, pcbPostRead));
1316 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1317 unsigned uBlock;
1318 unsigned offWrite;
1319 int rc = VINF_SUCCESS;
1320
1321 AssertPtr(pImage);
1322 Assert(!(uOffset % 512));
1323 Assert(!(cbToWrite % 512));
1324
1325 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
1326 {
1327 rc = VERR_VD_IMAGE_READ_ONLY;
1328 goto out;
1329 }
1330
1331 if (!VALID_PTR(pvBuf) || !cbToWrite)
1332 {
1333 rc = VERR_INVALID_PARAMETER;
1334 goto out;
1335 }
1336
1337 /* No size check here, will do that later. For dynamic images which are
1338 * not multiples of the block size in length, this would prevent writing to
1339 * the last grain. */
1340
1341 /* Calculate starting block number and offset inside it. */
1342 uBlock = (unsigned)(uOffset >> pImage->uShiftOffset2Index);
1343 offWrite = (unsigned)uOffset & pImage->uBlockMask;
1344
1345 /* Clip write range to at most the rest of the block. */
1346 cbToWrite = RT_MIN(cbToWrite, getImageBlockSize(&pImage->Header) - offWrite);
1347 Assert(!(cbToWrite % 512));
1348
1349 do
1350 {
1351 if (!IS_VDI_IMAGE_BLOCK_ALLOCATED(pImage->paBlocks[uBlock]))
1352 {
1353 /* Block is either free or zero. */
1354 if ( !(pImage->uOpenFlags & VD_OPEN_FLAGS_HONOR_ZEROES)
1355 && ( pImage->paBlocks[uBlock] == VDI_IMAGE_BLOCK_ZERO
1356 || cbToWrite == getImageBlockSize(&pImage->Header)))
1357 {
1358 /* If the destination block is unallocated at this point, it's
1359 * either a zero block or a block which hasn't been used so far
1360 * (which also means that it's a zero block. Don't need to write
1361 * anything to this block if the data consists of just zeroes. */
1362 Assert(!(cbToWrite % 4));
1363 Assert(cbToWrite * 8 <= UINT32_MAX);
1364 if (ASMBitFirstSet((volatile void *)pvBuf, (uint32_t)cbToWrite * 8) == -1)
1365 {
1366 pImage->paBlocks[uBlock] = VDI_IMAGE_BLOCK_ZERO;
1367 break;
1368 }
1369 }
1370
1371 if (cbToWrite == getImageBlockSize(&pImage->Header))
1372 {
1373 /* Full block write to previously unallocated block.
1374 * Allocate block and write data. */
1375 Assert(!offWrite);
1376 unsigned cBlocksAllocated = getImageBlocksAllocated(&pImage->Header);
1377 uint64_t u64Offset = (uint64_t)cBlocksAllocated * pImage->cbTotalBlockData
1378 + (pImage->offStartData + pImage->offStartBlockData);
1379 rc = vdiFileWriteSync(pImage, u64Offset, pvBuf, cbToWrite, NULL);
1380 if (RT_FAILURE(rc))
1381 goto out;
1382 pImage->paBlocks[uBlock] = cBlocksAllocated;
1383 setImageBlocksAllocated(&pImage->Header, cBlocksAllocated + 1);
1384
1385 rc = vdiUpdateBlockInfo(pImage, uBlock);
1386 if (RT_FAILURE(rc))
1387 goto out;
1388
1389 *pcbPreRead = 0;
1390 *pcbPostRead = 0;
1391 }
1392 else
1393 {
1394 /* Trying to do a partial write to an unallocated block. Don't do
1395 * anything except letting the upper layer know what to do. */
1396 *pcbPreRead = offWrite % getImageBlockSize(&pImage->Header);
1397 *pcbPostRead = getImageBlockSize(&pImage->Header) - cbToWrite - *pcbPreRead;
1398 rc = VERR_VD_BLOCK_FREE;
1399 }
1400 }
1401 else
1402 {
1403 /* Block present in image file, write relevant data. */
1404 uint64_t u64Offset = (uint64_t)pImage->paBlocks[uBlock] * pImage->cbTotalBlockData
1405 + (pImage->offStartData + pImage->offStartBlockData + offWrite);
1406 rc = vdiFileWriteSync(pImage, u64Offset, pvBuf, cbToWrite, NULL);
1407 }
1408 } while (0);
1409
1410 if (pcbWriteProcess)
1411 *pcbWriteProcess = cbToWrite;
1412
1413out:
1414 LogFlowFunc(("returns %Rrc\n", rc));
1415 return rc;
1416}
1417
1418/** @copydoc VBOXHDDBACKEND::pfnFlush */
1419static int vdiFlush(void *pBackendData)
1420{
1421 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
1422 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1423 int rc = VINF_SUCCESS;
1424
1425 Assert(pImage);
1426
1427 vdiFlushImage(pImage);
1428 LogFlowFunc(("returns %Rrc\n", rc));
1429 return rc;
1430}
1431
1432/** @copydoc VBOXHDDBACKEND::pfnGetVersion */
1433static unsigned vdiGetVersion(void *pBackendData)
1434{
1435 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
1436 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1437 unsigned uVersion;
1438
1439 AssertPtr(pImage);
1440
1441 if (pImage)
1442 uVersion = pImage->PreHeader.u32Version;
1443 else
1444 uVersion = 0;
1445
1446 LogFlowFunc(("returns %#x\n", uVersion));
1447 return uVersion;
1448}
1449
1450/** @copydoc VBOXHDDBACKEND::pfnGetSize */
1451static uint64_t vdiGetSize(void *pBackendData)
1452{
1453 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
1454 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1455 uint64_t cbSize;
1456
1457 AssertPtr(pImage);
1458
1459 if (pImage)
1460 cbSize = getImageDiskSize(&pImage->Header);
1461 else
1462 cbSize = 0;
1463
1464 LogFlowFunc(("returns %llu\n", cbSize));
1465 return cbSize;
1466}
1467
1468/** @copydoc VBOXHDDBACKEND::pfnGetFileSize */
1469static uint64_t vdiGetFileSize(void *pBackendData)
1470{
1471 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
1472 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1473 uint64_t cb = 0;
1474
1475 AssertPtr(pImage);
1476
1477 if (pImage)
1478 {
1479 uint64_t cbFile;
1480 if (vdiFileOpened(pImage))
1481 {
1482 int rc = vdiFileGetSize(pImage, &cbFile);
1483 if (RT_SUCCESS(rc))
1484 cb += cbFile;
1485 }
1486 }
1487
1488 LogFlowFunc(("returns %lld\n", cb));
1489 return cb;
1490}
1491
1492/** @copydoc VBOXHDDBACKEND::pfnGetPCHSGeometry */
1493static int vdiGetPCHSGeometry(void *pBackendData,
1494 PPDMMEDIAGEOMETRY pPCHSGeometry)
1495{
1496 LogFlowFunc(("pBackendData=%#p pPCHSGeometry=%#p\n", pBackendData, pPCHSGeometry));
1497 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1498 int rc;
1499
1500 AssertPtr(pImage);
1501
1502 if (pImage)
1503 {
1504 if (pImage->PCHSGeometry.cCylinders)
1505 {
1506 *pPCHSGeometry = pImage->PCHSGeometry;
1507 rc = VINF_SUCCESS;
1508 }
1509 else
1510 rc = VERR_VD_GEOMETRY_NOT_SET;
1511 }
1512 else
1513 rc = VERR_VD_NOT_OPENED;
1514
1515 LogFlowFunc(("returns %Rrc (PCHS=%u/%u/%u)\n", rc, pPCHSGeometry->cCylinders, pPCHSGeometry->cHeads, pPCHSGeometry->cSectors));
1516 return rc;
1517}
1518
1519/** @copydoc VBOXHDDBACKEND::pfnSetPCHSGeometry */
1520static int vdiSetPCHSGeometry(void *pBackendData,
1521 PCPDMMEDIAGEOMETRY pPCHSGeometry)
1522{
1523 LogFlowFunc(("pBackendData=%#p pPCHSGeometry=%#p PCHS=%u/%u/%u\n", pBackendData, pPCHSGeometry, pPCHSGeometry->cCylinders, pPCHSGeometry->cHeads, pPCHSGeometry->cSectors));
1524 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1525 int rc;
1526
1527 AssertPtr(pImage);
1528
1529 if (pImage)
1530 {
1531 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
1532 {
1533 rc = VERR_VD_IMAGE_READ_ONLY;
1534 goto out;
1535 }
1536
1537 pImage->PCHSGeometry = *pPCHSGeometry;
1538 rc = VINF_SUCCESS;
1539 }
1540 else
1541 rc = VERR_VD_NOT_OPENED;
1542
1543out:
1544 LogFlowFunc(("returns %Rrc\n", rc));
1545 return rc;
1546}
1547
1548/** @copydoc VBOXHDDBACKEND::pfnGetLCHSGeometry */
1549static int vdiGetLCHSGeometry(void *pBackendData,
1550 PPDMMEDIAGEOMETRY pLCHSGeometry)
1551{
1552 LogFlowFunc(("pBackendData=%#p pLCHSGeometry=%#p\n", pBackendData, pLCHSGeometry));
1553 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1554 int rc;
1555
1556 AssertPtr(pImage);
1557
1558 if (pImage)
1559 {
1560 VDIDISKGEOMETRY DummyGeo = { 0, 0, 0, VDI_GEOMETRY_SECTOR_SIZE };
1561 PVDIDISKGEOMETRY pGeometry = getImageLCHSGeometry(&pImage->Header);
1562 if (!pGeometry)
1563 pGeometry = &DummyGeo;
1564
1565 if ( pGeometry->cCylinders > 0
1566 && pGeometry->cHeads > 0
1567 && pGeometry->cSectors > 0)
1568 {
1569 pLCHSGeometry->cCylinders = pGeometry->cCylinders;
1570 pLCHSGeometry->cHeads = pGeometry->cHeads;
1571 pLCHSGeometry->cSectors = pGeometry->cSectors;
1572 rc = VINF_SUCCESS;
1573 }
1574 else
1575 rc = VERR_VD_GEOMETRY_NOT_SET;
1576 }
1577 else
1578 rc = VERR_VD_NOT_OPENED;
1579
1580 LogFlowFunc(("returns %Rrc (LCHS=%u/%u/%u)\n", rc, pLCHSGeometry->cCylinders, pLCHSGeometry->cHeads, pLCHSGeometry->cSectors));
1581 return rc;
1582}
1583
1584/** @copydoc VBOXHDDBACKEND::pfnSetLCHSGeometry */
1585static int vdiSetLCHSGeometry(void *pBackendData,
1586 PCPDMMEDIAGEOMETRY pLCHSGeometry)
1587{
1588 LogFlowFunc(("pBackendData=%#p pLCHSGeometry=%#p LCHS=%u/%u/%u\n", pBackendData, pLCHSGeometry, pLCHSGeometry->cCylinders, pLCHSGeometry->cHeads, pLCHSGeometry->cSectors));
1589 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1590 PVDIDISKGEOMETRY pGeometry;
1591 int rc;
1592
1593 AssertPtr(pImage);
1594
1595 if (pImage)
1596 {
1597 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
1598 {
1599 rc = VERR_VD_IMAGE_READ_ONLY;
1600 goto out;
1601 }
1602
1603 pGeometry = getImageLCHSGeometry(&pImage->Header);
1604 if (pGeometry)
1605 {
1606 pGeometry->cCylinders = pLCHSGeometry->cCylinders;
1607 pGeometry->cHeads = pLCHSGeometry->cHeads;
1608 pGeometry->cSectors = pLCHSGeometry->cSectors;
1609 pGeometry->cbSector = VDI_GEOMETRY_SECTOR_SIZE;
1610
1611 /* Update header information in base image file. */
1612 vdiFlushImage(pImage);
1613 }
1614 rc = VINF_SUCCESS;
1615 }
1616 else
1617 rc = VERR_VD_NOT_OPENED;
1618
1619out:
1620 LogFlowFunc(("returns %Rrc\n", rc));
1621 return rc;
1622}
1623
1624/** @copydoc VBOXHDDBACKEND::pfnGetImageFlags */
1625static unsigned vdiGetImageFlags(void *pBackendData)
1626{
1627 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
1628 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1629 unsigned uImageFlags;
1630
1631 AssertPtr(pImage);
1632
1633 if (pImage)
1634 uImageFlags = pImage->uImageFlags;
1635 else
1636 uImageFlags = 0;
1637
1638 LogFlowFunc(("returns %#x\n", uImageFlags));
1639 return uImageFlags;
1640}
1641
1642/** @copydoc VBOXHDDBACKEND::pfnGetOpenFlags */
1643static unsigned vdiGetOpenFlags(void *pBackendData)
1644{
1645 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
1646 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1647 unsigned uOpenFlags;
1648
1649 AssertPtr(pImage);
1650
1651 if (pImage)
1652 uOpenFlags = pImage->uOpenFlags;
1653 else
1654 uOpenFlags = 0;
1655
1656 LogFlowFunc(("returns %#x\n", uOpenFlags));
1657 return uOpenFlags;
1658}
1659
1660/** @copydoc VBOXHDDBACKEND::pfnSetOpenFlags */
1661static int vdiSetOpenFlags(void *pBackendData, unsigned uOpenFlags)
1662{
1663 LogFlowFunc(("pBackendData=%#p uOpenFlags=%#x\n", pBackendData, uOpenFlags));
1664 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1665 int rc;
1666 const char *pszFilename;
1667
1668 /* Image must be opened and the new flags must be valid. Just readonly and
1669 * info flags are supported. */
1670 if (!pImage || (uOpenFlags & ~(VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_INFO | VD_OPEN_FLAGS_ASYNC_IO | VD_OPEN_FLAGS_SHAREABLE)))
1671 {
1672 rc = VERR_INVALID_PARAMETER;
1673 goto out;
1674 }
1675
1676 /* Implement this operation via reopening the image. */
1677 pszFilename = pImage->pszFilename;
1678 vdiFreeImage(pImage, false);
1679 rc = vdiOpenImage(pImage, uOpenFlags);
1680
1681out:
1682 LogFlowFunc(("returns %Rrc\n", rc));
1683 return rc;
1684}
1685
1686/** @copydoc VBOXHDDBACKEND::pfnGetComment */
1687static int vdiGetComment(void *pBackendData, char *pszComment,
1688 size_t cbComment)
1689{
1690 LogFlowFunc(("pBackendData=%#p pszComment=%#p cbComment=%zu\n", pBackendData, pszComment, cbComment));
1691 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1692 int rc = VINF_SUCCESS;
1693
1694 AssertPtr(pImage);
1695
1696 if (pImage)
1697 {
1698 char *pszTmp = getImageComment(&pImage->Header);
1699 size_t cb = strlen(pszTmp);
1700 if (cb < cbComment)
1701 {
1702 /* memcpy is much better than strncpy. */
1703 memcpy(pszComment, pszTmp, cb + 1);
1704 }
1705 else
1706 rc = VERR_BUFFER_OVERFLOW;
1707 }
1708 else
1709 rc = VERR_VD_NOT_OPENED;
1710
1711 LogFlowFunc(("returns %Rrc comment=\"%s\"\n", rc, pszComment));
1712 return rc;
1713}
1714
1715/** @copydoc VBOXHDDBACKEND::pfnGetComment */
1716static int vdiSetComment(void *pBackendData, const char *pszComment)
1717{
1718 LogFlowFunc(("pBackendData=%#p pszComment=\"%s\"\n", pBackendData, pszComment));
1719 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1720 int rc;
1721
1722 AssertPtr(pImage);
1723
1724 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
1725 {
1726 rc = VERR_VD_IMAGE_READ_ONLY;
1727 goto out;
1728 }
1729
1730 if (pImage)
1731 {
1732 size_t cchComment = pszComment ? strlen(pszComment) : 0;
1733 if (cchComment >= VDI_IMAGE_COMMENT_SIZE)
1734 {
1735 LogFunc(("pszComment is too long, %d bytes!\n", cchComment));
1736 rc = VERR_VD_VDI_COMMENT_TOO_LONG;
1737 goto out;
1738 }
1739
1740 /* we don't support old style images */
1741 if (GET_MAJOR_HEADER_VERSION(&pImage->Header) == 1)
1742 {
1743 /*
1744 * Update the comment field, making sure to zero out all of the previous comment.
1745 */
1746 memset(pImage->Header.u.v1.szComment, '\0', VDI_IMAGE_COMMENT_SIZE);
1747 memcpy(pImage->Header.u.v1.szComment, pszComment, cchComment);
1748
1749 /* write out new the header */
1750 rc = vdiUpdateHeader(pImage);
1751 }
1752 else
1753 rc = VERR_VD_VDI_UNSUPPORTED_VERSION;
1754 }
1755 else
1756 rc = VERR_VD_NOT_OPENED;
1757
1758out:
1759 LogFlowFunc(("returns %Rrc\n", rc));
1760 return rc;
1761}
1762
1763/** @copydoc VBOXHDDBACKEND::pfnGetUuid */
1764static int vdiGetUuid(void *pBackendData, PRTUUID pUuid)
1765{
1766 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
1767 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1768 int rc;
1769
1770 AssertPtr(pImage);
1771
1772 if (pImage)
1773 {
1774 *pUuid = *getImageCreationUUID(&pImage->Header);
1775 rc = VINF_SUCCESS;
1776 }
1777 else
1778 rc = VERR_VD_NOT_OPENED;
1779
1780 LogFlowFunc(("returns %Rrc (%RTuuid)\n", rc, pUuid));
1781 return rc;
1782}
1783
1784/** @copydoc VBOXHDDBACKEND::pfnSetUuid */
1785static int vdiSetUuid(void *pBackendData, PCRTUUID pUuid)
1786{
1787 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
1788 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1789 int rc = VINF_SUCCESS;
1790
1791 AssertPtr(pImage);
1792
1793 if (pImage)
1794 {
1795 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
1796 {
1797 if (GET_MAJOR_HEADER_VERSION(&pImage->Header) == 1)
1798 pImage->Header.u.v1.uuidCreate = *pUuid;
1799 /* Make it possible to clone old VDIs. */
1800 else if (GET_MAJOR_HEADER_VERSION(&pImage->Header) == 0)
1801 pImage->Header.u.v0.uuidCreate = *pUuid;
1802 else
1803 {
1804 LogFunc(("Version is not supported!\n"));
1805 rc = VERR_VD_VDI_UNSUPPORTED_VERSION;
1806 }
1807 }
1808 else
1809 rc = VERR_VD_IMAGE_READ_ONLY;
1810 }
1811 else
1812 rc = VERR_VD_NOT_OPENED;
1813
1814 LogFlowFunc(("returns %Rrc\n", rc));
1815 return rc;
1816}
1817
1818/** @copydoc VBOXHDDBACKEND::pfnGetModificationUuid */
1819static int vdiGetModificationUuid(void *pBackendData, PRTUUID pUuid)
1820{
1821 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
1822 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1823 int rc;
1824
1825 AssertPtr(pImage);
1826
1827 if (pImage)
1828 {
1829 *pUuid = *getImageModificationUUID(&pImage->Header);
1830 rc = VINF_SUCCESS;
1831 }
1832 else
1833 rc = VERR_VD_NOT_OPENED;
1834
1835 LogFlowFunc(("returns %Rrc (%RTuuid)\n", rc, pUuid));
1836 return rc;
1837}
1838
1839/** @copydoc VBOXHDDBACKEND::pfnSetModificationUuid */
1840static int vdiSetModificationUuid(void *pBackendData, PCRTUUID pUuid)
1841{
1842 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
1843 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1844 int rc = VINF_SUCCESS;
1845
1846 AssertPtr(pImage);
1847
1848 if (pImage)
1849 {
1850 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
1851 {
1852 if (GET_MAJOR_HEADER_VERSION(&pImage->Header) == 1)
1853 pImage->Header.u.v1.uuidModify = *pUuid;
1854 /* Make it possible to clone old VDIs. */
1855 else if (GET_MAJOR_HEADER_VERSION(&pImage->Header) == 0)
1856 pImage->Header.u.v0.uuidModify = *pUuid;
1857 else
1858 {
1859 LogFunc(("Version is not supported!\n"));
1860 rc = VERR_VD_VDI_UNSUPPORTED_VERSION;
1861 }
1862 }
1863 else
1864 rc = VERR_VD_IMAGE_READ_ONLY;
1865 }
1866 else
1867 rc = VERR_VD_NOT_OPENED;
1868
1869 LogFlowFunc(("returns %Rrc\n", rc));
1870 return rc;
1871}
1872
1873/** @copydoc VBOXHDDBACKEND::pfnGetParentUuid */
1874static int vdiGetParentUuid(void *pBackendData, PRTUUID pUuid)
1875{
1876 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
1877 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1878 int rc;
1879
1880 AssertPtr(pImage);
1881
1882 if (pImage)
1883 {
1884 *pUuid = *getImageParentUUID(&pImage->Header);
1885 rc = VINF_SUCCESS;
1886 }
1887 else
1888 rc = VERR_VD_NOT_OPENED;
1889
1890 LogFlowFunc(("returns %Rrc (%RTuuid)\n", rc, pUuid));
1891 return rc;
1892}
1893
1894/** @copydoc VBOXHDDBACKEND::pfnSetParentUuid */
1895static int vdiSetParentUuid(void *pBackendData, PCRTUUID pUuid)
1896{
1897 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
1898 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1899 int rc = VINF_SUCCESS;
1900
1901 AssertPtr(pImage);
1902
1903 if (pImage)
1904 {
1905 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
1906 {
1907 if (GET_MAJOR_HEADER_VERSION(&pImage->Header) == 1)
1908 pImage->Header.u.v1.uuidLinkage = *pUuid;
1909 /* Make it possible to clone old VDIs. */
1910 else if (GET_MAJOR_HEADER_VERSION(&pImage->Header) == 0)
1911 pImage->Header.u.v0.uuidLinkage = *pUuid;
1912 else
1913 {
1914 LogFunc(("Version is not supported!\n"));
1915 rc = VERR_VD_VDI_UNSUPPORTED_VERSION;
1916 }
1917 }
1918 else
1919 rc = VERR_VD_IMAGE_READ_ONLY;
1920 }
1921 else
1922 rc = VERR_VD_NOT_OPENED;
1923
1924 LogFlowFunc(("returns %Rrc\n", rc));
1925 return rc;
1926}
1927
1928/** @copydoc VBOXHDDBACKEND::pfnGetParentModificationUuid */
1929static int vdiGetParentModificationUuid(void *pBackendData, PRTUUID pUuid)
1930{
1931 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
1932 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1933 int rc;
1934
1935 AssertPtr(pImage);
1936
1937 if (pImage)
1938 {
1939 *pUuid = *getImageParentModificationUUID(&pImage->Header);
1940 rc = VINF_SUCCESS;
1941 }
1942 else
1943 rc = VERR_VD_NOT_OPENED;
1944
1945 LogFlowFunc(("returns %Rrc (%RTuuid)\n", rc, pUuid));
1946 return rc;
1947}
1948
1949/** @copydoc VBOXHDDBACKEND::pfnSetParentModificationUuid */
1950static int vdiSetParentModificationUuid(void *pBackendData, PCRTUUID pUuid)
1951{
1952 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
1953 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1954 int rc = VINF_SUCCESS;
1955
1956 AssertPtr(pImage);
1957
1958 if (pImage)
1959 {
1960 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
1961 {
1962 if (GET_MAJOR_HEADER_VERSION(&pImage->Header) == 1)
1963 pImage->Header.u.v1.uuidParentModify = *pUuid;
1964 else
1965 {
1966 LogFunc(("Version is not supported!\n"));
1967 rc = VERR_VD_VDI_UNSUPPORTED_VERSION;
1968 }
1969 }
1970 else
1971 rc = VERR_VD_IMAGE_READ_ONLY;
1972 }
1973 else
1974 rc = VERR_VD_NOT_OPENED;
1975
1976 LogFlowFunc(("returns %Rrc\n", rc));
1977 return rc;
1978}
1979
1980/** @copydoc VBOXHDDBACKEND::pfnDump */
1981static void vdiDump(void *pBackendData)
1982{
1983 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1984
1985#ifndef VBOX_WITH_NEW_IO_CODE
1986 pImage->pInterfaceErrorCallbacks->pfnMessage(pImage->pInterfaceError->pvUser, "Dumping VDI image \"%s\" mode=%s uOpenFlags=%X File=%08X\n",
1987 pImage->pszFilename,
1988 (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY) ? "r/o" : "r/w",
1989 pImage->uOpenFlags,
1990 pImage->File);
1991#else
1992 pImage->pInterfaceErrorCallbacks->pfnMessage(pImage->pInterfaceError->pvUser, "Dumping VDI image \"%s\" mode=%s uOpenFlags=%X File=%#p\n",
1993 pImage->pszFilename,
1994 (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY) ? "r/o" : "r/w",
1995 pImage->uOpenFlags,
1996 pImage->pStorage);
1997#endif
1998 pImage->pInterfaceErrorCallbacks->pfnMessage(pImage->pInterfaceError->pvUser, "Header: Version=%08X Type=%X Flags=%X Size=%llu\n",
1999 pImage->PreHeader.u32Version,
2000 getImageType(&pImage->Header),
2001 getImageFlags(&pImage->Header),
2002 getImageDiskSize(&pImage->Header));
2003 pImage->pInterfaceErrorCallbacks->pfnMessage(pImage->pInterfaceError->pvUser, "Header: cbBlock=%u cbBlockExtra=%u cBlocks=%u cBlocksAllocated=%u\n",
2004 getImageBlockSize(&pImage->Header),
2005 getImageExtraBlockSize(&pImage->Header),
2006 getImageBlocks(&pImage->Header),
2007 getImageBlocksAllocated(&pImage->Header));
2008 pImage->pInterfaceErrorCallbacks->pfnMessage(pImage->pInterfaceError->pvUser, "Header: offBlocks=%u offData=%u\n",
2009 getImageBlocksOffset(&pImage->Header),
2010 getImageDataOffset(&pImage->Header));
2011 PVDIDISKGEOMETRY pg = getImageLCHSGeometry(&pImage->Header);
2012 if (pg)
2013 pImage->pInterfaceErrorCallbacks->pfnMessage(pImage->pInterfaceError->pvUser, "Header: Geometry: C/H/S=%u/%u/%u cbSector=%u\n",
2014 pg->cCylinders, pg->cHeads, pg->cSectors, pg->cbSector);
2015 pImage->pInterfaceErrorCallbacks->pfnMessage(pImage->pInterfaceError->pvUser, "Header: uuidCreation={%RTuuid}\n", getImageCreationUUID(&pImage->Header));
2016 pImage->pInterfaceErrorCallbacks->pfnMessage(pImage->pInterfaceError->pvUser, "Header: uuidModification={%RTuuid}\n", getImageModificationUUID(&pImage->Header));
2017 pImage->pInterfaceErrorCallbacks->pfnMessage(pImage->pInterfaceError->pvUser, "Header: uuidParent={%RTuuid}\n", getImageParentUUID(&pImage->Header));
2018 if (GET_MAJOR_HEADER_VERSION(&pImage->Header) >= 1)
2019 pImage->pInterfaceErrorCallbacks->pfnMessage(pImage->pInterfaceError->pvUser, "Header: uuidParentModification={%RTuuid}\n", getImageParentModificationUUID(&pImage->Header));
2020 pImage->pInterfaceErrorCallbacks->pfnMessage(pImage->pInterfaceError->pvUser, "Image: fFlags=%08X offStartBlocks=%u offStartData=%u\n",
2021 pImage->uImageFlags, pImage->offStartBlocks, pImage->offStartData);
2022 pImage->pInterfaceErrorCallbacks->pfnMessage(pImage->pInterfaceError->pvUser, "Image: uBlockMask=%08X cbTotalBlockData=%u uShiftOffset2Index=%u offStartBlockData=%u\n",
2023 pImage->uBlockMask,
2024 pImage->cbTotalBlockData,
2025 pImage->uShiftOffset2Index,
2026 pImage->offStartBlockData);
2027
2028 unsigned uBlock, cBlocksNotFree, cBadBlocks, cBlocks = getImageBlocks(&pImage->Header);
2029 for (uBlock=0, cBlocksNotFree=0, cBadBlocks=0; uBlock<cBlocks; uBlock++)
2030 {
2031 if (IS_VDI_IMAGE_BLOCK_ALLOCATED(pImage->paBlocks[uBlock]))
2032 {
2033 cBlocksNotFree++;
2034 if (pImage->paBlocks[uBlock] >= cBlocks)
2035 cBadBlocks++;
2036 }
2037 }
2038 if (cBlocksNotFree != getImageBlocksAllocated(&pImage->Header))
2039 {
2040 pImage->pInterfaceErrorCallbacks->pfnMessage(pImage->pInterfaceError->pvUser, "!! WARNING: %u blocks actually allocated (cBlocksAllocated=%u) !!\n",
2041 cBlocksNotFree, getImageBlocksAllocated(&pImage->Header));
2042 }
2043 if (cBadBlocks)
2044 {
2045 pImage->pInterfaceErrorCallbacks->pfnMessage(pImage->pInterfaceError->pvUser, "!! WARNING: %u bad blocks found !!\n",
2046 cBadBlocks);
2047 }
2048}
2049
2050static int vdiGetTimeStamp(void *pBackendData, PRTTIMESPEC pTimeStamp)
2051{
2052 int rc = VERR_NOT_IMPLEMENTED;
2053 LogFlow(("%s: returned %Rrc\n", __FUNCTION__, rc));
2054 return rc;
2055}
2056
2057static int vdiGetParentTimeStamp(void *pBackendData, PRTTIMESPEC pTimeStamp)
2058{
2059 int rc = VERR_NOT_IMPLEMENTED;
2060 LogFlow(("%s: returned %Rrc\n", __FUNCTION__, rc));
2061 return rc;
2062}
2063
2064static int vdiSetParentTimeStamp(void *pBackendData, PCRTTIMESPEC pTimeStamp)
2065{
2066 int rc = VERR_NOT_IMPLEMENTED;
2067 LogFlow(("%s: returned %Rrc\n", __FUNCTION__, rc));
2068 return rc;
2069}
2070
2071static int vdiGetParentFilename(void *pBackendData, char **ppszParentFilename)
2072{
2073 int rc = VERR_NOT_IMPLEMENTED;
2074 LogFlow(("%s: returned %Rrc\n", __FUNCTION__, rc));
2075 return rc;
2076}
2077
2078static int vdiSetParentFilename(void *pBackendData, const char *pszParentFilename)
2079{
2080 int rc = VERR_NOT_IMPLEMENTED;
2081 LogFlow(("%s: returned %Rrc\n", __FUNCTION__, rc));
2082 return rc;
2083}
2084
2085static bool vdiIsAsyncIOSupported(void *pBackendData)
2086{
2087 return true;
2088}
2089
2090static int vdiAsyncRead(void *pvBackendData, uint64_t uOffset, size_t cbToRead,
2091 PVDIOCTX pIoCtx, size_t *pcbActuallyRead)
2092{
2093 LogFlowFunc(("pvBackendData=%#p uOffset=%llu pIoCtx=%#p cbToRead=%zu pcbActuallyRead=%#p\n",
2094 pvBackendData, uOffset, pIoCtx, cbToRead, pcbActuallyRead));
2095 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pvBackendData;
2096 unsigned uBlock;
2097 unsigned offRead;
2098 int rc;
2099
2100 AssertPtr(pImage);
2101 Assert(!(uOffset % 512));
2102 Assert(!(cbToRead % 512));
2103
2104 if ( uOffset + cbToRead > getImageDiskSize(&pImage->Header)
2105 || !VALID_PTR(pIoCtx)
2106 || !cbToRead)
2107 {
2108 rc = VERR_INVALID_PARAMETER;
2109 goto out;
2110 }
2111
2112 /* Calculate starting block number and offset inside it. */
2113 uBlock = (unsigned)(uOffset >> pImage->uShiftOffset2Index);
2114 offRead = (unsigned)uOffset & pImage->uBlockMask;
2115
2116 /* Clip read range to at most the rest of the block. */
2117 cbToRead = RT_MIN(cbToRead, getImageBlockSize(&pImage->Header) - offRead);
2118 Assert(!(cbToRead % 512));
2119
2120 if (pImage->paBlocks[uBlock] == VDI_IMAGE_BLOCK_FREE)
2121 rc = VERR_VD_BLOCK_FREE;
2122 else if (pImage->paBlocks[uBlock] == VDI_IMAGE_BLOCK_ZERO)
2123 {
2124 size_t cbSet;
2125
2126 cbSet = pImage->pInterfaceIOCallbacks->pfnIoCtxSet(pImage->pInterfaceIO->pvUser,
2127 pIoCtx, 0, cbToRead);
2128 Assert(cbSet == cbToRead);
2129
2130 rc = VINF_SUCCESS;
2131 }
2132 else
2133 {
2134 /* Block present in image file, read relevant data. */
2135 uint64_t u64Offset = (uint64_t)pImage->paBlocks[uBlock] * pImage->cbTotalBlockData
2136 + (pImage->offStartData + pImage->offStartBlockData + offRead);
2137 rc = pImage->pInterfaceIOCallbacks->pfnReadUserAsync(pImage->pInterfaceIO->pvUser,
2138 pImage->pStorage,
2139 u64Offset,
2140 pIoCtx, cbToRead);
2141 }
2142
2143 if (pcbActuallyRead)
2144 *pcbActuallyRead = cbToRead;
2145
2146out:
2147 LogFlowFunc(("returns %Rrc\n", rc));
2148 return rc;
2149}
2150
2151static int vdiAsyncWrite(void *pvBackendData, uint64_t uOffset, size_t cbToWrite,
2152 PVDIOCTX pIoCtx,
2153 size_t *pcbWriteProcess, size_t *pcbPreRead,
2154 size_t *pcbPostRead, unsigned fWrite)
2155{
2156 LogFlowFunc(("pvBackendData=%#p uOffset=%llu pIoCtx=%#p cbToWrite=%zu pcbWriteProcess=%#p pcbPreRead=%#p pcbPostRead=%#p\n",
2157 pvBackendData, uOffset, pIoCtx, cbToWrite, pcbWriteProcess, pcbPreRead, pcbPostRead));
2158 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pvBackendData;
2159 unsigned uBlock;
2160 unsigned offWrite;
2161 int rc = VINF_SUCCESS;
2162
2163 AssertPtr(pImage);
2164 Assert(!(uOffset % 512));
2165 Assert(!(cbToWrite % 512));
2166
2167 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
2168 {
2169 rc = VERR_VD_IMAGE_READ_ONLY;
2170 goto out;
2171 }
2172
2173 if (!VALID_PTR(pIoCtx) || !cbToWrite)
2174 {
2175 rc = VERR_INVALID_PARAMETER;
2176 goto out;
2177 }
2178
2179 /* No size check here, will do that later. For dynamic images which are
2180 * not multiples of the block size in length, this would prevent writing to
2181 * the last grain. */
2182
2183 /* Calculate starting block number and offset inside it. */
2184 uBlock = (unsigned)(uOffset >> pImage->uShiftOffset2Index);
2185 offWrite = (unsigned)uOffset & pImage->uBlockMask;
2186
2187 /* Clip write range to at most the rest of the block. */
2188 cbToWrite = RT_MIN(cbToWrite, getImageBlockSize(&pImage->Header) - offWrite);
2189 Assert(!(cbToWrite % 512));
2190
2191 do
2192 {
2193 if (!IS_VDI_IMAGE_BLOCK_ALLOCATED(pImage->paBlocks[uBlock]))
2194 {
2195 /* Block is either free or zero. */
2196 if ( !(pImage->uOpenFlags & VD_OPEN_FLAGS_HONOR_ZEROES)
2197 && ( pImage->paBlocks[uBlock] == VDI_IMAGE_BLOCK_ZERO
2198 || cbToWrite == getImageBlockSize(&pImage->Header)))
2199 {
2200#if 0 /** @todo Provide interface to check an I/O context for a specific value */
2201 /* If the destination block is unallocated at this point, it's
2202 * either a zero block or a block which hasn't been used so far
2203 * (which also means that it's a zero block. Don't need to write
2204 * anything to this block if the data consists of just zeroes. */
2205 Assert(!(cbToWrite % 4));
2206 Assert(cbToWrite * 8 <= UINT32_MAX);
2207 if (ASMBitFirstSet((volatile void *)pvBuf, (uint32_t)cbToWrite * 8) == -1)
2208 {
2209 pImage->paBlocks[uBlock] = VDI_IMAGE_BLOCK_ZERO;
2210 break;
2211 }
2212#endif
2213 }
2214
2215 if (cbToWrite == getImageBlockSize(&pImage->Header))
2216 {
2217 /* Full block write to previously unallocated block.
2218 * Allocate block and write data. */
2219 Assert(!offWrite);
2220 unsigned cBlocksAllocated = getImageBlocksAllocated(&pImage->Header);
2221 uint64_t u64Offset = (uint64_t)cBlocksAllocated * pImage->cbTotalBlockData
2222 + (pImage->offStartData + pImage->offStartBlockData);
2223 rc = pImage->pInterfaceIOCallbacks->pfnWriteUserAsync(pImage->pInterfaceIO->pvUser,
2224 pImage->pStorage,
2225 u64Offset,
2226 pIoCtx, cbToWrite,
2227 NULL, NULL);
2228 if (RT_UNLIKELY(RT_FAILURE_NP(rc) && (rc != VERR_VD_ASYNC_IO_IN_PROGRESS)))
2229 goto out;
2230 pImage->paBlocks[uBlock] = cBlocksAllocated;
2231 setImageBlocksAllocated(&pImage->Header, cBlocksAllocated + 1);
2232
2233 rc = vdiUpdateBlockInfoAsync(pImage, uBlock, pIoCtx);
2234 if (RT_FAILURE(rc) && (rc != VERR_VD_ASYNC_IO_IN_PROGRESS))
2235 goto out;
2236
2237 *pcbPreRead = 0;
2238 *pcbPostRead = 0;
2239 }
2240 else
2241 {
2242 /* Trying to do a partial write to an unallocated block. Don't do
2243 * anything except letting the upper layer know what to do. */
2244 *pcbPreRead = offWrite % getImageBlockSize(&pImage->Header);
2245 *pcbPostRead = getImageBlockSize(&pImage->Header) - cbToWrite - *pcbPreRead;
2246 rc = VERR_VD_BLOCK_FREE;
2247 }
2248 }
2249 else
2250 {
2251 /* Block present in image file, write relevant data. */
2252 uint64_t u64Offset = (uint64_t)pImage->paBlocks[uBlock] * pImage->cbTotalBlockData
2253 + (pImage->offStartData + pImage->offStartBlockData + offWrite);
2254 rc = pImage->pInterfaceIOCallbacks->pfnWriteUserAsync(pImage->pInterfaceIO->pvUser,
2255 pImage->pStorage,
2256 u64Offset,
2257 pIoCtx, cbToWrite,
2258 NULL, NULL);
2259 }
2260 } while (0);
2261
2262 if (pcbWriteProcess)
2263 *pcbWriteProcess = cbToWrite;
2264
2265out:
2266 LogFlowFunc(("returns %Rrc\n", rc));
2267 return rc;
2268}
2269
2270static int vdiAsyncFlush(void *pvBackendData, PVDIOCTX pIoCtx)
2271{
2272 LogFlowFunc(("pBackendData=%#p\n", pvBackendData));
2273 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pvBackendData;
2274 int rc = VINF_SUCCESS;
2275
2276 Assert(pImage);
2277
2278 rc = vdiFlushImageAsync(pImage, pIoCtx);
2279 LogFlowFunc(("returns %Rrc\n", rc));
2280 return rc;
2281}
2282
2283/** @copydoc VBOXHDDBACKEND::pfnCompact */
2284static int vdiCompact(void *pBackendData, unsigned uPercentStart,
2285 unsigned uPercentSpan, PVDINTERFACE pVDIfsDisk,
2286 PVDINTERFACE pVDIfsImage, PVDINTERFACE pVDIfsOperation)
2287{
2288 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
2289 int rc = VINF_SUCCESS;
2290 void *pvBuf = NULL, *pvTmp = NULL;
2291 unsigned *paBlocks2 = NULL;
2292
2293 int (*pfnParentRead)(void *, uint64_t, void *, size_t) = NULL;
2294 void *pvParent = NULL;
2295 PVDINTERFACE pIfParentState = VDInterfaceGet(pVDIfsOperation,
2296 VDINTERFACETYPE_PARENTSTATE);
2297 PVDINTERFACEPARENTSTATE pCbParentState = NULL;
2298 if (pIfParentState)
2299 {
2300 pCbParentState = VDGetInterfaceParentState(pIfParentState);
2301 if (pCbParentState)
2302 pfnParentRead = pCbParentState->pfnParentRead;
2303 pvParent = pIfParentState->pvUser;
2304 }
2305
2306 PFNVDPROGRESS pfnProgress = NULL;
2307 void *pvUser = NULL;
2308 PVDINTERFACE pIfProgress = VDInterfaceGet(pVDIfsOperation,
2309 VDINTERFACETYPE_PROGRESS);
2310 PVDINTERFACEPROGRESS pCbProgress = NULL;
2311 if (pIfProgress)
2312 {
2313 pCbProgress = VDGetInterfaceProgress(pIfProgress);
2314 if (pCbProgress)
2315 pfnProgress = pCbProgress->pfnProgress;
2316 pvUser = pIfProgress->pvUser;
2317 }
2318
2319 do {
2320 AssertBreakStmt(pImage, rc = VERR_INVALID_PARAMETER);
2321
2322 AssertBreakStmt(!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY),
2323 rc = VERR_VD_IMAGE_READ_ONLY);
2324
2325 unsigned cBlocks;
2326 unsigned cBlocksToMove = 0;
2327 size_t cbBlock;
2328 cBlocks = getImageBlocks(&pImage->Header);
2329 cbBlock = getImageBlockSize(&pImage->Header);
2330 if (pfnParentRead)
2331 {
2332 pvBuf = RTMemTmpAlloc(cbBlock);
2333 AssertBreakStmt(VALID_PTR(pvBuf), rc = VERR_NO_MEMORY);
2334 }
2335 pvTmp = RTMemTmpAlloc(cbBlock);
2336 AssertBreakStmt(VALID_PTR(pvTmp), rc = VERR_NO_MEMORY);
2337
2338 uint64_t cbFile;
2339 rc = vdiFileGetSize(pImage, &cbFile);
2340 AssertRCBreak(rc);
2341 unsigned cBlocksAllocated = (unsigned)((cbFile - pImage->offStartData - pImage->offStartBlockData) >> pImage->uShiftOffset2Index);
2342 if (cBlocksAllocated == 0)
2343 {
2344 /* No data blocks in this image, no need to compact. */
2345 rc = VINF_SUCCESS;
2346 break;
2347 }
2348
2349 /* Allocate block array for back resolving. */
2350 paBlocks2 = (unsigned *)RTMemAlloc(sizeof(unsigned *) * cBlocksAllocated);
2351 AssertBreakStmt(VALID_PTR(paBlocks2), rc = VERR_NO_MEMORY);
2352 /* Fill out back resolving, check/fix allocation errors before
2353 * compacting the image, just to be on the safe side. Update the
2354 * image contents straight away, as this enables cancelling. */
2355 for (unsigned i = 0; i < cBlocksAllocated; i++)
2356 paBlocks2[i] = VDI_IMAGE_BLOCK_FREE;
2357 rc = VINF_SUCCESS;
2358 for (unsigned i = 0; i < cBlocks; i++)
2359 {
2360 VDIIMAGEBLOCKPOINTER ptrBlock = pImage->paBlocks[i];
2361 if (IS_VDI_IMAGE_BLOCK_ALLOCATED(ptrBlock))
2362 {
2363 if (ptrBlock < cBlocksAllocated)
2364 {
2365 if (paBlocks2[ptrBlock] == VDI_IMAGE_BLOCK_FREE)
2366 paBlocks2[ptrBlock] = i;
2367 else
2368 {
2369 LogFunc(("Freed cross-linked block %u in file \"%s\"\n",
2370 i, pImage->pszFilename));
2371 pImage->paBlocks[i] = VDI_IMAGE_BLOCK_FREE;
2372 rc = vdiUpdateBlockInfo(pImage, i);
2373 if (RT_FAILURE(rc))
2374 break;
2375 }
2376 }
2377 else
2378 {
2379 LogFunc(("Freed out of bounds reference for block %u in file \"%s\"\n",
2380 i, pImage->pszFilename));
2381 pImage->paBlocks[i] = VDI_IMAGE_BLOCK_FREE;
2382 rc = vdiUpdateBlockInfo(pImage, i);
2383 if (RT_FAILURE(rc))
2384 break;
2385 }
2386 }
2387 }
2388 if (RT_FAILURE(rc))
2389 break;
2390
2391 /* Find redundant information and update the block pointers
2392 * accordingly, creating bubbles. Keep disk up to date, as this
2393 * enables cancelling. */
2394 for (unsigned i = 0; i < cBlocks; i++)
2395 {
2396 VDIIMAGEBLOCKPOINTER ptrBlock = pImage->paBlocks[i];
2397 if (IS_VDI_IMAGE_BLOCK_ALLOCATED(ptrBlock))
2398 {
2399 /* Block present in image file, read relevant data. */
2400 uint64_t u64Offset = (uint64_t)ptrBlock * pImage->cbTotalBlockData
2401 + (pImage->offStartData + pImage->offStartBlockData);
2402 rc = vdiFileReadSync(pImage, u64Offset, pvTmp, cbBlock, NULL);
2403 if (RT_FAILURE(rc))
2404 break;
2405
2406 if (ASMBitFirstSet((volatile void *)pvTmp, (uint32_t)cbBlock * 8) == -1)
2407 {
2408 pImage->paBlocks[i] = VDI_IMAGE_BLOCK_ZERO;
2409 rc = vdiUpdateBlockInfo(pImage, i);
2410 if (RT_FAILURE(rc))
2411 break;
2412 paBlocks2[ptrBlock] = VDI_IMAGE_BLOCK_FREE;
2413 /* Adjust progress info, one block to be relocated. */
2414 cBlocksToMove++;
2415 }
2416 else if (pfnParentRead)
2417 {
2418 rc = pfnParentRead(pvParent, i * cbBlock, pvBuf, cbBlock);
2419 if (RT_FAILURE(rc))
2420 break;
2421 if (!memcmp(pvTmp, pvBuf, cbBlock))
2422 {
2423 pImage->paBlocks[i] = VDI_IMAGE_BLOCK_FREE;
2424 rc = vdiUpdateBlockInfo(pImage, i);
2425 if (RT_FAILURE(rc))
2426 break;
2427 paBlocks2[ptrBlock] = VDI_IMAGE_BLOCK_FREE;
2428 /* Adjust progress info, one block to be relocated. */
2429 cBlocksToMove++;
2430 }
2431 }
2432 }
2433
2434 if (pCbProgress && pCbProgress->pfnProgress)
2435 {
2436 rc = pCbProgress->pfnProgress(pIfProgress->pvUser,
2437 (uint64_t)i * uPercentSpan / (cBlocks + cBlocksToMove) + uPercentStart);
2438 if (RT_FAILURE(rc))
2439 break;
2440 }
2441 }
2442 if (RT_FAILURE(rc))
2443 break;
2444
2445 /* Fill bubbles with other data (if available). */
2446 unsigned cBlocksMoved = 0;
2447 unsigned uBlockUsedPos = cBlocksAllocated;
2448 for (unsigned i = 0; i < cBlocksAllocated; i++)
2449 {
2450 unsigned uBlock = paBlocks2[i];
2451 if (uBlock == VDI_IMAGE_BLOCK_FREE)
2452 {
2453 unsigned uBlockData = VDI_IMAGE_BLOCK_FREE;
2454 while (uBlockUsedPos > i && uBlockData == VDI_IMAGE_BLOCK_FREE)
2455 {
2456 uBlockUsedPos--;
2457 uBlockData = paBlocks2[uBlockUsedPos];
2458 }
2459 /* Terminate early if there is no block which needs copying. */
2460 if (uBlockUsedPos == i)
2461 break;
2462 uint64_t u64Offset = (uint64_t)uBlockUsedPos * pImage->cbTotalBlockData
2463 + (pImage->offStartData + pImage->offStartBlockData);
2464 rc = vdiFileReadSync(pImage, u64Offset, pvTmp, cbBlock, NULL);
2465 u64Offset = (uint64_t)i * pImage->cbTotalBlockData
2466 + (pImage->offStartData + pImage->offStartBlockData);
2467 rc = vdiFileWriteSync(pImage, u64Offset, pvTmp, cbBlock, NULL);
2468 pImage->paBlocks[uBlockData] = i;
2469 setImageBlocksAllocated(&pImage->Header, cBlocksAllocated - cBlocksMoved);
2470 rc = vdiUpdateBlockInfo(pImage, uBlockData);
2471 if (RT_FAILURE(rc))
2472 break;
2473 paBlocks2[i] = uBlockData;
2474 paBlocks2[uBlockUsedPos] = VDI_IMAGE_BLOCK_FREE;
2475 cBlocksMoved++;
2476 }
2477
2478 if (pCbProgress && pCbProgress->pfnProgress)
2479 {
2480 rc = pCbProgress->pfnProgress(pIfProgress->pvUser,
2481 (uint64_t)(cBlocks + cBlocksMoved) * uPercentSpan / (cBlocks + cBlocksToMove) + uPercentStart);
2482
2483 if (RT_FAILURE(rc))
2484 break;
2485 }
2486 }
2487 if (RT_FAILURE(rc))
2488 break;
2489
2490 /* Update image header. */
2491 setImageBlocksAllocated(&pImage->Header, uBlockUsedPos);
2492 vdiUpdateHeader(pImage);
2493
2494 /* Truncate the image to the proper size to finish compacting. */
2495 rc = vdiFileSetSize(pImage,
2496 (uint64_t)uBlockUsedPos * pImage->cbTotalBlockData
2497 + (pImage->offStartData + pImage->offStartBlockData));
2498 } while (0);
2499
2500 if (paBlocks2)
2501 RTMemTmpFree(paBlocks2);
2502 if (pvTmp)
2503 RTMemTmpFree(pvTmp);
2504 if (pvBuf)
2505 RTMemTmpFree(pvBuf);
2506
2507 if (RT_SUCCESS(rc) && pCbProgress && pCbProgress->pfnProgress)
2508 {
2509 pCbProgress->pfnProgress(pIfProgress->pvUser,
2510 uPercentStart + uPercentSpan);
2511 }
2512
2513 LogFlowFunc(("returns %Rrc\n", rc));
2514 return rc;
2515}
2516
2517
2518VBOXHDDBACKEND g_VDIBackend =
2519{
2520 /* pszBackendName */
2521 "VDI",
2522 /* cbSize */
2523 sizeof(VBOXHDDBACKEND),
2524 /* uBackendCaps */
2525 VD_CAP_UUID | VD_CAP_CREATE_FIXED | VD_CAP_CREATE_DYNAMIC
2526 | VD_CAP_DIFF | VD_CAP_FILE | VD_CAP_ASYNC,
2527 /* papszFileExtensions */
2528 s_apszVdiFileExtensions,
2529 /* paConfigInfo */
2530 NULL,
2531 /* hPlugin */
2532 NIL_RTLDRMOD,
2533 /* pfnCheckIfValid */
2534 vdiCheckIfValid,
2535 /* pfnOpen */
2536 vdiOpen,
2537 /* pfnCreate */
2538 vdiCreate,
2539 /* pfnRename */
2540 vdiRename,
2541 /* pfnClose */
2542 vdiClose,
2543 /* pfnRead */
2544 vdiRead,
2545 /* pfnWrite */
2546 vdiWrite,
2547 /* pfnFlush */
2548 vdiFlush,
2549 /* pfnGetVersion */
2550 vdiGetVersion,
2551 /* pfnGetSize */
2552 vdiGetSize,
2553 /* pfnGetFileSize */
2554 vdiGetFileSize,
2555 /* pfnGetPCHSGeometry */
2556 vdiGetPCHSGeometry,
2557 /* pfnSetPCHSGeometry */
2558 vdiSetPCHSGeometry,
2559 /* pfnGetLCHSGeometry */
2560 vdiGetLCHSGeometry,
2561 /* pfnSetLCHSGeometry */
2562 vdiSetLCHSGeometry,
2563 /* pfnGetImageFlags */
2564 vdiGetImageFlags,
2565 /* pfnGetOpenFlags */
2566 vdiGetOpenFlags,
2567 /* pfnSetOpenFlags */
2568 vdiSetOpenFlags,
2569 /* pfnGetComment */
2570 vdiGetComment,
2571 /* pfnSetComment */
2572 vdiSetComment,
2573 /* pfnGetUuid */
2574 vdiGetUuid,
2575 /* pfnSetUuid */
2576 vdiSetUuid,
2577 /* pfnGetModificationUuid */
2578 vdiGetModificationUuid,
2579 /* pfnSetModificationUuid */
2580 vdiSetModificationUuid,
2581 /* pfnGetParentUuid */
2582 vdiGetParentUuid,
2583 /* pfnSetParentUuid */
2584 vdiSetParentUuid,
2585 /* pfnGetParentModificationUuid */
2586 vdiGetParentModificationUuid,
2587 /* pfnSetParentModificationUuid */
2588 vdiSetParentModificationUuid,
2589 /* pfnDump */
2590 vdiDump,
2591 /* pfnGetTimeStamp */
2592 vdiGetTimeStamp,
2593 /* pfnGetParentTimeStamp */
2594 vdiGetParentTimeStamp,
2595 /* pfnSetParentTimeStamp */
2596 vdiSetParentTimeStamp,
2597 /* pfnGetParentFilename */
2598 vdiGetParentFilename,
2599 /* pfnSetParentFilename */
2600 vdiSetParentFilename,
2601 /* pfnIsAsyncIOSupported */
2602 vdiIsAsyncIOSupported,
2603 /* pfnAsyncRead */
2604 vdiAsyncRead,
2605 /* pfnAsyncWrite */
2606 vdiAsyncWrite,
2607 /* pfnAsyncFlush */
2608 vdiAsyncFlush,
2609 /* pfnComposeLocation */
2610 genericFileComposeLocation,
2611 /* pfnComposeName */
2612 genericFileComposeName,
2613 /* pfnCompact */
2614 vdiCompact
2615};
2616
Note: See TracBrowser for help on using the repository browser.

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette