VirtualBox

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

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

Storage: Convert from PDMDATASEG to RTSGSEG to avoid casting between those two in VBoxHDD and more async I/O updates

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