VirtualBox

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

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

Main/Medium+Main/Console+Storage: Pass a flag for the medium type "Shareable" to the image format backends so that they can treat the files appropriately.

  • 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 break;
886 case 1:
887 if (pImage->Header.u.v1plus.cbHeader < sizeof(pImage->Header.u.v1plus))
888 rc = vdiFileWriteMetaAsync(pImage, sizeof(VDIPREHEADER),
889 &pImage->Header.u.v1, sizeof(pImage->Header.u.v1),
890 pIoCtx);
891 else
892 rc = vdiFileWriteMetaAsync(pImage, sizeof(VDIPREHEADER),
893 &pImage->Header.u.v1plus, sizeof(pImage->Header.u.v1plus),
894 pIoCtx);
895 break;
896 default:
897 rc = VERR_VD_VDI_UNSUPPORTED_VERSION;
898 break;
899 }
900 AssertMsg(RT_SUCCESS(rc) || rc == VERR_VD_ASYNC_IO_IN_PROGRESS,
901 ("vdiUpdateHeader failed, filename=\"%s\" rc=%Rrc\n", pImage->pszFilename, rc));
902 return rc;
903}
904
905/**
906 * Internal: Save block pointer to file, save header to file.
907 */
908static int vdiUpdateBlockInfo(PVDIIMAGEDESC pImage, unsigned uBlock)
909{
910 /* Update image header. */
911 int rc = vdiUpdateHeader(pImage);
912 if (RT_SUCCESS(rc))
913 {
914 /* write only one block pointer. */
915 rc = vdiFileWriteSync(pImage,
916 pImage->offStartBlocks + uBlock * sizeof(VDIIMAGEBLOCKPOINTER),
917 &pImage->paBlocks[uBlock],
918 sizeof(VDIIMAGEBLOCKPOINTER),
919 NULL);
920 AssertMsgRC(rc, ("vdiUpdateBlockInfo failed to update block=%u, filename=\"%s\", rc=%Rrc\n",
921 uBlock, pImage->pszFilename, rc));
922 }
923 return rc;
924}
925
926/**
927 * Internal: Save block pointer to file, save header to file - async version.
928 */
929static int vdiUpdateBlockInfoAsync(PVDIIMAGEDESC pImage, unsigned uBlock,
930 PVDIOCTX pIoCtx)
931{
932 /* Update image header. */
933 int rc = vdiUpdateHeaderAsync(pImage, pIoCtx);
934 if (RT_SUCCESS(rc) || rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
935 {
936 /* write only one block pointer. */
937 rc = vdiFileWriteMetaAsync(pImage,
938 pImage->offStartBlocks + uBlock * sizeof(VDIIMAGEBLOCKPOINTER),
939 &pImage->paBlocks[uBlock],
940 sizeof(VDIIMAGEBLOCKPOINTER),
941 pIoCtx);
942 AssertMsg(RT_SUCCESS(rc) || rc == VERR_VD_ASYNC_IO_IN_PROGRESS,
943 ("vdiUpdateBlockInfo failed to update block=%u, filename=\"%s\", rc=%Rrc\n",
944 uBlock, pImage->pszFilename, rc));
945 }
946 return rc;
947}
948
949/**
950 * Internal: Flush the image file to disk.
951 */
952static void vdiFlushImage(PVDIIMAGEDESC pImage)
953{
954 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
955 {
956 /* Save header. */
957 int rc = vdiUpdateHeader(pImage);
958 AssertMsgRC(rc, ("vdiUpdateHeader() failed, filename=\"%s\", rc=%Rrc\n",
959 pImage->pszFilename, rc));
960 vdiFileFlushSync(pImage);
961 }
962}
963
964/**
965 * Internal: Flush the image file to disk - async version.
966 */
967static int vdiFlushImageAsync(PVDIIMAGEDESC pImage, PVDIOCTX pIoCtx)
968{
969 int rc = VINF_SUCCESS;
970
971 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
972 {
973 /* Save header. */
974 rc = vdiUpdateHeaderAsync(pImage, pIoCtx);
975 AssertMsg(RT_SUCCESS(rc) || rc == VERR_VD_ASYNC_IO_IN_PROGRESS,
976 ("vdiUpdateHeaderAsync() failed, filename=\"%s\", rc=%Rrc\n",
977 pImage->pszFilename, rc));
978 rc = vdiFileFlushAsync(pImage, pIoCtx);
979 AssertMsg(RT_SUCCESS(rc) || rc == VERR_VD_ASYNC_IO_IN_PROGRESS,
980 ("Flushing data to disk failed rc=%Rrc\n", rc));
981 }
982
983 return rc;
984}
985
986/**
987 * Internal: Free all allocated space for representing an image, and optionally
988 * delete the image from disk.
989 */
990static void vdiFreeImage(PVDIIMAGEDESC pImage, bool fDelete)
991{
992 AssertPtr(pImage);
993
994 if (vdiFileOpened(pImage))
995 {
996 vdiFlushImage(pImage);
997 vdiFileClose(pImage);
998 }
999 if (pImage->paBlocks)
1000 {
1001 RTMemFree(pImage->paBlocks);
1002 pImage->paBlocks = NULL;
1003 }
1004 if (fDelete && pImage->pszFilename)
1005 RTFileDelete(pImage->pszFilename);
1006}
1007
1008
1009/** @copydoc VBOXHDDBACKEND::pfnCheckIfValid */
1010static int vdiCheckIfValid(const char *pszFilename, PVDINTERFACE pVDIfsDisk)
1011{
1012 LogFlowFunc(("pszFilename=\"%s\"\n", pszFilename));
1013 int rc = VINF_SUCCESS;
1014 PVDIIMAGEDESC pImage;
1015
1016 if ( !VALID_PTR(pszFilename)
1017 || !*pszFilename)
1018 {
1019 rc = VERR_INVALID_PARAMETER;
1020 goto out;
1021 }
1022
1023 pImage = (PVDIIMAGEDESC)RTMemAllocZ(sizeof(VDIIMAGEDESC));
1024 if (!pImage)
1025 {
1026 rc = VERR_NO_MEMORY;
1027 goto out;
1028 }
1029 pImage->pszFilename = pszFilename;
1030#ifndef VBOX_WITH_NEW_IO_CODE
1031 pImage->File = NIL_RTFILE;
1032#else
1033 pImage->pStorage = NULL;
1034#endif
1035 pImage->paBlocks = NULL;
1036 pImage->pVDIfsDisk = pVDIfsDisk;
1037 /* For the async I/O interface which is normally retrieved from the image interface list. */
1038 pImage->pVDIfsImage = pVDIfsDisk;
1039
1040 rc = vdiOpenImage(pImage, VD_OPEN_FLAGS_INFO | VD_OPEN_FLAGS_READONLY);
1041 vdiFreeImage(pImage, false);
1042 RTMemFree(pImage);
1043
1044out:
1045 LogFlowFunc(("returns %Rrc\n", rc));
1046 return rc;
1047}
1048
1049/** @copydoc VBOXHDDBACKEND::pfnOpen */
1050static int vdiOpen(const char *pszFilename, unsigned uOpenFlags,
1051 PVDINTERFACE pVDIfsDisk, PVDINTERFACE pVDIfsImage,
1052 void **ppBackendData)
1053{
1054 LogFlowFunc(("pszFilename=\"%s\" uOpenFlags=%#x pVDIfsDisk=%#p pVDIfsImage=%#p ppBackendData=%#p\n", pszFilename, uOpenFlags, pVDIfsDisk, pVDIfsImage, ppBackendData));
1055 int rc;
1056 PVDIIMAGEDESC pImage;
1057
1058 /* Check open flags. All valid flags are supported. */
1059 if (uOpenFlags & ~VD_OPEN_FLAGS_MASK)
1060 {
1061 rc = VERR_INVALID_PARAMETER;
1062 goto out;
1063 }
1064
1065 /* Check remaining arguments. */
1066 if ( !VALID_PTR(pszFilename)
1067 || !*pszFilename)
1068 {
1069 rc = VERR_INVALID_PARAMETER;
1070 goto out;
1071 }
1072
1073 pImage = (PVDIIMAGEDESC)RTMemAllocZ(sizeof(VDIIMAGEDESC));
1074 if (!pImage)
1075 {
1076 rc = VERR_NO_MEMORY;
1077 goto out;
1078 }
1079 pImage->pszFilename = pszFilename;
1080#ifndef VBOX_WITH_NEW_IO_CODE
1081 pImage->File = NIL_RTFILE;
1082#else
1083 pImage->pStorage = NULL;
1084#endif
1085 pImage->paBlocks = NULL;
1086 pImage->pVDIfsDisk = pVDIfsDisk;
1087 pImage->pVDIfsImage = pVDIfsImage;
1088
1089 rc = vdiOpenImage(pImage, uOpenFlags);
1090 if (RT_SUCCESS(rc))
1091 *ppBackendData = pImage;
1092
1093out:
1094 LogFlowFunc(("returns %Rrc (pBackendData=%#p)\n", rc, *ppBackendData));
1095 return rc;
1096}
1097
1098/** @copydoc VBOXHDDBACKEND::pfnCreate */
1099static int vdiCreate(const char *pszFilename, uint64_t cbSize,
1100 unsigned uImageFlags, const char *pszComment,
1101 PCPDMMEDIAGEOMETRY pPCHSGeometry,
1102 PCPDMMEDIAGEOMETRY pLCHSGeometry, PCRTUUID pUuid,
1103 unsigned uOpenFlags, unsigned uPercentStart,
1104 unsigned uPercentSpan, PVDINTERFACE pVDIfsDisk,
1105 PVDINTERFACE pVDIfsImage, PVDINTERFACE pVDIfsOperation,
1106 void **ppBackendData)
1107{
1108 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));
1109 int rc;
1110 PVDIIMAGEDESC pImage;
1111
1112 PFNVDPROGRESS pfnProgress = NULL;
1113 void *pvUser = NULL;
1114 PVDINTERFACE pIfProgress = VDInterfaceGet(pVDIfsOperation,
1115 VDINTERFACETYPE_PROGRESS);
1116 PVDINTERFACEPROGRESS pCbProgress = NULL;
1117 if (pIfProgress)
1118 {
1119 pCbProgress = VDGetInterfaceProgress(pIfProgress);
1120 if (pCbProgress)
1121 pfnProgress = pCbProgress->pfnProgress;
1122 pvUser = pIfProgress->pvUser;
1123 }
1124
1125 /* Check open flags. All valid flags are supported. */
1126 if (uOpenFlags & ~VD_OPEN_FLAGS_MASK)
1127 {
1128 rc = VERR_INVALID_PARAMETER;
1129 goto out;
1130 }
1131
1132 /* Check size. Maximum 2PB-3M (to be on the safe side). No tricks with
1133 * adjusting the 1M block size so far, which would extend the size. */
1134 if ( !cbSize
1135 || cbSize >= _1P * 2 - _1M * 3)
1136 {
1137 rc = VERR_VD_INVALID_SIZE;
1138 goto out;
1139 }
1140
1141 /* Check remaining arguments. */
1142 if ( !VALID_PTR(pszFilename)
1143 || !*pszFilename
1144 || cbSize < VDI_IMAGE_DEFAULT_BLOCK_SIZE
1145 || !VALID_PTR(pPCHSGeometry)
1146 || !VALID_PTR(pLCHSGeometry))
1147 {
1148 rc = VERR_INVALID_PARAMETER;
1149 goto out;
1150 }
1151
1152 pImage = (PVDIIMAGEDESC)RTMemAllocZ(sizeof(VDIIMAGEDESC));
1153 if (!pImage)
1154 {
1155 rc = VERR_NO_MEMORY;
1156 goto out;
1157 }
1158 pImage->pszFilename = pszFilename;
1159#ifndef VBOX_WITH_NEW_IO_CODE
1160 pImage->File = NIL_RTFILE;
1161#else
1162 pImage->pStorage = NULL;
1163#endif
1164 pImage->paBlocks = NULL;
1165 pImage->pVDIfsDisk = pVDIfsDisk;
1166 pImage->pVDIfsImage = pVDIfsImage;
1167
1168 rc = vdiCreateImage(pImage, cbSize, uImageFlags, pszComment,
1169 pPCHSGeometry, pLCHSGeometry, pUuid, uOpenFlags,
1170 pfnProgress, pvUser, uPercentStart, uPercentSpan);
1171 if (RT_SUCCESS(rc))
1172 {
1173 /* So far the image is opened in read/write mode. Make sure the
1174 * image is opened in read-only mode if the caller requested that. */
1175 if (uOpenFlags & VD_OPEN_FLAGS_READONLY)
1176 {
1177 vdiFreeImage(pImage, false);
1178 rc = vdiOpenImage(pImage, uOpenFlags);
1179 if (RT_FAILURE(rc))
1180 goto out;
1181 }
1182 *ppBackendData = pImage;
1183 }
1184 else
1185 RTMemFree(pImage);
1186
1187out:
1188 LogFlowFunc(("returns %Rrc (pBackendData=%#p)\n", rc, *ppBackendData));
1189 return rc;
1190}
1191
1192/** @copydoc VBOXHDDBACKEND::pfnRename */
1193static int vdiRename(void *pBackendData, const char *pszFilename)
1194{
1195 LogFlowFunc(("pBackendData=%#p pszFilename=%#p\n", pBackendData, pszFilename));
1196
1197 int rc = VINF_SUCCESS;
1198 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1199
1200 /* Check arguments. */
1201 if ( !pImage
1202 || !pszFilename
1203 || !*pszFilename)
1204 {
1205 rc = VERR_INVALID_PARAMETER;
1206 goto out;
1207 }
1208
1209 /* Close the image. */
1210 vdiFreeImage(pImage, false);
1211
1212 /* Rename the file. */
1213 rc = RTFileMove(pImage->pszFilename, pszFilename, 0);
1214 if (RT_FAILURE(rc))
1215 {
1216 /* The move failed, try to reopen the original image. */
1217 int rc2 = vdiOpenImage(pImage, pImage->uOpenFlags);
1218 if (RT_FAILURE(rc2))
1219 rc = rc2;
1220
1221 goto out;
1222 }
1223
1224 /* Update pImage with the new information. */
1225 pImage->pszFilename = pszFilename;
1226
1227 /* Open the new image. */
1228 rc = vdiOpenImage(pImage, pImage->uOpenFlags);
1229 if (RT_FAILURE(rc))
1230 goto out;
1231
1232out:
1233 LogFlowFunc(("returns %Rrc\n", rc));
1234 return rc;
1235}
1236
1237/** @copydoc VBOXHDDBACKEND::pfnClose */
1238static int vdiClose(void *pBackendData, bool fDelete)
1239{
1240 LogFlowFunc(("pBackendData=%#p fDelete=%d\n", pBackendData, fDelete));
1241 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1242 int rc = VINF_SUCCESS;
1243
1244 /* Freeing a never allocated image (e.g. because the open failed) is
1245 * not signalled as an error. After all nothing bad happens. */
1246 if (pImage)
1247 {
1248 vdiFreeImage(pImage, fDelete);
1249 RTMemFree(pImage);
1250 }
1251
1252 LogFlowFunc(("returns %Rrc\n", rc));
1253 return rc;
1254}
1255
1256/** @copydoc VBOXHDDBACKEND::pfnRead */
1257static int vdiRead(void *pBackendData, uint64_t uOffset, void *pvBuf,
1258 size_t cbToRead, size_t *pcbActuallyRead)
1259{
1260 LogFlowFunc(("pBackendData=%#p uOffset=%llu pvBuf=%#p cbToRead=%zu pcbActuallyRead=%#p\n", pBackendData, uOffset, pvBuf, cbToRead, pcbActuallyRead));
1261 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1262 unsigned uBlock;
1263 unsigned offRead;
1264 int rc;
1265
1266 AssertPtr(pImage);
1267 Assert(!(uOffset % 512));
1268 Assert(!(cbToRead % 512));
1269
1270 if ( uOffset + cbToRead > getImageDiskSize(&pImage->Header)
1271 || !VALID_PTR(pvBuf)
1272 || !cbToRead)
1273 {
1274 rc = VERR_INVALID_PARAMETER;
1275 goto out;
1276 }
1277
1278 /* Calculate starting block number and offset inside it. */
1279 uBlock = (unsigned)(uOffset >> pImage->uShiftOffset2Index);
1280 offRead = (unsigned)uOffset & pImage->uBlockMask;
1281
1282 /* Clip read range to at most the rest of the block. */
1283 cbToRead = RT_MIN(cbToRead, getImageBlockSize(&pImage->Header) - offRead);
1284 Assert(!(cbToRead % 512));
1285
1286 if (pImage->paBlocks[uBlock] == VDI_IMAGE_BLOCK_FREE)
1287 rc = VERR_VD_BLOCK_FREE;
1288 else if (pImage->paBlocks[uBlock] == VDI_IMAGE_BLOCK_ZERO)
1289 {
1290 memset(pvBuf, 0, cbToRead);
1291 rc = VINF_SUCCESS;
1292 }
1293 else
1294 {
1295 /* Block present in image file, read relevant data. */
1296 uint64_t u64Offset = (uint64_t)pImage->paBlocks[uBlock] * pImage->cbTotalBlockData
1297 + (pImage->offStartData + pImage->offStartBlockData + offRead);
1298 rc = vdiFileReadSync(pImage, u64Offset, pvBuf, cbToRead, NULL);
1299 }
1300
1301 if (pcbActuallyRead)
1302 *pcbActuallyRead = cbToRead;
1303
1304out:
1305 LogFlowFunc(("returns %Rrc\n", rc));
1306 return rc;
1307}
1308
1309/**@copydoc VBOXHDDBACKEND::pfnWrite */
1310static int vdiWrite(void *pBackendData, uint64_t uOffset, const void *pvBuf,
1311 size_t cbToWrite, size_t *pcbWriteProcess,
1312 size_t *pcbPreRead, size_t *pcbPostRead, unsigned fWrite)
1313{
1314 LogFlowFunc(("pBackendData=%#p uOffset=%llu pvBuf=%#p cbToWrite=%zu pcbWriteProcess=%#p pcbPreRead=%#p pcbPostRead=%#p\n", pBackendData, uOffset, pvBuf, cbToWrite, pcbWriteProcess, pcbPreRead, pcbPostRead));
1315 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1316 unsigned uBlock;
1317 unsigned offWrite;
1318 int rc = VINF_SUCCESS;
1319
1320 AssertPtr(pImage);
1321 Assert(!(uOffset % 512));
1322 Assert(!(cbToWrite % 512));
1323
1324 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
1325 {
1326 rc = VERR_VD_IMAGE_READ_ONLY;
1327 goto out;
1328 }
1329
1330 if (!VALID_PTR(pvBuf) || !cbToWrite)
1331 {
1332 rc = VERR_INVALID_PARAMETER;
1333 goto out;
1334 }
1335
1336 /* No size check here, will do that later. For dynamic images which are
1337 * not multiples of the block size in length, this would prevent writing to
1338 * the last grain. */
1339
1340 /* Calculate starting block number and offset inside it. */
1341 uBlock = (unsigned)(uOffset >> pImage->uShiftOffset2Index);
1342 offWrite = (unsigned)uOffset & pImage->uBlockMask;
1343
1344 /* Clip write range to at most the rest of the block. */
1345 cbToWrite = RT_MIN(cbToWrite, getImageBlockSize(&pImage->Header) - offWrite);
1346 Assert(!(cbToWrite % 512));
1347
1348 do
1349 {
1350 if (!IS_VDI_IMAGE_BLOCK_ALLOCATED(pImage->paBlocks[uBlock]))
1351 {
1352 /* Block is either free or zero. */
1353 if ( !(pImage->uOpenFlags & VD_OPEN_FLAGS_HONOR_ZEROES)
1354 && ( pImage->paBlocks[uBlock] == VDI_IMAGE_BLOCK_ZERO
1355 || cbToWrite == getImageBlockSize(&pImage->Header)))
1356 {
1357 /* If the destination block is unallocated at this point, it's
1358 * either a zero block or a block which hasn't been used so far
1359 * (which also means that it's a zero block. Don't need to write
1360 * anything to this block if the data consists of just zeroes. */
1361 Assert(!(cbToWrite % 4));
1362 Assert(cbToWrite * 8 <= UINT32_MAX);
1363 if (ASMBitFirstSet((volatile void *)pvBuf, (uint32_t)cbToWrite * 8) == -1)
1364 {
1365 pImage->paBlocks[uBlock] = VDI_IMAGE_BLOCK_ZERO;
1366 break;
1367 }
1368 }
1369
1370 if (cbToWrite == getImageBlockSize(&pImage->Header))
1371 {
1372 /* Full block write to previously unallocated block.
1373 * Allocate block and write data. */
1374 Assert(!offWrite);
1375 unsigned cBlocksAllocated = getImageBlocksAllocated(&pImage->Header);
1376 uint64_t u64Offset = (uint64_t)cBlocksAllocated * pImage->cbTotalBlockData
1377 + (pImage->offStartData + pImage->offStartBlockData);
1378 rc = vdiFileWriteSync(pImage, u64Offset, pvBuf, cbToWrite, NULL);
1379 if (RT_FAILURE(rc))
1380 goto out;
1381 pImage->paBlocks[uBlock] = cBlocksAllocated;
1382 setImageBlocksAllocated(&pImage->Header, cBlocksAllocated + 1);
1383
1384 rc = vdiUpdateBlockInfo(pImage, uBlock);
1385 if (RT_FAILURE(rc))
1386 goto out;
1387
1388 *pcbPreRead = 0;
1389 *pcbPostRead = 0;
1390 }
1391 else
1392 {
1393 /* Trying to do a partial write to an unallocated block. Don't do
1394 * anything except letting the upper layer know what to do. */
1395 *pcbPreRead = offWrite % getImageBlockSize(&pImage->Header);
1396 *pcbPostRead = getImageBlockSize(&pImage->Header) - cbToWrite - *pcbPreRead;
1397 rc = VERR_VD_BLOCK_FREE;
1398 }
1399 }
1400 else
1401 {
1402 /* Block present in image file, write relevant data. */
1403 uint64_t u64Offset = (uint64_t)pImage->paBlocks[uBlock] * pImage->cbTotalBlockData
1404 + (pImage->offStartData + pImage->offStartBlockData + offWrite);
1405 rc = vdiFileWriteSync(pImage, u64Offset, pvBuf, cbToWrite, NULL);
1406 }
1407 } while (0);
1408
1409 if (pcbWriteProcess)
1410 *pcbWriteProcess = cbToWrite;
1411
1412out:
1413 LogFlowFunc(("returns %Rrc\n", rc));
1414 return rc;
1415}
1416
1417/** @copydoc VBOXHDDBACKEND::pfnFlush */
1418static int vdiFlush(void *pBackendData)
1419{
1420 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
1421 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1422 int rc = VINF_SUCCESS;
1423
1424 Assert(pImage);
1425
1426 vdiFlushImage(pImage);
1427 LogFlowFunc(("returns %Rrc\n", rc));
1428 return rc;
1429}
1430
1431/** @copydoc VBOXHDDBACKEND::pfnGetVersion */
1432static unsigned vdiGetVersion(void *pBackendData)
1433{
1434 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
1435 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1436 unsigned uVersion;
1437
1438 AssertPtr(pImage);
1439
1440 if (pImage)
1441 uVersion = pImage->PreHeader.u32Version;
1442 else
1443 uVersion = 0;
1444
1445 LogFlowFunc(("returns %#x\n", uVersion));
1446 return uVersion;
1447}
1448
1449/** @copydoc VBOXHDDBACKEND::pfnGetSize */
1450static uint64_t vdiGetSize(void *pBackendData)
1451{
1452 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
1453 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1454 uint64_t cbSize;
1455
1456 AssertPtr(pImage);
1457
1458 if (pImage)
1459 cbSize = getImageDiskSize(&pImage->Header);
1460 else
1461 cbSize = 0;
1462
1463 LogFlowFunc(("returns %llu\n", cbSize));
1464 return cbSize;
1465}
1466
1467/** @copydoc VBOXHDDBACKEND::pfnGetFileSize */
1468static uint64_t vdiGetFileSize(void *pBackendData)
1469{
1470 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
1471 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1472 uint64_t cb = 0;
1473
1474 AssertPtr(pImage);
1475
1476 if (pImage)
1477 {
1478 uint64_t cbFile;
1479 if (vdiFileOpened(pImage))
1480 {
1481 int rc = vdiFileGetSize(pImage, &cbFile);
1482 if (RT_SUCCESS(rc))
1483 cb += cbFile;
1484 }
1485 }
1486
1487 LogFlowFunc(("returns %lld\n", cb));
1488 return cb;
1489}
1490
1491/** @copydoc VBOXHDDBACKEND::pfnGetPCHSGeometry */
1492static int vdiGetPCHSGeometry(void *pBackendData,
1493 PPDMMEDIAGEOMETRY pPCHSGeometry)
1494{
1495 LogFlowFunc(("pBackendData=%#p pPCHSGeometry=%#p\n", pBackendData, pPCHSGeometry));
1496 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1497 int rc;
1498
1499 AssertPtr(pImage);
1500
1501 if (pImage)
1502 {
1503 if (pImage->PCHSGeometry.cCylinders)
1504 {
1505 *pPCHSGeometry = pImage->PCHSGeometry;
1506 rc = VINF_SUCCESS;
1507 }
1508 else
1509 rc = VERR_VD_GEOMETRY_NOT_SET;
1510 }
1511 else
1512 rc = VERR_VD_NOT_OPENED;
1513
1514 LogFlowFunc(("returns %Rrc (PCHS=%u/%u/%u)\n", rc, pPCHSGeometry->cCylinders, pPCHSGeometry->cHeads, pPCHSGeometry->cSectors));
1515 return rc;
1516}
1517
1518/** @copydoc VBOXHDDBACKEND::pfnSetPCHSGeometry */
1519static int vdiSetPCHSGeometry(void *pBackendData,
1520 PCPDMMEDIAGEOMETRY pPCHSGeometry)
1521{
1522 LogFlowFunc(("pBackendData=%#p pPCHSGeometry=%#p PCHS=%u/%u/%u\n", pBackendData, pPCHSGeometry, pPCHSGeometry->cCylinders, pPCHSGeometry->cHeads, pPCHSGeometry->cSectors));
1523 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1524 int rc;
1525
1526 AssertPtr(pImage);
1527
1528 if (pImage)
1529 {
1530 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
1531 {
1532 rc = VERR_VD_IMAGE_READ_ONLY;
1533 goto out;
1534 }
1535
1536 pImage->PCHSGeometry = *pPCHSGeometry;
1537 rc = VINF_SUCCESS;
1538 }
1539 else
1540 rc = VERR_VD_NOT_OPENED;
1541
1542out:
1543 LogFlowFunc(("returns %Rrc\n", rc));
1544 return rc;
1545}
1546
1547/** @copydoc VBOXHDDBACKEND::pfnGetLCHSGeometry */
1548static int vdiGetLCHSGeometry(void *pBackendData,
1549 PPDMMEDIAGEOMETRY pLCHSGeometry)
1550{
1551 LogFlowFunc(("pBackendData=%#p pLCHSGeometry=%#p\n", pBackendData, pLCHSGeometry));
1552 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1553 int rc;
1554
1555 AssertPtr(pImage);
1556
1557 if (pImage)
1558 {
1559 VDIDISKGEOMETRY DummyGeo = { 0, 0, 0, VDI_GEOMETRY_SECTOR_SIZE };
1560 PVDIDISKGEOMETRY pGeometry = getImageLCHSGeometry(&pImage->Header);
1561 if (!pGeometry)
1562 pGeometry = &DummyGeo;
1563
1564 if ( pGeometry->cCylinders > 0
1565 && pGeometry->cHeads > 0
1566 && pGeometry->cSectors > 0)
1567 {
1568 pLCHSGeometry->cCylinders = pGeometry->cCylinders;
1569 pLCHSGeometry->cHeads = pGeometry->cHeads;
1570 pLCHSGeometry->cSectors = pGeometry->cSectors;
1571 rc = VINF_SUCCESS;
1572 }
1573 else
1574 rc = VERR_VD_GEOMETRY_NOT_SET;
1575 }
1576 else
1577 rc = VERR_VD_NOT_OPENED;
1578
1579 LogFlowFunc(("returns %Rrc (LCHS=%u/%u/%u)\n", rc, pLCHSGeometry->cCylinders, pLCHSGeometry->cHeads, pLCHSGeometry->cSectors));
1580 return rc;
1581}
1582
1583/** @copydoc VBOXHDDBACKEND::pfnSetLCHSGeometry */
1584static int vdiSetLCHSGeometry(void *pBackendData,
1585 PCPDMMEDIAGEOMETRY pLCHSGeometry)
1586{
1587 LogFlowFunc(("pBackendData=%#p pLCHSGeometry=%#p LCHS=%u/%u/%u\n", pBackendData, pLCHSGeometry, pLCHSGeometry->cCylinders, pLCHSGeometry->cHeads, pLCHSGeometry->cSectors));
1588 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1589 PVDIDISKGEOMETRY pGeometry;
1590 int rc;
1591
1592 AssertPtr(pImage);
1593
1594 if (pImage)
1595 {
1596 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
1597 {
1598 rc = VERR_VD_IMAGE_READ_ONLY;
1599 goto out;
1600 }
1601
1602 pGeometry = getImageLCHSGeometry(&pImage->Header);
1603 if (pGeometry)
1604 {
1605 pGeometry->cCylinders = pLCHSGeometry->cCylinders;
1606 pGeometry->cHeads = pLCHSGeometry->cHeads;
1607 pGeometry->cSectors = pLCHSGeometry->cSectors;
1608 pGeometry->cbSector = VDI_GEOMETRY_SECTOR_SIZE;
1609
1610 /* Update header information in base image file. */
1611 vdiFlushImage(pImage);
1612 }
1613 rc = VINF_SUCCESS;
1614 }
1615 else
1616 rc = VERR_VD_NOT_OPENED;
1617
1618out:
1619 LogFlowFunc(("returns %Rrc\n", rc));
1620 return rc;
1621}
1622
1623/** @copydoc VBOXHDDBACKEND::pfnGetImageFlags */
1624static unsigned vdiGetImageFlags(void *pBackendData)
1625{
1626 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
1627 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1628 unsigned uImageFlags;
1629
1630 AssertPtr(pImage);
1631
1632 if (pImage)
1633 uImageFlags = pImage->uImageFlags;
1634 else
1635 uImageFlags = 0;
1636
1637 LogFlowFunc(("returns %#x\n", uImageFlags));
1638 return uImageFlags;
1639}
1640
1641/** @copydoc VBOXHDDBACKEND::pfnGetOpenFlags */
1642static unsigned vdiGetOpenFlags(void *pBackendData)
1643{
1644 LogFlowFunc(("pBackendData=%#p\n", pBackendData));
1645 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1646 unsigned uOpenFlags;
1647
1648 AssertPtr(pImage);
1649
1650 if (pImage)
1651 uOpenFlags = pImage->uOpenFlags;
1652 else
1653 uOpenFlags = 0;
1654
1655 LogFlowFunc(("returns %#x\n", uOpenFlags));
1656 return uOpenFlags;
1657}
1658
1659/** @copydoc VBOXHDDBACKEND::pfnSetOpenFlags */
1660static int vdiSetOpenFlags(void *pBackendData, unsigned uOpenFlags)
1661{
1662 LogFlowFunc(("pBackendData=%#p uOpenFlags=%#x\n", pBackendData, uOpenFlags));
1663 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1664 int rc;
1665 const char *pszFilename;
1666
1667 /* Image must be opened and the new flags must be valid. Just readonly and
1668 * info flags are supported. */
1669 if (!pImage || (uOpenFlags & ~(VD_OPEN_FLAGS_READONLY | VD_OPEN_FLAGS_INFO | VD_OPEN_FLAGS_ASYNC_IO)))
1670 {
1671 rc = VERR_INVALID_PARAMETER;
1672 goto out;
1673 }
1674
1675 /* Implement this operation via reopening the image. */
1676 pszFilename = pImage->pszFilename;
1677 vdiFreeImage(pImage, false);
1678 rc = vdiOpenImage(pImage, uOpenFlags);
1679
1680out:
1681 LogFlowFunc(("returns %Rrc\n", rc));
1682 return rc;
1683}
1684
1685/** @copydoc VBOXHDDBACKEND::pfnGetComment */
1686static int vdiGetComment(void *pBackendData, char *pszComment,
1687 size_t cbComment)
1688{
1689 LogFlowFunc(("pBackendData=%#p pszComment=%#p cbComment=%zu\n", pBackendData, pszComment, cbComment));
1690 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1691 int rc = VINF_SUCCESS;
1692
1693 AssertPtr(pImage);
1694
1695 if (pImage)
1696 {
1697 char *pszTmp = getImageComment(&pImage->Header);
1698 size_t cb = strlen(pszTmp);
1699 if (cb < cbComment)
1700 {
1701 /* memcpy is much better than strncpy. */
1702 memcpy(pszComment, pszTmp, cb + 1);
1703 }
1704 else
1705 rc = VERR_BUFFER_OVERFLOW;
1706 }
1707 else
1708 rc = VERR_VD_NOT_OPENED;
1709
1710 LogFlowFunc(("returns %Rrc comment=\"%s\"\n", rc, pszComment));
1711 return rc;
1712}
1713
1714/** @copydoc VBOXHDDBACKEND::pfnGetComment */
1715static int vdiSetComment(void *pBackendData, const char *pszComment)
1716{
1717 LogFlowFunc(("pBackendData=%#p pszComment=\"%s\"\n", pBackendData, pszComment));
1718 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1719 int rc;
1720
1721 AssertPtr(pImage);
1722
1723 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
1724 {
1725 rc = VERR_VD_IMAGE_READ_ONLY;
1726 goto out;
1727 }
1728
1729 if (pImage)
1730 {
1731 size_t cchComment = pszComment ? strlen(pszComment) : 0;
1732 if (cchComment >= VDI_IMAGE_COMMENT_SIZE)
1733 {
1734 LogFunc(("pszComment is too long, %d bytes!\n", cchComment));
1735 rc = VERR_VD_VDI_COMMENT_TOO_LONG;
1736 goto out;
1737 }
1738
1739 /* we don't support old style images */
1740 if (GET_MAJOR_HEADER_VERSION(&pImage->Header) == 1)
1741 {
1742 /*
1743 * Update the comment field, making sure to zero out all of the previous comment.
1744 */
1745 memset(pImage->Header.u.v1.szComment, '\0', VDI_IMAGE_COMMENT_SIZE);
1746 memcpy(pImage->Header.u.v1.szComment, pszComment, cchComment);
1747
1748 /* write out new the header */
1749 rc = vdiUpdateHeader(pImage);
1750 }
1751 else
1752 rc = VERR_VD_VDI_UNSUPPORTED_VERSION;
1753 }
1754 else
1755 rc = VERR_VD_NOT_OPENED;
1756
1757out:
1758 LogFlowFunc(("returns %Rrc\n", rc));
1759 return rc;
1760}
1761
1762/** @copydoc VBOXHDDBACKEND::pfnGetUuid */
1763static int vdiGetUuid(void *pBackendData, PRTUUID pUuid)
1764{
1765 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
1766 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1767 int rc;
1768
1769 AssertPtr(pImage);
1770
1771 if (pImage)
1772 {
1773 *pUuid = *getImageCreationUUID(&pImage->Header);
1774 rc = VINF_SUCCESS;
1775 }
1776 else
1777 rc = VERR_VD_NOT_OPENED;
1778
1779 LogFlowFunc(("returns %Rrc (%RTuuid)\n", rc, pUuid));
1780 return rc;
1781}
1782
1783/** @copydoc VBOXHDDBACKEND::pfnSetUuid */
1784static int vdiSetUuid(void *pBackendData, PCRTUUID pUuid)
1785{
1786 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
1787 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1788 int rc = VINF_SUCCESS;
1789
1790 AssertPtr(pImage);
1791
1792 if (pImage)
1793 {
1794 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
1795 {
1796 if (GET_MAJOR_HEADER_VERSION(&pImage->Header) == 1)
1797 pImage->Header.u.v1.uuidCreate = *pUuid;
1798 /* Make it possible to clone old VDIs. */
1799 else if (GET_MAJOR_HEADER_VERSION(&pImage->Header) == 0)
1800 pImage->Header.u.v0.uuidCreate = *pUuid;
1801 else
1802 {
1803 LogFunc(("Version is not supported!\n"));
1804 rc = VERR_VD_VDI_UNSUPPORTED_VERSION;
1805 }
1806 }
1807 else
1808 rc = VERR_VD_IMAGE_READ_ONLY;
1809 }
1810 else
1811 rc = VERR_VD_NOT_OPENED;
1812
1813 LogFlowFunc(("returns %Rrc\n", rc));
1814 return rc;
1815}
1816
1817/** @copydoc VBOXHDDBACKEND::pfnGetModificationUuid */
1818static int vdiGetModificationUuid(void *pBackendData, PRTUUID pUuid)
1819{
1820 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
1821 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1822 int rc;
1823
1824 AssertPtr(pImage);
1825
1826 if (pImage)
1827 {
1828 *pUuid = *getImageModificationUUID(&pImage->Header);
1829 rc = VINF_SUCCESS;
1830 }
1831 else
1832 rc = VERR_VD_NOT_OPENED;
1833
1834 LogFlowFunc(("returns %Rrc (%RTuuid)\n", rc, pUuid));
1835 return rc;
1836}
1837
1838/** @copydoc VBOXHDDBACKEND::pfnSetModificationUuid */
1839static int vdiSetModificationUuid(void *pBackendData, PCRTUUID pUuid)
1840{
1841 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
1842 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1843 int rc = VINF_SUCCESS;
1844
1845 AssertPtr(pImage);
1846
1847 if (pImage)
1848 {
1849 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
1850 {
1851 if (GET_MAJOR_HEADER_VERSION(&pImage->Header) == 1)
1852 pImage->Header.u.v1.uuidModify = *pUuid;
1853 /* Make it possible to clone old VDIs. */
1854 else if (GET_MAJOR_HEADER_VERSION(&pImage->Header) == 0)
1855 pImage->Header.u.v0.uuidModify = *pUuid;
1856 else
1857 {
1858 LogFunc(("Version is not supported!\n"));
1859 rc = VERR_VD_VDI_UNSUPPORTED_VERSION;
1860 }
1861 }
1862 else
1863 rc = VERR_VD_IMAGE_READ_ONLY;
1864 }
1865 else
1866 rc = VERR_VD_NOT_OPENED;
1867
1868 LogFlowFunc(("returns %Rrc\n", rc));
1869 return rc;
1870}
1871
1872/** @copydoc VBOXHDDBACKEND::pfnGetParentUuid */
1873static int vdiGetParentUuid(void *pBackendData, PRTUUID pUuid)
1874{
1875 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
1876 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1877 int rc;
1878
1879 AssertPtr(pImage);
1880
1881 if (pImage)
1882 {
1883 *pUuid = *getImageParentUUID(&pImage->Header);
1884 rc = VINF_SUCCESS;
1885 }
1886 else
1887 rc = VERR_VD_NOT_OPENED;
1888
1889 LogFlowFunc(("returns %Rrc (%RTuuid)\n", rc, pUuid));
1890 return rc;
1891}
1892
1893/** @copydoc VBOXHDDBACKEND::pfnSetParentUuid */
1894static int vdiSetParentUuid(void *pBackendData, PCRTUUID pUuid)
1895{
1896 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
1897 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1898 int rc = VINF_SUCCESS;
1899
1900 AssertPtr(pImage);
1901
1902 if (pImage)
1903 {
1904 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
1905 {
1906 if (GET_MAJOR_HEADER_VERSION(&pImage->Header) == 1)
1907 pImage->Header.u.v1.uuidLinkage = *pUuid;
1908 /* Make it possible to clone old VDIs. */
1909 else if (GET_MAJOR_HEADER_VERSION(&pImage->Header) == 0)
1910 pImage->Header.u.v0.uuidLinkage = *pUuid;
1911 else
1912 {
1913 LogFunc(("Version is not supported!\n"));
1914 rc = VERR_VD_VDI_UNSUPPORTED_VERSION;
1915 }
1916 }
1917 else
1918 rc = VERR_VD_IMAGE_READ_ONLY;
1919 }
1920 else
1921 rc = VERR_VD_NOT_OPENED;
1922
1923 LogFlowFunc(("returns %Rrc\n", rc));
1924 return rc;
1925}
1926
1927/** @copydoc VBOXHDDBACKEND::pfnGetParentModificationUuid */
1928static int vdiGetParentModificationUuid(void *pBackendData, PRTUUID pUuid)
1929{
1930 LogFlowFunc(("pBackendData=%#p pUuid=%#p\n", pBackendData, pUuid));
1931 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1932 int rc;
1933
1934 AssertPtr(pImage);
1935
1936 if (pImage)
1937 {
1938 *pUuid = *getImageParentModificationUUID(&pImage->Header);
1939 rc = VINF_SUCCESS;
1940 }
1941 else
1942 rc = VERR_VD_NOT_OPENED;
1943
1944 LogFlowFunc(("returns %Rrc (%RTuuid)\n", rc, pUuid));
1945 return rc;
1946}
1947
1948/** @copydoc VBOXHDDBACKEND::pfnSetParentModificationUuid */
1949static int vdiSetParentModificationUuid(void *pBackendData, PCRTUUID pUuid)
1950{
1951 LogFlowFunc(("pBackendData=%#p Uuid=%RTuuid\n", pBackendData, pUuid));
1952 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1953 int rc = VINF_SUCCESS;
1954
1955 AssertPtr(pImage);
1956
1957 if (pImage)
1958 {
1959 if (!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY))
1960 {
1961 if (GET_MAJOR_HEADER_VERSION(&pImage->Header) == 1)
1962 pImage->Header.u.v1.uuidParentModify = *pUuid;
1963 else
1964 {
1965 LogFunc(("Version is not supported!\n"));
1966 rc = VERR_VD_VDI_UNSUPPORTED_VERSION;
1967 }
1968 }
1969 else
1970 rc = VERR_VD_IMAGE_READ_ONLY;
1971 }
1972 else
1973 rc = VERR_VD_NOT_OPENED;
1974
1975 LogFlowFunc(("returns %Rrc\n", rc));
1976 return rc;
1977}
1978
1979/** @copydoc VBOXHDDBACKEND::pfnDump */
1980static void vdiDump(void *pBackendData)
1981{
1982 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
1983
1984#ifndef VBOX_WITH_NEW_IO_CODE
1985 pImage->pInterfaceErrorCallbacks->pfnMessage(pImage->pInterfaceError->pvUser, "Dumping VDI image \"%s\" mode=%s uOpenFlags=%X File=%08X\n",
1986 pImage->pszFilename,
1987 (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY) ? "r/o" : "r/w",
1988 pImage->uOpenFlags,
1989 pImage->File);
1990#else
1991 pImage->pInterfaceErrorCallbacks->pfnMessage(pImage->pInterfaceError->pvUser, "Dumping VDI image \"%s\" mode=%s uOpenFlags=%X File=%#p\n",
1992 pImage->pszFilename,
1993 (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY) ? "r/o" : "r/w",
1994 pImage->uOpenFlags,
1995 pImage->pStorage);
1996#endif
1997 pImage->pInterfaceErrorCallbacks->pfnMessage(pImage->pInterfaceError->pvUser, "Header: Version=%08X Type=%X Flags=%X Size=%llu\n",
1998 pImage->PreHeader.u32Version,
1999 getImageType(&pImage->Header),
2000 getImageFlags(&pImage->Header),
2001 getImageDiskSize(&pImage->Header));
2002 pImage->pInterfaceErrorCallbacks->pfnMessage(pImage->pInterfaceError->pvUser, "Header: cbBlock=%u cbBlockExtra=%u cBlocks=%u cBlocksAllocated=%u\n",
2003 getImageBlockSize(&pImage->Header),
2004 getImageExtraBlockSize(&pImage->Header),
2005 getImageBlocks(&pImage->Header),
2006 getImageBlocksAllocated(&pImage->Header));
2007 pImage->pInterfaceErrorCallbacks->pfnMessage(pImage->pInterfaceError->pvUser, "Header: offBlocks=%u offData=%u\n",
2008 getImageBlocksOffset(&pImage->Header),
2009 getImageDataOffset(&pImage->Header));
2010 PVDIDISKGEOMETRY pg = getImageLCHSGeometry(&pImage->Header);
2011 if (pg)
2012 pImage->pInterfaceErrorCallbacks->pfnMessage(pImage->pInterfaceError->pvUser, "Header: Geometry: C/H/S=%u/%u/%u cbSector=%u\n",
2013 pg->cCylinders, pg->cHeads, pg->cSectors, pg->cbSector);
2014 pImage->pInterfaceErrorCallbacks->pfnMessage(pImage->pInterfaceError->pvUser, "Header: uuidCreation={%RTuuid}\n", getImageCreationUUID(&pImage->Header));
2015 pImage->pInterfaceErrorCallbacks->pfnMessage(pImage->pInterfaceError->pvUser, "Header: uuidModification={%RTuuid}\n", getImageModificationUUID(&pImage->Header));
2016 pImage->pInterfaceErrorCallbacks->pfnMessage(pImage->pInterfaceError->pvUser, "Header: uuidParent={%RTuuid}\n", getImageParentUUID(&pImage->Header));
2017 if (GET_MAJOR_HEADER_VERSION(&pImage->Header) >= 1)
2018 pImage->pInterfaceErrorCallbacks->pfnMessage(pImage->pInterfaceError->pvUser, "Header: uuidParentModification={%RTuuid}\n", getImageParentModificationUUID(&pImage->Header));
2019 pImage->pInterfaceErrorCallbacks->pfnMessage(pImage->pInterfaceError->pvUser, "Image: fFlags=%08X offStartBlocks=%u offStartData=%u\n",
2020 pImage->uImageFlags, pImage->offStartBlocks, pImage->offStartData);
2021 pImage->pInterfaceErrorCallbacks->pfnMessage(pImage->pInterfaceError->pvUser, "Image: uBlockMask=%08X cbTotalBlockData=%u uShiftOffset2Index=%u offStartBlockData=%u\n",
2022 pImage->uBlockMask,
2023 pImage->cbTotalBlockData,
2024 pImage->uShiftOffset2Index,
2025 pImage->offStartBlockData);
2026
2027 unsigned uBlock, cBlocksNotFree, cBadBlocks, cBlocks = getImageBlocks(&pImage->Header);
2028 for (uBlock=0, cBlocksNotFree=0, cBadBlocks=0; uBlock<cBlocks; uBlock++)
2029 {
2030 if (IS_VDI_IMAGE_BLOCK_ALLOCATED(pImage->paBlocks[uBlock]))
2031 {
2032 cBlocksNotFree++;
2033 if (pImage->paBlocks[uBlock] >= cBlocks)
2034 cBadBlocks++;
2035 }
2036 }
2037 if (cBlocksNotFree != getImageBlocksAllocated(&pImage->Header))
2038 {
2039 pImage->pInterfaceErrorCallbacks->pfnMessage(pImage->pInterfaceError->pvUser, "!! WARNING: %u blocks actually allocated (cBlocksAllocated=%u) !!\n",
2040 cBlocksNotFree, getImageBlocksAllocated(&pImage->Header));
2041 }
2042 if (cBadBlocks)
2043 {
2044 pImage->pInterfaceErrorCallbacks->pfnMessage(pImage->pInterfaceError->pvUser, "!! WARNING: %u bad blocks found !!\n",
2045 cBadBlocks);
2046 }
2047}
2048
2049static int vdiGetTimeStamp(void *pBackendData, PRTTIMESPEC pTimeStamp)
2050{
2051 int rc = VERR_NOT_IMPLEMENTED;
2052 LogFlow(("%s: returned %Rrc\n", __FUNCTION__, rc));
2053 return rc;
2054}
2055
2056static int vdiGetParentTimeStamp(void *pBackendData, PRTTIMESPEC pTimeStamp)
2057{
2058 int rc = VERR_NOT_IMPLEMENTED;
2059 LogFlow(("%s: returned %Rrc\n", __FUNCTION__, rc));
2060 return rc;
2061}
2062
2063static int vdiSetParentTimeStamp(void *pBackendData, PCRTTIMESPEC pTimeStamp)
2064{
2065 int rc = VERR_NOT_IMPLEMENTED;
2066 LogFlow(("%s: returned %Rrc\n", __FUNCTION__, rc));
2067 return rc;
2068}
2069
2070static int vdiGetParentFilename(void *pBackendData, char **ppszParentFilename)
2071{
2072 int rc = VERR_NOT_IMPLEMENTED;
2073 LogFlow(("%s: returned %Rrc\n", __FUNCTION__, rc));
2074 return rc;
2075}
2076
2077static int vdiSetParentFilename(void *pBackendData, const char *pszParentFilename)
2078{
2079 int rc = VERR_NOT_IMPLEMENTED;
2080 LogFlow(("%s: returned %Rrc\n", __FUNCTION__, rc));
2081 return rc;
2082}
2083
2084static bool vdiIsAsyncIOSupported(void *pBackendData)
2085{
2086 return true;
2087}
2088
2089static int vdiAsyncRead(void *pvBackendData, uint64_t uOffset, size_t cbToRead,
2090 PVDIOCTX pIoCtx, size_t *pcbActuallyRead)
2091{
2092 LogFlowFunc(("pvBackendData=%#p uOffset=%llu pIoCtx=%#p cbToRead=%zu pcbActuallyRead=%#p\n",
2093 pvBackendData, uOffset, pIoCtx, cbToRead, pcbActuallyRead));
2094 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pvBackendData;
2095 unsigned uBlock;
2096 unsigned offRead;
2097 int rc;
2098
2099 AssertPtr(pImage);
2100 Assert(!(uOffset % 512));
2101 Assert(!(cbToRead % 512));
2102
2103 if ( uOffset + cbToRead > getImageDiskSize(&pImage->Header)
2104 || !VALID_PTR(pIoCtx)
2105 || !cbToRead)
2106 {
2107 rc = VERR_INVALID_PARAMETER;
2108 goto out;
2109 }
2110
2111 /* Calculate starting block number and offset inside it. */
2112 uBlock = (unsigned)(uOffset >> pImage->uShiftOffset2Index);
2113 offRead = (unsigned)uOffset & pImage->uBlockMask;
2114
2115 /* Clip read range to at most the rest of the block. */
2116 cbToRead = RT_MIN(cbToRead, getImageBlockSize(&pImage->Header) - offRead);
2117 Assert(!(cbToRead % 512));
2118
2119 if (pImage->paBlocks[uBlock] == VDI_IMAGE_BLOCK_FREE)
2120 rc = VERR_VD_BLOCK_FREE;
2121 else if (pImage->paBlocks[uBlock] == VDI_IMAGE_BLOCK_ZERO)
2122 {
2123 size_t cbSet;
2124
2125 cbSet = pImage->pInterfaceIOCallbacks->pfnIoCtxSet(pImage->pInterfaceIO->pvUser,
2126 pIoCtx, 0, cbToRead);
2127 Assert(cbSet == cbToRead);
2128
2129 rc = VINF_SUCCESS;
2130 }
2131 else
2132 {
2133 /* Block present in image file, read relevant data. */
2134 uint64_t u64Offset = (uint64_t)pImage->paBlocks[uBlock] * pImage->cbTotalBlockData
2135 + (pImage->offStartData + pImage->offStartBlockData + offRead);
2136 rc = pImage->pInterfaceIOCallbacks->pfnReadUserAsync(pImage->pInterfaceIO->pvUser,
2137 pImage->pStorage,
2138 u64Offset,
2139 pIoCtx, cbToRead);
2140 }
2141
2142 if (pcbActuallyRead)
2143 *pcbActuallyRead = cbToRead;
2144
2145out:
2146 LogFlowFunc(("returns %Rrc\n", rc));
2147 return rc;
2148}
2149
2150static int vdiAsyncWrite(void *pvBackendData, uint64_t uOffset, size_t cbToWrite,
2151 PVDIOCTX pIoCtx,
2152 size_t *pcbWriteProcess, size_t *pcbPreRead,
2153 size_t *pcbPostRead, unsigned fWrite)
2154{
2155 LogFlowFunc(("pvBackendData=%#p uOffset=%llu pIoCtx=%#p cbToWrite=%zu pcbWriteProcess=%#p pcbPreRead=%#p pcbPostRead=%#p\n",
2156 pvBackendData, uOffset, pIoCtx, cbToWrite, pcbWriteProcess, pcbPreRead, pcbPostRead));
2157 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pvBackendData;
2158 unsigned uBlock;
2159 unsigned offWrite;
2160 int rc = VINF_SUCCESS;
2161
2162 AssertPtr(pImage);
2163 Assert(!(uOffset % 512));
2164 Assert(!(cbToWrite % 512));
2165
2166 if (pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY)
2167 {
2168 rc = VERR_VD_IMAGE_READ_ONLY;
2169 goto out;
2170 }
2171
2172 if (!VALID_PTR(pIoCtx) || !cbToWrite)
2173 {
2174 rc = VERR_INVALID_PARAMETER;
2175 goto out;
2176 }
2177
2178 /* No size check here, will do that later. For dynamic images which are
2179 * not multiples of the block size in length, this would prevent writing to
2180 * the last grain. */
2181
2182 /* Calculate starting block number and offset inside it. */
2183 uBlock = (unsigned)(uOffset >> pImage->uShiftOffset2Index);
2184 offWrite = (unsigned)uOffset & pImage->uBlockMask;
2185
2186 /* Clip write range to at most the rest of the block. */
2187 cbToWrite = RT_MIN(cbToWrite, getImageBlockSize(&pImage->Header) - offWrite);
2188 Assert(!(cbToWrite % 512));
2189
2190 do
2191 {
2192 if (!IS_VDI_IMAGE_BLOCK_ALLOCATED(pImage->paBlocks[uBlock]))
2193 {
2194 /* Block is either free or zero. */
2195 if ( !(pImage->uOpenFlags & VD_OPEN_FLAGS_HONOR_ZEROES)
2196 && ( pImage->paBlocks[uBlock] == VDI_IMAGE_BLOCK_ZERO
2197 || cbToWrite == getImageBlockSize(&pImage->Header)))
2198 {
2199#if 0 /** @todo Provide interface to check an I/O context for a specific value */
2200 /* If the destination block is unallocated at this point, it's
2201 * either a zero block or a block which hasn't been used so far
2202 * (which also means that it's a zero block. Don't need to write
2203 * anything to this block if the data consists of just zeroes. */
2204 Assert(!(cbToWrite % 4));
2205 Assert(cbToWrite * 8 <= UINT32_MAX);
2206 if (ASMBitFirstSet((volatile void *)pvBuf, (uint32_t)cbToWrite * 8) == -1)
2207 {
2208 pImage->paBlocks[uBlock] = VDI_IMAGE_BLOCK_ZERO;
2209 break;
2210 }
2211#endif
2212 }
2213
2214 if (cbToWrite == getImageBlockSize(&pImage->Header))
2215 {
2216 /* Full block write to previously unallocated block.
2217 * Allocate block and write data. */
2218 Assert(!offWrite);
2219 unsigned cBlocksAllocated = getImageBlocksAllocated(&pImage->Header);
2220 uint64_t u64Offset = (uint64_t)cBlocksAllocated * pImage->cbTotalBlockData
2221 + (pImage->offStartData + pImage->offStartBlockData);
2222 rc = pImage->pInterfaceIOCallbacks->pfnWriteUserAsync(pImage->pInterfaceIO->pvUser,
2223 pImage->pStorage,
2224 u64Offset,
2225 pIoCtx, cbToWrite,
2226 NULL, NULL);
2227 if (RT_UNLIKELY(RT_FAILURE_NP(rc) && (rc != VERR_VD_ASYNC_IO_IN_PROGRESS)))
2228 goto out;
2229 pImage->paBlocks[uBlock] = cBlocksAllocated;
2230 setImageBlocksAllocated(&pImage->Header, cBlocksAllocated + 1);
2231
2232 rc = vdiUpdateBlockInfoAsync(pImage, uBlock, pIoCtx);
2233 if (RT_FAILURE(rc) && (rc != VERR_VD_ASYNC_IO_IN_PROGRESS))
2234 goto out;
2235
2236 *pcbPreRead = 0;
2237 *pcbPostRead = 0;
2238 }
2239 else
2240 {
2241 /* Trying to do a partial write to an unallocated block. Don't do
2242 * anything except letting the upper layer know what to do. */
2243 *pcbPreRead = offWrite % getImageBlockSize(&pImage->Header);
2244 *pcbPostRead = getImageBlockSize(&pImage->Header) - cbToWrite - *pcbPreRead;
2245 rc = VERR_VD_BLOCK_FREE;
2246 }
2247 }
2248 else
2249 {
2250 /* Block present in image file, write relevant data. */
2251 uint64_t u64Offset = (uint64_t)pImage->paBlocks[uBlock] * pImage->cbTotalBlockData
2252 + (pImage->offStartData + pImage->offStartBlockData + offWrite);
2253 rc = pImage->pInterfaceIOCallbacks->pfnWriteUserAsync(pImage->pInterfaceIO->pvUser,
2254 pImage->pStorage,
2255 u64Offset,
2256 pIoCtx, cbToWrite,
2257 NULL, NULL);
2258 }
2259 } while (0);
2260
2261 if (pcbWriteProcess)
2262 *pcbWriteProcess = cbToWrite;
2263
2264out:
2265 LogFlowFunc(("returns %Rrc\n", rc));
2266 return rc;
2267}
2268
2269static int vdiAsyncFlush(void *pvBackendData, PVDIOCTX pIoCtx)
2270{
2271 LogFlowFunc(("pBackendData=%#p\n", pvBackendData));
2272 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pvBackendData;
2273 int rc = VINF_SUCCESS;
2274
2275 Assert(pImage);
2276
2277 rc = vdiFlushImageAsync(pImage, pIoCtx);
2278 LogFlowFunc(("returns %Rrc\n", rc));
2279 return rc;
2280}
2281
2282/** @copydoc VBOXHDDBACKEND::pfnCompact */
2283static int vdiCompact(void *pBackendData, unsigned uPercentStart,
2284 unsigned uPercentSpan, PVDINTERFACE pVDIfsDisk,
2285 PVDINTERFACE pVDIfsImage, PVDINTERFACE pVDIfsOperation)
2286{
2287 PVDIIMAGEDESC pImage = (PVDIIMAGEDESC)pBackendData;
2288 int rc = VINF_SUCCESS;
2289 void *pvBuf = NULL, *pvTmp = NULL;
2290 unsigned *paBlocks2 = NULL;
2291
2292 int (*pfnParentRead)(void *, uint64_t, void *, size_t) = NULL;
2293 void *pvParent = NULL;
2294 PVDINTERFACE pIfParentState = VDInterfaceGet(pVDIfsOperation,
2295 VDINTERFACETYPE_PARENTSTATE);
2296 PVDINTERFACEPARENTSTATE pCbParentState = NULL;
2297 if (pIfParentState)
2298 {
2299 pCbParentState = VDGetInterfaceParentState(pIfParentState);
2300 if (pCbParentState)
2301 pfnParentRead = pCbParentState->pfnParentRead;
2302 pvParent = pIfParentState->pvUser;
2303 }
2304
2305 PFNVDPROGRESS pfnProgress = NULL;
2306 void *pvUser = NULL;
2307 PVDINTERFACE pIfProgress = VDInterfaceGet(pVDIfsOperation,
2308 VDINTERFACETYPE_PROGRESS);
2309 PVDINTERFACEPROGRESS pCbProgress = NULL;
2310 if (pIfProgress)
2311 {
2312 pCbProgress = VDGetInterfaceProgress(pIfProgress);
2313 if (pCbProgress)
2314 pfnProgress = pCbProgress->pfnProgress;
2315 pvUser = pIfProgress->pvUser;
2316 }
2317
2318 do {
2319 AssertBreakStmt(pImage, rc = VERR_INVALID_PARAMETER);
2320
2321 AssertBreakStmt(!(pImage->uOpenFlags & VD_OPEN_FLAGS_READONLY),
2322 rc = VERR_VD_IMAGE_READ_ONLY);
2323
2324 unsigned cBlocks;
2325 unsigned cBlocksToMove = 0;
2326 size_t cbBlock;
2327 cBlocks = getImageBlocks(&pImage->Header);
2328 cbBlock = getImageBlockSize(&pImage->Header);
2329 if (pfnParentRead)
2330 {
2331 pvBuf = RTMemTmpAlloc(cbBlock);
2332 AssertBreakStmt(VALID_PTR(pvBuf), rc = VERR_NO_MEMORY);
2333 }
2334 pvTmp = RTMemTmpAlloc(cbBlock);
2335 AssertBreakStmt(VALID_PTR(pvTmp), rc = VERR_NO_MEMORY);
2336
2337 uint64_t cbFile;
2338 rc = vdiFileGetSize(pImage, &cbFile);
2339 AssertRCBreak(rc);
2340 unsigned cBlocksAllocated = (unsigned)((cbFile - pImage->offStartData - pImage->offStartBlockData) >> pImage->uShiftOffset2Index);
2341 if (cBlocksAllocated == 0)
2342 {
2343 /* No data blocks in this image, no need to compact. */
2344 rc = VINF_SUCCESS;
2345 break;
2346 }
2347
2348 /* Allocate block array for back resolving. */
2349 paBlocks2 = (unsigned *)RTMemAlloc(sizeof(unsigned *) * cBlocksAllocated);
2350 AssertBreakStmt(VALID_PTR(paBlocks2), rc = VERR_NO_MEMORY);
2351 /* Fill out back resolving, check/fix allocation errors before
2352 * compacting the image, just to be on the safe side. Update the
2353 * image contents straight away, as this enables cancelling. */
2354 for (unsigned i = 0; i < cBlocksAllocated; i++)
2355 paBlocks2[i] = VDI_IMAGE_BLOCK_FREE;
2356 rc = VINF_SUCCESS;
2357 for (unsigned i = 0; i < cBlocks; i++)
2358 {
2359 VDIIMAGEBLOCKPOINTER ptrBlock = pImage->paBlocks[i];
2360 if (IS_VDI_IMAGE_BLOCK_ALLOCATED(ptrBlock))
2361 {
2362 if (ptrBlock < cBlocksAllocated)
2363 {
2364 if (paBlocks2[ptrBlock] == VDI_IMAGE_BLOCK_FREE)
2365 paBlocks2[ptrBlock] = i;
2366 else
2367 {
2368 LogFunc(("Freed cross-linked block %u in file \"%s\"\n",
2369 i, pImage->pszFilename));
2370 pImage->paBlocks[i] = VDI_IMAGE_BLOCK_FREE;
2371 rc = vdiUpdateBlockInfo(pImage, i);
2372 if (RT_FAILURE(rc))
2373 break;
2374 }
2375 }
2376 else
2377 {
2378 LogFunc(("Freed out of bounds reference for block %u in file \"%s\"\n",
2379 i, pImage->pszFilename));
2380 pImage->paBlocks[i] = VDI_IMAGE_BLOCK_FREE;
2381 rc = vdiUpdateBlockInfo(pImage, i);
2382 if (RT_FAILURE(rc))
2383 break;
2384 }
2385 }
2386 }
2387 if (RT_FAILURE(rc))
2388 break;
2389
2390 /* Find redundant information and update the block pointers
2391 * accordingly, creating bubbles. Keep disk up to date, as this
2392 * enables cancelling. */
2393 for (unsigned i = 0; i < cBlocks; i++)
2394 {
2395 VDIIMAGEBLOCKPOINTER ptrBlock = pImage->paBlocks[i];
2396 if (IS_VDI_IMAGE_BLOCK_ALLOCATED(ptrBlock))
2397 {
2398 /* Block present in image file, read relevant data. */
2399 uint64_t u64Offset = (uint64_t)ptrBlock * pImage->cbTotalBlockData
2400 + (pImage->offStartData + pImage->offStartBlockData);
2401 rc = vdiFileReadSync(pImage, u64Offset, pvTmp, cbBlock, NULL);
2402 if (RT_FAILURE(rc))
2403 break;
2404
2405 if (ASMBitFirstSet((volatile void *)pvTmp, (uint32_t)cbBlock * 8) == -1)
2406 {
2407 pImage->paBlocks[i] = VDI_IMAGE_BLOCK_ZERO;
2408 rc = vdiUpdateBlockInfo(pImage, i);
2409 if (RT_FAILURE(rc))
2410 break;
2411 paBlocks2[ptrBlock] = VDI_IMAGE_BLOCK_FREE;
2412 /* Adjust progress info, one block to be relocated. */
2413 cBlocksToMove++;
2414 }
2415 else if (pfnParentRead)
2416 {
2417 rc = pfnParentRead(pvParent, i * cbBlock, pvBuf, cbBlock);
2418 if (RT_FAILURE(rc))
2419 break;
2420 if (!memcmp(pvTmp, pvBuf, cbBlock))
2421 {
2422 pImage->paBlocks[i] = VDI_IMAGE_BLOCK_FREE;
2423 rc = vdiUpdateBlockInfo(pImage, i);
2424 if (RT_FAILURE(rc))
2425 break;
2426 paBlocks2[ptrBlock] = VDI_IMAGE_BLOCK_FREE;
2427 /* Adjust progress info, one block to be relocated. */
2428 cBlocksToMove++;
2429 }
2430 }
2431 }
2432
2433 if (pCbProgress && pCbProgress->pfnProgress)
2434 {
2435 rc = pCbProgress->pfnProgress(pIfProgress->pvUser,
2436 (uint64_t)i * uPercentSpan / (cBlocks + cBlocksToMove) + uPercentStart);
2437 if (RT_FAILURE(rc))
2438 break;
2439 }
2440 }
2441 if (RT_FAILURE(rc))
2442 break;
2443
2444 /* Fill bubbles with other data (if available). */
2445 unsigned cBlocksMoved = 0;
2446 unsigned uBlockUsedPos = cBlocksAllocated;
2447 for (unsigned i = 0; i < cBlocksAllocated; i++)
2448 {
2449 unsigned uBlock = paBlocks2[i];
2450 if (uBlock == VDI_IMAGE_BLOCK_FREE)
2451 {
2452 unsigned uBlockData = VDI_IMAGE_BLOCK_FREE;
2453 while (uBlockUsedPos > i && uBlockData == VDI_IMAGE_BLOCK_FREE)
2454 {
2455 uBlockUsedPos--;
2456 uBlockData = paBlocks2[uBlockUsedPos];
2457 }
2458 /* Terminate early if there is no block which needs copying. */
2459 if (uBlockUsedPos == i)
2460 break;
2461 uint64_t u64Offset = (uint64_t)uBlockUsedPos * pImage->cbTotalBlockData
2462 + (pImage->offStartData + pImage->offStartBlockData);
2463 rc = vdiFileReadSync(pImage, u64Offset, pvTmp, cbBlock, NULL);
2464 u64Offset = (uint64_t)i * pImage->cbTotalBlockData
2465 + (pImage->offStartData + pImage->offStartBlockData);
2466 rc = vdiFileWriteSync(pImage, u64Offset, pvTmp, cbBlock, NULL);
2467 pImage->paBlocks[uBlockData] = i;
2468 setImageBlocksAllocated(&pImage->Header, cBlocksAllocated - cBlocksMoved);
2469 rc = vdiUpdateBlockInfo(pImage, uBlockData);
2470 if (RT_FAILURE(rc))
2471 break;
2472 paBlocks2[i] = uBlockData;
2473 paBlocks2[uBlockUsedPos] = VDI_IMAGE_BLOCK_FREE;
2474 cBlocksMoved++;
2475 }
2476
2477 if (pCbProgress && pCbProgress->pfnProgress)
2478 {
2479 rc = pCbProgress->pfnProgress(pIfProgress->pvUser,
2480 (uint64_t)(cBlocks + cBlocksMoved) * uPercentSpan / (cBlocks + cBlocksToMove) + uPercentStart);
2481
2482 if (RT_FAILURE(rc))
2483 break;
2484 }
2485 }
2486 if (RT_FAILURE(rc))
2487 break;
2488
2489 /* Update image header. */
2490 setImageBlocksAllocated(&pImage->Header, uBlockUsedPos);
2491 vdiUpdateHeader(pImage);
2492
2493 /* Truncate the image to the proper size to finish compacting. */
2494 rc = vdiFileSetSize(pImage,
2495 (uint64_t)uBlockUsedPos * pImage->cbTotalBlockData
2496 + (pImage->offStartData + pImage->offStartBlockData));
2497 } while (0);
2498
2499 if (paBlocks2)
2500 RTMemTmpFree(paBlocks2);
2501 if (pvTmp)
2502 RTMemTmpFree(pvTmp);
2503 if (pvBuf)
2504 RTMemTmpFree(pvBuf);
2505
2506 if (RT_SUCCESS(rc) && pCbProgress && pCbProgress->pfnProgress)
2507 {
2508 pCbProgress->pfnProgress(pIfProgress->pvUser,
2509 uPercentStart + uPercentSpan);
2510 }
2511
2512 LogFlowFunc(("returns %Rrc\n", rc));
2513 return rc;
2514}
2515
2516
2517VBOXHDDBACKEND g_VDIBackend =
2518{
2519 /* pszBackendName */
2520 "VDI",
2521 /* cbSize */
2522 sizeof(VBOXHDDBACKEND),
2523 /* uBackendCaps */
2524 VD_CAP_UUID | VD_CAP_CREATE_FIXED | VD_CAP_CREATE_DYNAMIC
2525 | VD_CAP_DIFF | VD_CAP_FILE | VD_CAP_ASYNC,
2526 /* papszFileExtensions */
2527 s_apszVdiFileExtensions,
2528 /* paConfigInfo */
2529 NULL,
2530 /* hPlugin */
2531 NIL_RTLDRMOD,
2532 /* pfnCheckIfValid */
2533 vdiCheckIfValid,
2534 /* pfnOpen */
2535 vdiOpen,
2536 /* pfnCreate */
2537 vdiCreate,
2538 /* pfnRename */
2539 vdiRename,
2540 /* pfnClose */
2541 vdiClose,
2542 /* pfnRead */
2543 vdiRead,
2544 /* pfnWrite */
2545 vdiWrite,
2546 /* pfnFlush */
2547 vdiFlush,
2548 /* pfnGetVersion */
2549 vdiGetVersion,
2550 /* pfnGetSize */
2551 vdiGetSize,
2552 /* pfnGetFileSize */
2553 vdiGetFileSize,
2554 /* pfnGetPCHSGeometry */
2555 vdiGetPCHSGeometry,
2556 /* pfnSetPCHSGeometry */
2557 vdiSetPCHSGeometry,
2558 /* pfnGetLCHSGeometry */
2559 vdiGetLCHSGeometry,
2560 /* pfnSetLCHSGeometry */
2561 vdiSetLCHSGeometry,
2562 /* pfnGetImageFlags */
2563 vdiGetImageFlags,
2564 /* pfnGetOpenFlags */
2565 vdiGetOpenFlags,
2566 /* pfnSetOpenFlags */
2567 vdiSetOpenFlags,
2568 /* pfnGetComment */
2569 vdiGetComment,
2570 /* pfnSetComment */
2571 vdiSetComment,
2572 /* pfnGetUuid */
2573 vdiGetUuid,
2574 /* pfnSetUuid */
2575 vdiSetUuid,
2576 /* pfnGetModificationUuid */
2577 vdiGetModificationUuid,
2578 /* pfnSetModificationUuid */
2579 vdiSetModificationUuid,
2580 /* pfnGetParentUuid */
2581 vdiGetParentUuid,
2582 /* pfnSetParentUuid */
2583 vdiSetParentUuid,
2584 /* pfnGetParentModificationUuid */
2585 vdiGetParentModificationUuid,
2586 /* pfnSetParentModificationUuid */
2587 vdiSetParentModificationUuid,
2588 /* pfnDump */
2589 vdiDump,
2590 /* pfnGetTimeStamp */
2591 vdiGetTimeStamp,
2592 /* pfnGetParentTimeStamp */
2593 vdiGetParentTimeStamp,
2594 /* pfnSetParentTimeStamp */
2595 vdiSetParentTimeStamp,
2596 /* pfnGetParentFilename */
2597 vdiGetParentFilename,
2598 /* pfnSetParentFilename */
2599 vdiSetParentFilename,
2600 /* pfnIsAsyncIOSupported */
2601 vdiIsAsyncIOSupported,
2602 /* pfnAsyncRead */
2603 vdiAsyncRead,
2604 /* pfnAsyncWrite */
2605 vdiAsyncWrite,
2606 /* pfnAsyncFlush */
2607 vdiAsyncFlush,
2608 /* pfnComposeLocation */
2609 genericFileComposeLocation,
2610 /* pfnComposeName */
2611 genericFileComposeName,
2612 /* pfnCompact */
2613 vdiCompact
2614};
2615
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