VirtualBox

source: vbox/trunk/src/VBox/Devices/Storage/DrvVD.cpp@ 63917

Last change on this file since 63917 was 63917, checked in by vboxsync, 8 years ago

DrvVD: Don't fail completely when loading a plugin failed, log the error and go on

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 189.4 KB
Line 
1/* $Id: DrvVD.cpp 63917 2016-09-21 07:58:31Z vboxsync $ */
2/** @file
3 * DrvVD - Generic VBox disk media driver.
4 */
5
6/*
7 * Copyright (C) 2006-2016 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18
19/*********************************************************************************************************************************
20* Header files *
21*********************************************************************************************************************************/
22#define LOG_GROUP LOG_GROUP_DRV_VD
23#include <VBox/vd.h>
24#include <VBox/vmm/pdmdrv.h>
25#include <VBox/vmm/pdmstorageifs.h>
26#include <VBox/vmm/pdmasynccompletion.h>
27#include <VBox/vmm/pdmblkcache.h>
28#include <VBox/vmm/ssm.h>
29#include <iprt/asm.h>
30#include <iprt/alloc.h>
31#include <iprt/assert.h>
32#include <iprt/uuid.h>
33#include <iprt/file.h>
34#include <iprt/string.h>
35#include <iprt/tcp.h>
36#include <iprt/semaphore.h>
37#include <iprt/sg.h>
38#include <iprt/poll.h>
39#include <iprt/pipe.h>
40#include <iprt/system.h>
41#include <iprt/memsafer.h>
42#include <iprt/memcache.h>
43#include <iprt/list.h>
44
45#ifdef VBOX_WITH_INIP
46/* All lwip header files are not C++ safe. So hack around this. */
47RT_C_DECLS_BEGIN
48#include <lwip/opt.h>
49#include <lwip/inet.h>
50#include <lwip/tcp.h>
51#include <lwip/sockets.h>
52# if LWIP_IPV6
53# include <lwip/inet6.h>
54# endif
55RT_C_DECLS_END
56#endif /* VBOX_WITH_INIP */
57
58#include "HBDMgmt.h"
59#include "IOBufMgmt.h"
60
61#include "VBoxDD.h"
62
63#ifdef VBOX_WITH_INIP
64/* Small hack to get at lwIP initialized status */
65extern bool DevINIPConfigured(void);
66#endif /* VBOX_WITH_INIP */
67
68
69/** @def VBOX_PERIODIC_FLUSH
70 * Enable support for periodically flushing the VDI to disk. This may prove
71 * useful for those nasty problems with the ultra-slow host filesystems.
72 * If this is enabled, it can be configured via the CFGM key
73 * "VBoxInternal/Devices/piix3ide/0/LUN#<x>/Config/FlushInterval". <x>
74 * must be replaced with the correct LUN number of the disk that should
75 * do the periodic flushes. The value of the key is the number of bytes
76 * written between flushes. A value of 0 (the default) denotes no flushes. */
77#define VBOX_PERIODIC_FLUSH
78
79/** @def VBOX_IGNORE_FLUSH
80 * Enable support for ignoring VDI flush requests. This can be useful for
81 * filesystems that show bad guest IDE write performance (especially with
82 * Windows guests). NOTE that this does not disable the flushes caused by
83 * the periodic flush cache feature above.
84 * If this feature is enabled, it can be configured via the CFGM key
85 * "VBoxInternal/Devices/piix3ide/0/LUN#<x>/Config/IgnoreFlush". <x>
86 * must be replaced with the correct LUN number of the disk that should
87 * ignore flush requests. The value of the key is a boolean. The default
88 * is to ignore flushes, i.e. true. */
89#define VBOX_IGNORE_FLUSH
90
91
92/*********************************************************************************************************************************
93* Defined types, constants and macros *
94*********************************************************************************************************************************/
95
96/** Converts a pointer to VBOXDISK::IMedia to a PVBOXDISK. */
97#define PDMIMEDIA_2_VBOXDISK(pInterface) \
98 ( (PVBOXDISK)((uintptr_t)pInterface - RT_OFFSETOF(VBOXDISK, IMedia)) )
99
100/** Converts a pointer to VBOXDISK::IMediaAsync to a PVBOXDISK. */
101#define PDMIMEDIAASYNC_2_VBOXDISK(pInterface) \
102 ( (PVBOXDISK)((uintptr_t)pInterface - RT_OFFSETOF(VBOXDISK, IMediaAsync)) )
103
104/** Saved state version of an I/O request .*/
105#define DRVVD_IOREQ_SAVED_STATE_VERSION UINT32_C(1)
106/** Maximum number of request errors in the release log before muting. */
107#define DRVVD_MAX_LOG_REL_ERRORS 100
108
109/** Forward declaration for the dis kcontainer. */
110typedef struct VBOXDISK *PVBOXDISK;
111
112/**
113 * VBox disk container, image information, private part.
114 */
115
116typedef struct VBOXIMAGE
117{
118 /** Pointer to next image. */
119 struct VBOXIMAGE *pNext;
120 /** Pointer to list of VD interfaces. Per-image. */
121 PVDINTERFACE pVDIfsImage;
122 /** Configuration information interface. */
123 VDINTERFACECONFIG VDIfConfig;
124 /** TCP network stack interface. */
125 VDINTERFACETCPNET VDIfTcpNet;
126 /** I/O interface. */
127 VDINTERFACEIO VDIfIo;
128} VBOXIMAGE, *PVBOXIMAGE;
129
130/**
131 * Storage backend data.
132 */
133typedef struct DRVVDSTORAGEBACKEND
134{
135 /** PDM async completion end point. */
136 PPDMASYNCCOMPLETIONENDPOINT pEndpoint;
137 /** The template. */
138 PPDMASYNCCOMPLETIONTEMPLATE pTemplate;
139 /** Event semaphore for synchronous operations. */
140 RTSEMEVENT EventSem;
141 /** Flag whether a synchronous operation is currently pending. */
142 volatile bool fSyncIoPending;
143 /** Return code of the last completed request. */
144 int rcReqLast;
145 /** Callback routine */
146 PFNVDCOMPLETED pfnCompleted;
147} DRVVDSTORAGEBACKEND, *PDRVVDSTORAGEBACKEND;
148
149/**
150 * VD I/O request state.
151 */
152typedef enum VDIOREQSTATE
153{
154 /** Invalid. */
155 VDIOREQSTATE_INVALID = 0,
156 /** The request is not in use and resides on the free list. */
157 VDIOREQSTATE_FREE,
158 /** The request was just allocated and is not active. */
159 VDIOREQSTATE_ALLOCATED,
160 /** The request was allocated and is in use. */
161 VDIOREQSTATE_ACTIVE,
162 /** The request was suspended and is not actively processed. */
163 VDIOREQSTATE_SUSPENDED,
164 /** The request is in the last step of completion and syncs memory. */
165 VDIOREQSTATE_COMPLETING,
166 /** The request completed. */
167 VDIOREQSTATE_COMPLETED,
168 /** The request was aborted but wasn't returned as complete from the storage
169 * layer below us. */
170 VDIOREQSTATE_CANCELED,
171 /** 32bit hack. */
172 VDIOREQSTATE_32BIT_HACK = 0x7fffffff
173} VDIOREQSTATE;
174
175/**
176 * VD I/O Request.
177 */
178typedef struct PDMMEDIAEXIOREQINT
179{
180 /** List node for the list of allocated requests. */
181 RTLISTNODE NdAllocatedList;
182 /** List for requests waiting for I/O memory or on the redo list. */
183 RTLISTNODE NdLstWait;
184 /** I/O request type. */
185 PDMMEDIAEXIOREQTYPE enmType;
186 /** Request state. */
187 volatile VDIOREQSTATE enmState;
188 /** I/O request ID. */
189 PDMMEDIAEXIOREQID uIoReqId;
190 /** Pointer to the disk container. */
191 PVBOXDISK pDisk;
192 /** Flags. */
193 uint32_t fFlags;
194 /** Timestamp when the request was submitted. */
195 uint64_t tsSubmit;
196 /** Type dependent data. */
197 union
198 {
199 /** Read/Write request sepcific data. */
200 struct
201 {
202 /** Start offset of the request. */
203 uint64_t offStart;
204 /** Size of the request. */
205 size_t cbReq;
206 /** Size left for this request. */
207 size_t cbReqLeft;
208 /** Size of the allocated I/O buffer. */
209 size_t cbIoBuf;
210 /** I/O buffer descriptor. */
211 IOBUFDESC IoBuf;
212 } ReadWrite;
213 /** Discard specific data. */
214 struct
215 {
216 /** Pointer to array of ranges to discard. */
217 PRTRANGE paRanges;
218 /** Number of ranges to discard. */
219 unsigned cRanges;
220 } Discard;
221 };
222 /** Allocator specific memory - variable size. */
223 uint8_t abAlloc[1];
224} PDMMEDIAEXIOREQINT;
225/** Pointer to a VD I/O request. */
226typedef PDMMEDIAEXIOREQINT *PPDMMEDIAEXIOREQINT;
227
228/**
229 * Structure for holding a list of allocated requests.
230 */
231typedef struct VDLSTIOREQALLOC
232{
233 /** Mutex protecting the table of allocated requests. */
234 RTSEMFASTMUTEX hMtxLstIoReqAlloc;
235 /** List anchor. */
236 RTLISTANCHOR LstIoReqAlloc;
237} VDLSTIOREQALLOC;
238typedef VDLSTIOREQALLOC *PVDLSTIOREQALLOC;
239
240/** Number of bins for allocated requests. */
241#define DRVVD_VDIOREQ_ALLOC_BINS 8
242
243/**
244 * VBox disk container media main structure, private part.
245 *
246 * @implements PDMIMEDIA
247 * @implements PDMIMEDIAASYNC
248 * @implements PDMIMEDIAEX
249 * @implements PDMIMOUNT
250 * @implements VDINTERFACEERROR
251 * @implements VDINTERFACETCPNET
252 * @implements VDINTERFACEASYNCIO
253 * @implements VDINTERFACECONFIG
254 */
255typedef struct VBOXDISK
256{
257 /** The VBox disk container. */
258 PVBOXHDD pDisk;
259 /** The media interface. */
260 PDMIMEDIA IMedia;
261 /** Media port. */
262 PPDMIMEDIAPORT pDrvMediaPort;
263 /** Pointer to the driver instance. */
264 PPDMDRVINS pDrvIns;
265 /** Flag whether suspend has changed image open mode to read only. */
266 bool fTempReadOnly;
267 /** Flag whether to use the runtime (true) or startup error facility. */
268 bool fErrorUseRuntime;
269 /** Pointer to list of VD interfaces. Per-disk. */
270 PVDINTERFACE pVDIfsDisk;
271 /** Error interface. */
272 VDINTERFACEERROR VDIfError;
273 /** Thread synchronization interface. */
274 VDINTERFACETHREADSYNC VDIfThreadSync;
275
276 /** Flag whether opened disk supports async I/O operations. */
277 bool fAsyncIOSupported;
278 /** The async media interface. */
279 PDMIMEDIAASYNC IMediaAsync;
280 /** The async media port interface above. */
281 PPDMIMEDIAASYNCPORT pDrvMediaAsyncPort;
282 /** Pointer to the list of data we need to keep per image. */
283 PVBOXIMAGE pImages;
284 /** Flag whether the media should allow concurrent open for writing. */
285 bool fShareable;
286 /** Flag whether a merge operation has been set up. */
287 bool fMergePending;
288 /** Synchronization to prevent destruction before merge finishes. */
289 RTSEMFASTMUTEX MergeCompleteMutex;
290 /** Synchronization between merge and other image accesses. */
291 RTSEMRW MergeLock;
292 /** Source image index for merging. */
293 unsigned uMergeSource;
294 /** Target image index for merging. */
295 unsigned uMergeTarget;
296
297 /** Flag whether boot acceleration is enabled. */
298 bool fBootAccelEnabled;
299 /** Flag whether boot acceleration is currently active. */
300 bool fBootAccelActive;
301 /** Size of the disk, used for read truncation. */
302 uint64_t cbDisk;
303 /** Size of the configured buffer. */
304 size_t cbBootAccelBuffer;
305 /** Start offset for which the buffer holds data. */
306 uint64_t offDisk;
307 /** Number of valid bytes in the buffer. */
308 size_t cbDataValid;
309 /** The disk buffer. */
310 uint8_t *pbData;
311 /** Bandwidth group the disk is assigned to. */
312 char *pszBwGroup;
313 /** Flag whether async I/O using the host cache is enabled. */
314 bool fAsyncIoWithHostCache;
315
316 /** I/O interface for a cache image. */
317 VDINTERFACEIO VDIfIoCache;
318 /** Interface list for the cache image. */
319 PVDINTERFACE pVDIfsCache;
320
321 /** The block cache handle if configured. */
322 PPDMBLKCACHE pBlkCache;
323 /** Host block device manager. */
324 HBDMGR hHbdMgr;
325
326 /** Drive type. */
327 PDMMEDIATYPE enmType;
328 /** Locked indicator. */
329 bool fLocked;
330 /** Mountable indicator. */
331 bool fMountable;
332 /** Visible to the BIOS. */
333 bool fBiosVisible;
334#ifdef VBOX_PERIODIC_FLUSH
335 /** HACK: Configuration value for number of bytes written after which to flush. */
336 uint32_t cbFlushInterval;
337 /** HACK: Current count for the number of bytes written since the last flush. */
338 uint32_t cbDataWritten;
339#endif /* VBOX_PERIODIC_FLUSH */
340#ifdef VBOX_IGNORE_FLUSH
341 /** HACK: Disable flushes for this drive. */
342 bool fIgnoreFlush;
343 /** Disable async flushes for this drive. */
344 bool fIgnoreFlushAsync;
345#endif /* VBOX_IGNORE_FLUSH */
346 /** Our mountable interface. */
347 PDMIMOUNT IMount;
348 /** Pointer to the mount notify interface above us. */
349 PPDMIMOUNTNOTIFY pDrvMountNotify;
350 /** Uuid of the drive. */
351 RTUUID Uuid;
352 /** BIOS PCHS Geometry. */
353 PDMMEDIAGEOMETRY PCHSGeometry;
354 /** BIOS LCHS Geometry. */
355 PDMMEDIAGEOMETRY LCHSGeometry;
356
357 /** Cryptographic support
358 * @{ */
359 /** Pointer to the CFGM node containing the config of the crypto filter
360 * if enable. */
361 PCFGMNODE pCfgCrypto;
362 /** Config interface for the encryption filter. */
363 VDINTERFACECONFIG VDIfCfg;
364 /** Crypto interface for the encryption filter. */
365 VDINTERFACECRYPTO VDIfCrypto;
366 /** The secret key interface used to retrieve keys. */
367 PPDMISECKEY pIfSecKey;
368 /** The secret key helper interface used to notify about missing keys. */
369 PPDMISECKEYHLP pIfSecKeyHlp;
370 /** @} */
371
372 /** @name IMEDIAEX interface support specific members.
373 * @{ */
374 /** Pointer to the IMEDIAEXPORT interface above us. */
375 PPDMIMEDIAEXPORT pDrvMediaExPort;
376 /** Our extended media interface. */
377 PDMIMEDIAEX IMediaEx;
378 /** Memory cache for the I/O requests. */
379 RTMEMCACHE hIoReqCache;
380 /** I/O buffer manager. */
381 IOBUFMGR hIoBufMgr;
382 /** Active request counter. */
383 volatile uint32_t cIoReqsActive;
384 /** Bins for allocated requests. */
385 VDLSTIOREQALLOC aIoReqAllocBins[DRVVD_VDIOREQ_ALLOC_BINS];
386 /** List of requests for I/O memory to be available - VDIOREQ::NdLstWait. */
387 RTLISTANCHOR LstIoReqIoBufWait;
388 /** Critical section protecting the list of requests waiting for I/O memory. */
389 RTCRITSECT CritSectIoReqsIoBufWait;
390 /** Number of requests waiting for a I/O buffer. */
391 volatile uint32_t cIoReqsWaiting;
392 /** Flag whether we have to resubmit requests on resume because the
393 * VM was suspended due to a recoverable I/O error.
394 */
395 volatile bool fRedo;
396 /** List of requests we have to redo. */
397 RTLISTANCHOR LstIoReqRedo;
398 /** Criticial section protecting the list of waiting requests. */
399 RTCRITSECT CritSectIoReqRedo;
400 /** Number of errors logged so far. */
401 unsigned cErrors;
402 /** @} */
403} VBOXDISK;
404
405
406/*********************************************************************************************************************************
407* Internal Functions *
408*********************************************************************************************************************************/
409
410static DECLCALLBACK(void) drvvdMediaExIoReqComplete(void *pvUser1, void *pvUser2, int rcReq);
411static void drvvdPowerOffOrDestructOrUnmount(PPDMDRVINS pDrvIns);
412DECLINLINE(void) drvvdMediaExIoReqBufFree(PVBOXDISK pThis, PPDMMEDIAEXIOREQINT pIoReq);
413static int drvvdMediaExIoReqReadWriteProcess(PVBOXDISK pThis, PPDMMEDIAEXIOREQINT pIoReq, bool fUpNotify);
414
415/**
416 * Internal: allocate new image descriptor and put it in the list
417 */
418static PVBOXIMAGE drvvdNewImage(PVBOXDISK pThis)
419{
420 AssertPtr(pThis);
421 PVBOXIMAGE pImage = (PVBOXIMAGE)RTMemAllocZ(sizeof(VBOXIMAGE));
422 if (pImage)
423 {
424 pImage->pVDIfsImage = NULL;
425 PVBOXIMAGE *pp = &pThis->pImages;
426 while (*pp != NULL)
427 pp = &(*pp)->pNext;
428 *pp = pImage;
429 pImage->pNext = NULL;
430 }
431
432 return pImage;
433}
434
435/**
436 * Internal: free the list of images descriptors.
437 */
438static void drvvdFreeImages(PVBOXDISK pThis)
439{
440 while (pThis->pImages != NULL)
441 {
442 PVBOXIMAGE p = pThis->pImages;
443 pThis->pImages = pThis->pImages->pNext;
444 RTMemFree(p);
445 }
446}
447
448
449/**
450 * Make the image temporarily read-only.
451 *
452 * @returns VBox status code.
453 * @param pThis The driver instance data.
454 */
455static int drvvdSetReadonly(PVBOXDISK pThis)
456{
457 int rc = VINF_SUCCESS;
458 if ( pThis->pDisk
459 && !VDIsReadOnly(pThis->pDisk))
460 {
461 unsigned uOpenFlags;
462 rc = VDGetOpenFlags(pThis->pDisk, VD_LAST_IMAGE, &uOpenFlags);
463 AssertRC(rc);
464 uOpenFlags |= VD_OPEN_FLAGS_READONLY;
465 rc = VDSetOpenFlags(pThis->pDisk, VD_LAST_IMAGE, uOpenFlags);
466 AssertRC(rc);
467 pThis->fTempReadOnly = true;
468 }
469 return rc;
470}
471
472
473/**
474 * Undo the temporary read-only status of the image.
475 *
476 * @returns VBox status code.
477 * @param pThis The driver instance data.
478 */
479static int drvvdSetWritable(PVBOXDISK pThis)
480{
481 int rc = VINF_SUCCESS;
482 if (pThis->fTempReadOnly)
483 {
484 unsigned uOpenFlags;
485 rc = VDGetOpenFlags(pThis->pDisk, VD_LAST_IMAGE, &uOpenFlags);
486 AssertRC(rc);
487 uOpenFlags &= ~VD_OPEN_FLAGS_READONLY;
488 rc = VDSetOpenFlags(pThis->pDisk, VD_LAST_IMAGE, uOpenFlags);
489 if (RT_SUCCESS(rc))
490 pThis->fTempReadOnly = false;
491 else
492 AssertRC(rc);
493 }
494 return rc;
495}
496
497
498/*********************************************************************************************************************************
499* Error reporting callback *
500*********************************************************************************************************************************/
501
502static DECLCALLBACK(void) drvvdErrorCallback(void *pvUser, int rc, RT_SRC_POS_DECL,
503 const char *pszFormat, va_list va)
504{
505 PPDMDRVINS pDrvIns = (PPDMDRVINS)pvUser;
506 PVBOXDISK pThis = PDMINS_2_DATA(pDrvIns, PVBOXDISK);
507 if (pThis->fErrorUseRuntime)
508 /* We must not pass VMSETRTERR_FLAGS_FATAL as it could lead to a
509 * deadlock: We are probably executed in a thread context != EMT
510 * and the EM thread would wait until every thread is suspended
511 * but we would wait for the EM thread ... */
512
513 PDMDrvHlpVMSetRuntimeErrorV(pDrvIns, /* fFlags=*/ 0, "DrvVD", pszFormat, va);
514 else
515 PDMDrvHlpVMSetErrorV(pDrvIns, rc, RT_SRC_POS_ARGS, pszFormat, va);
516}
517
518
519/*********************************************************************************************************************************
520* VD Async I/O interface implementation *
521*********************************************************************************************************************************/
522
523#ifdef VBOX_WITH_PDM_ASYNC_COMPLETION
524
525static DECLCALLBACK(void) drvvdAsyncTaskCompleted(PPDMDRVINS pDrvIns, void *pvTemplateUser, void *pvUser, int rcReq)
526{
527 RT_NOREF(pDrvIns);
528 PDRVVDSTORAGEBACKEND pStorageBackend = (PDRVVDSTORAGEBACKEND)pvTemplateUser;
529
530 LogFlowFunc(("pDrvIns=%#p pvTemplateUser=%#p pvUser=%#p rcReq=%d\n",
531 pDrvIns, pvTemplateUser, pvUser, rcReq));
532
533 if (pStorageBackend->fSyncIoPending)
534 {
535 Assert(!pvUser);
536 pStorageBackend->rcReqLast = rcReq;
537 ASMAtomicWriteBool(&pStorageBackend->fSyncIoPending, false);
538 RTSemEventSignal(pStorageBackend->EventSem);
539 }
540 else
541 {
542 int rc;
543
544 AssertPtr(pvUser);
545
546 AssertPtr(pStorageBackend->pfnCompleted);
547 rc = pStorageBackend->pfnCompleted(pvUser, rcReq);
548 AssertRC(rc);
549 }
550}
551
552static DECLCALLBACK(int) drvvdAsyncIOOpen(void *pvUser, const char *pszLocation,
553 uint32_t fOpen,
554 PFNVDCOMPLETED pfnCompleted,
555 void **ppStorage)
556{
557 PVBOXDISK pThis = (PVBOXDISK)pvUser;
558 PDRVVDSTORAGEBACKEND pStorageBackend = NULL;
559 int rc = VINF_SUCCESS;
560
561 /*
562 * Check whether the backend wants to open a block device and try to prepare it
563 * if we didn't claim it yet.
564 *
565 * We only create a block device manager on demand to not waste any resources.
566 */
567 if (HBDMgrIsBlockDevice(pszLocation))
568 {
569 if (pThis->hHbdMgr == NIL_HBDMGR)
570 rc = HBDMgrCreate(&pThis->hHbdMgr);
571
572 if ( RT_SUCCESS(rc)
573 && !HBDMgrIsBlockDeviceClaimed(pThis->hHbdMgr, pszLocation))
574 rc = HBDMgrClaimBlockDevice(pThis->hHbdMgr, pszLocation);
575
576 if (RT_FAILURE(rc))
577 return rc;
578 }
579
580 pStorageBackend = (PDRVVDSTORAGEBACKEND)RTMemAllocZ(sizeof(DRVVDSTORAGEBACKEND));
581 if (pStorageBackend)
582 {
583 pStorageBackend->fSyncIoPending = false;
584 pStorageBackend->rcReqLast = VINF_SUCCESS;
585 pStorageBackend->pfnCompleted = pfnCompleted;
586
587 rc = RTSemEventCreate(&pStorageBackend->EventSem);
588 if (RT_SUCCESS(rc))
589 {
590 rc = PDMDrvHlpAsyncCompletionTemplateCreate(pThis->pDrvIns, &pStorageBackend->pTemplate,
591 drvvdAsyncTaskCompleted, pStorageBackend, "AsyncTaskCompleted");
592 if (RT_SUCCESS(rc))
593 {
594 uint32_t fFlags = (fOpen & RTFILE_O_ACCESS_MASK) == RTFILE_O_READ
595 ? PDMACEP_FILE_FLAGS_READ_ONLY
596 : 0;
597 if (pThis->fShareable)
598 {
599 Assert((fOpen & RTFILE_O_DENY_MASK) == RTFILE_O_DENY_NONE);
600
601 fFlags |= PDMACEP_FILE_FLAGS_DONT_LOCK;
602 }
603 if (pThis->fAsyncIoWithHostCache)
604 fFlags |= PDMACEP_FILE_FLAGS_HOST_CACHE_ENABLED;
605
606 rc = PDMR3AsyncCompletionEpCreateForFile(&pStorageBackend->pEndpoint,
607 pszLocation, fFlags,
608 pStorageBackend->pTemplate);
609
610 if (RT_SUCCESS(rc))
611 {
612 if (pThis->pszBwGroup)
613 rc = PDMR3AsyncCompletionEpSetBwMgr(pStorageBackend->pEndpoint, pThis->pszBwGroup);
614
615 if (RT_SUCCESS(rc))
616 {
617 LogFlow(("drvvdAsyncIOOpen: Successfully opened '%s'; fOpen=%#x pStorage=%p\n",
618 pszLocation, fOpen, pStorageBackend));
619 *ppStorage = pStorageBackend;
620 return VINF_SUCCESS;
621 }
622
623 PDMR3AsyncCompletionEpClose(pStorageBackend->pEndpoint);
624 }
625
626 PDMR3AsyncCompletionTemplateDestroy(pStorageBackend->pTemplate);
627 }
628 RTSemEventDestroy(pStorageBackend->EventSem);
629 }
630 RTMemFree(pStorageBackend);
631 }
632 else
633 rc = VERR_NO_MEMORY;
634
635 return rc;
636}
637
638static DECLCALLBACK(int) drvvdAsyncIOClose(void *pvUser, void *pStorage)
639{
640 RT_NOREF(pvUser);
641 PDRVVDSTORAGEBACKEND pStorageBackend = (PDRVVDSTORAGEBACKEND)pStorage;
642
643 /*
644 * We don't unclaim any block devices on purpose here because they
645 * might get reopened shortly (switching to readonly during suspend)
646 *
647 * Block devices will get unclaimed during destruction of the driver.
648 */
649
650 PDMR3AsyncCompletionEpClose(pStorageBackend->pEndpoint);
651 PDMR3AsyncCompletionTemplateDestroy(pStorageBackend->pTemplate);
652 RTSemEventDestroy(pStorageBackend->EventSem);
653 RTMemFree(pStorageBackend);
654 return VINF_SUCCESS;;
655}
656
657static DECLCALLBACK(int) drvvdAsyncIOReadSync(void *pvUser, void *pStorage, uint64_t uOffset,
658 void *pvBuf, size_t cbRead, size_t *pcbRead)
659{
660 RT_NOREF(pvUser);
661 PDRVVDSTORAGEBACKEND pStorageBackend = (PDRVVDSTORAGEBACKEND)pStorage;
662 RTSGSEG DataSeg;
663 PPDMASYNCCOMPLETIONTASK pTask;
664
665 bool fOld = ASMAtomicXchgBool(&pStorageBackend->fSyncIoPending, true);
666 Assert(!fOld); NOREF(fOld);
667 DataSeg.cbSeg = cbRead;
668 DataSeg.pvSeg = pvBuf;
669
670 int rc = PDMR3AsyncCompletionEpRead(pStorageBackend->pEndpoint, uOffset, &DataSeg, 1, cbRead, NULL, &pTask);
671 if (RT_FAILURE(rc))
672 return rc;
673
674 if (rc == VINF_AIO_TASK_PENDING)
675 {
676 /* Wait */
677 rc = RTSemEventWait(pStorageBackend->EventSem, RT_INDEFINITE_WAIT);
678 AssertRC(rc);
679 }
680 else
681 ASMAtomicXchgBool(&pStorageBackend->fSyncIoPending, false);
682
683 if (pcbRead)
684 *pcbRead = cbRead;
685
686 return pStorageBackend->rcReqLast;
687}
688
689static DECLCALLBACK(int) drvvdAsyncIOWriteSync(void *pvUser, void *pStorage, uint64_t uOffset,
690 const void *pvBuf, size_t cbWrite, size_t *pcbWritten)
691{
692 RT_NOREF(pvUser);
693 PDRVVDSTORAGEBACKEND pStorageBackend = (PDRVVDSTORAGEBACKEND)pStorage;
694 RTSGSEG DataSeg;
695 PPDMASYNCCOMPLETIONTASK pTask;
696
697 bool fOld = ASMAtomicXchgBool(&pStorageBackend->fSyncIoPending, true);
698 Assert(!fOld); NOREF(fOld);
699 DataSeg.cbSeg = cbWrite;
700 DataSeg.pvSeg = (void *)pvBuf;
701
702 int rc = PDMR3AsyncCompletionEpWrite(pStorageBackend->pEndpoint, uOffset, &DataSeg, 1, cbWrite, NULL, &pTask);
703 if (RT_FAILURE(rc))
704 return rc;
705
706 if (rc == VINF_AIO_TASK_PENDING)
707 {
708 /* Wait */
709 rc = RTSemEventWait(pStorageBackend->EventSem, RT_INDEFINITE_WAIT);
710 AssertRC(rc);
711 }
712 else
713 ASMAtomicXchgBool(&pStorageBackend->fSyncIoPending, false);
714
715 if (pcbWritten)
716 *pcbWritten = cbWrite;
717
718 return pStorageBackend->rcReqLast;
719}
720
721static DECLCALLBACK(int) drvvdAsyncIOFlushSync(void *pvUser, void *pStorage)
722{
723 RT_NOREF(pvUser);
724 PDRVVDSTORAGEBACKEND pStorageBackend = (PDRVVDSTORAGEBACKEND)pStorage;
725 PPDMASYNCCOMPLETIONTASK pTask;
726
727 LogFlowFunc(("pvUser=%#p pStorage=%#p\n", pvUser, pStorage));
728
729 bool fOld = ASMAtomicXchgBool(&pStorageBackend->fSyncIoPending, true);
730 Assert(!fOld); NOREF(fOld);
731
732 int rc = PDMR3AsyncCompletionEpFlush(pStorageBackend->pEndpoint, NULL, &pTask);
733 if (RT_FAILURE(rc))
734 return rc;
735
736 if (rc == VINF_AIO_TASK_PENDING)
737 {
738 /* Wait */
739 LogFlowFunc(("Waiting for flush to complete\n"));
740 rc = RTSemEventWait(pStorageBackend->EventSem, RT_INDEFINITE_WAIT);
741 AssertRC(rc);
742 }
743 else
744 ASMAtomicXchgBool(&pStorageBackend->fSyncIoPending, false);
745
746 return pStorageBackend->rcReqLast;
747}
748
749static DECLCALLBACK(int) drvvdAsyncIOReadAsync(void *pvUser, void *pStorage, uint64_t uOffset,
750 PCRTSGSEG paSegments, size_t cSegments,
751 size_t cbRead, void *pvCompletion,
752 void **ppTask)
753{
754 RT_NOREF(pvUser);
755 PDRVVDSTORAGEBACKEND pStorageBackend = (PDRVVDSTORAGEBACKEND)pStorage;
756
757 int rc = PDMR3AsyncCompletionEpRead(pStorageBackend->pEndpoint, uOffset, paSegments, (unsigned)cSegments, cbRead,
758 pvCompletion, (PPPDMASYNCCOMPLETIONTASK)ppTask);
759 if (rc == VINF_AIO_TASK_PENDING)
760 rc = VERR_VD_ASYNC_IO_IN_PROGRESS;
761
762 return rc;
763}
764
765static DECLCALLBACK(int) drvvdAsyncIOWriteAsync(void *pvUser, void *pStorage, uint64_t uOffset,
766 PCRTSGSEG paSegments, size_t cSegments,
767 size_t cbWrite, void *pvCompletion,
768 void **ppTask)
769{
770 RT_NOREF(pvUser);
771 PDRVVDSTORAGEBACKEND pStorageBackend = (PDRVVDSTORAGEBACKEND)pStorage;
772
773 int rc = PDMR3AsyncCompletionEpWrite(pStorageBackend->pEndpoint, uOffset, paSegments, (unsigned)cSegments, cbWrite,
774 pvCompletion, (PPPDMASYNCCOMPLETIONTASK)ppTask);
775 if (rc == VINF_AIO_TASK_PENDING)
776 rc = VERR_VD_ASYNC_IO_IN_PROGRESS;
777
778 return rc;
779}
780
781static DECLCALLBACK(int) drvvdAsyncIOFlushAsync(void *pvUser, void *pStorage,
782 void *pvCompletion, void **ppTask)
783{
784 RT_NOREF(pvUser);
785 PDRVVDSTORAGEBACKEND pStorageBackend = (PDRVVDSTORAGEBACKEND)pStorage;
786
787 int rc = PDMR3AsyncCompletionEpFlush(pStorageBackend->pEndpoint, pvCompletion,
788 (PPPDMASYNCCOMPLETIONTASK)ppTask);
789 if (rc == VINF_AIO_TASK_PENDING)
790 rc = VERR_VD_ASYNC_IO_IN_PROGRESS;
791
792 return rc;
793}
794
795static DECLCALLBACK(int) drvvdAsyncIOGetSize(void *pvUser, void *pStorage, uint64_t *pcbSize)
796{
797 RT_NOREF(pvUser);
798 PDRVVDSTORAGEBACKEND pStorageBackend = (PDRVVDSTORAGEBACKEND)pStorage;
799
800 return PDMR3AsyncCompletionEpGetSize(pStorageBackend->pEndpoint, pcbSize);
801}
802
803static DECLCALLBACK(int) drvvdAsyncIOSetSize(void *pvUser, void *pStorage, uint64_t cbSize)
804{
805 RT_NOREF(pvUser);
806 PDRVVDSTORAGEBACKEND pStorageBackend = (PDRVVDSTORAGEBACKEND)pStorage;
807
808 return PDMR3AsyncCompletionEpSetSize(pStorageBackend->pEndpoint, cbSize);
809}
810
811static DECLCALLBACK(int) drvvdAsyncIOSetAllocationSize(void *pvUser, void *pvStorage, uint64_t cbSize, uint32_t fFlags)
812{
813 RT_NOREF(pvUser, pvStorage, cbSize, fFlags);
814 return VERR_NOT_SUPPORTED;
815}
816
817#endif /* VBOX_WITH_PDM_ASYNC_COMPLETION */
818
819
820/*********************************************************************************************************************************
821* VD Thread Synchronization interface implementation *
822*********************************************************************************************************************************/
823
824static DECLCALLBACK(int) drvvdThreadStartRead(void *pvUser)
825{
826 PVBOXDISK pThis = (PVBOXDISK)pvUser;
827
828 return RTSemRWRequestRead(pThis->MergeLock, RT_INDEFINITE_WAIT);
829}
830
831static DECLCALLBACK(int) drvvdThreadFinishRead(void *pvUser)
832{
833 PVBOXDISK pThis = (PVBOXDISK)pvUser;
834
835 return RTSemRWReleaseRead(pThis->MergeLock);
836}
837
838static DECLCALLBACK(int) drvvdThreadStartWrite(void *pvUser)
839{
840 PVBOXDISK pThis = (PVBOXDISK)pvUser;
841
842 return RTSemRWRequestWrite(pThis->MergeLock, RT_INDEFINITE_WAIT);
843}
844
845static DECLCALLBACK(int) drvvdThreadFinishWrite(void *pvUser)
846{
847 PVBOXDISK pThis = (PVBOXDISK)pvUser;
848
849 return RTSemRWReleaseWrite(pThis->MergeLock);
850}
851
852
853/*********************************************************************************************************************************
854* VD Configuration interface implementation *
855*********************************************************************************************************************************/
856
857static DECLCALLBACK(bool) drvvdCfgAreKeysValid(void *pvUser, const char *pszzValid)
858{
859 return CFGMR3AreValuesValid((PCFGMNODE)pvUser, pszzValid);
860}
861
862static DECLCALLBACK(int) drvvdCfgQuerySize(void *pvUser, const char *pszName, size_t *pcb)
863{
864 return CFGMR3QuerySize((PCFGMNODE)pvUser, pszName, pcb);
865}
866
867static DECLCALLBACK(int) drvvdCfgQuery(void *pvUser, const char *pszName, char *pszString, size_t cchString)
868{
869 return CFGMR3QueryString((PCFGMNODE)pvUser, pszName, pszString, cchString);
870}
871
872static DECLCALLBACK(int) drvvdCfgQueryBytes(void *pvUser, const char *pszName, void *ppvData, size_t cbData)
873{
874 return CFGMR3QueryBytes((PCFGMNODE)pvUser, pszName, ppvData, cbData);
875}
876
877
878/*******************************************************************************
879* VD Crypto interface implementation for the encryption support *
880*******************************************************************************/
881
882static DECLCALLBACK(int) drvvdCryptoKeyRetain(void *pvUser, const char *pszId, const uint8_t **ppbKey, size_t *pcbKey)
883{
884 PVBOXDISK pThis = (PVBOXDISK)pvUser;
885 int rc = VINF_SUCCESS;
886
887 AssertPtr(pThis->pIfSecKey);
888 if (pThis->pIfSecKey)
889 rc = pThis->pIfSecKey->pfnKeyRetain(pThis->pIfSecKey, pszId, ppbKey, pcbKey);
890 else
891 rc = VERR_NOT_SUPPORTED;
892
893 return rc;
894}
895
896static DECLCALLBACK(int) drvvdCryptoKeyRelease(void *pvUser, const char *pszId)
897{
898 PVBOXDISK pThis = (PVBOXDISK)pvUser;
899 int rc = VINF_SUCCESS;
900
901 AssertPtr(pThis->pIfSecKey);
902 if (pThis->pIfSecKey)
903 rc = pThis->pIfSecKey->pfnKeyRelease(pThis->pIfSecKey, pszId);
904 else
905 rc = VERR_NOT_SUPPORTED;
906
907 return rc;
908}
909
910static DECLCALLBACK(int) drvvdCryptoKeyStorePasswordRetain(void *pvUser, const char *pszId, const char **ppszPassword)
911{
912 PVBOXDISK pThis = (PVBOXDISK)pvUser;
913 int rc = VINF_SUCCESS;
914
915 AssertPtr(pThis->pIfSecKey);
916 if (pThis->pIfSecKey)
917 rc = pThis->pIfSecKey->pfnPasswordRetain(pThis->pIfSecKey, pszId, ppszPassword);
918 else
919 rc = VERR_NOT_SUPPORTED;
920
921 return rc;
922}
923
924static DECLCALLBACK(int) drvvdCryptoKeyStorePasswordRelease(void *pvUser, const char *pszId)
925{
926 PVBOXDISK pThis = (PVBOXDISK)pvUser;
927 int rc = VINF_SUCCESS;
928
929 AssertPtr(pThis->pIfSecKey);
930 if (pThis->pIfSecKey)
931 rc = pThis->pIfSecKey->pfnPasswordRelease(pThis->pIfSecKey, pszId);
932 else
933 rc = VERR_NOT_SUPPORTED;
934
935 return rc;
936}
937
938#ifdef VBOX_WITH_INIP
939
940
941/*********************************************************************************************************************************
942* VD TCP network stack interface implementation - INIP case *
943*********************************************************************************************************************************/
944
945/**
946 * vvl: this structure duplicate meaning of sockaddr,
947 * perhaps it'd be better to get rid of it.
948 */
949typedef union INIPSOCKADDRUNION
950{
951 struct sockaddr Addr;
952 struct sockaddr_in Ipv4;
953#if LWIP_IPV6
954 struct sockaddr_in6 Ipv6;
955#endif
956} INIPSOCKADDRUNION;
957
958typedef struct INIPSOCKET
959{
960 int hSock;
961} INIPSOCKET, *PINIPSOCKET;
962
963static DECLCALLBACK(int) drvvdINIPFlush(VDSOCKET Sock);
964
965/** @interface_method_impl{VDINTERFACETCPNET,pfnSocketCreate} */
966static DECLCALLBACK(int) drvvdINIPSocketCreate(uint32_t fFlags, PVDSOCKET pSock)
967{
968 PINIPSOCKET pSocketInt = NULL;
969
970 /*
971 * The extended select method is not supported because it is impossible to wakeup
972 * the thread.
973 */
974 if (fFlags & VD_INTERFACETCPNET_CONNECT_EXTENDED_SELECT)
975 return VERR_NOT_SUPPORTED;
976
977 pSocketInt = (PINIPSOCKET)RTMemAllocZ(sizeof(INIPSOCKET));
978 if (pSocketInt)
979 {
980 pSocketInt->hSock = INT32_MAX;
981 *pSock = (VDSOCKET)pSocketInt;
982 return VINF_SUCCESS;
983 }
984
985 return VERR_NO_MEMORY;
986}
987
988/** @interface_method_impl{VDINTERFACETCPNET,pfnSocketCreate} */
989static DECLCALLBACK(int) drvvdINIPSocketDestroy(VDSOCKET Sock)
990{
991 PINIPSOCKET pSocketInt = (PINIPSOCKET)Sock;
992
993 RTMemFree(pSocketInt);
994 return VINF_SUCCESS;
995}
996
997/** @interface_method_impl{VDINTERFACETCPNET,pfnClientConnect} */
998static DECLCALLBACK(int) drvvdINIPClientConnect(VDSOCKET Sock, const char *pszAddress, uint32_t uPort,
999 RTMSINTERVAL cMillies)
1000{
1001 int rc = VINF_SUCCESS;
1002 PINIPSOCKET pSocketInt = (PINIPSOCKET)Sock;
1003 int iInetFamily = PF_INET;
1004 struct in_addr ip;
1005#if LWIP_IPV6
1006 ip6_addr_t ip6;
1007 RT_ZERO(ip6);
1008#endif
1009
1010 NOREF(cMillies); /* LwIP doesn't support connect timeout. */
1011 RT_ZERO(ip); /* Shut up MSC. */
1012
1013 /* Check whether lwIP is set up in this VM instance. */
1014 if (!DevINIPConfigured())
1015 {
1016 LogRelFunc(("no IP stack\n"));
1017 return VERR_NET_HOST_UNREACHABLE;
1018 }
1019 /* Resolve hostname. As there is no standard resolver for lwIP yet,
1020 * just accept numeric IP addresses for now. */
1021#if LWIP_IPV6
1022 if (inet6_aton(pszAddress, &ip6))
1023 iInetFamily = PF_INET6;
1024 else /* concatination with if */
1025#endif
1026 if (!lwip_inet_aton(pszAddress, &ip))
1027 {
1028 LogRelFunc(("cannot resolve IP %s\n", pszAddress));
1029 return VERR_NET_HOST_UNREACHABLE;
1030 }
1031 /* Create socket and connect. */
1032 int iSock = lwip_socket(iInetFamily, SOCK_STREAM, 0);
1033 if (iSock != -1)
1034 {
1035 struct sockaddr *pSockAddr = NULL;
1036 struct sockaddr_in InAddr = {0};
1037#if LWIP_IPV6
1038 struct sockaddr_in6 In6Addr = {0};
1039#endif
1040 if (iInetFamily == PF_INET)
1041 {
1042 InAddr.sin_family = AF_INET;
1043 InAddr.sin_port = htons(uPort);
1044 InAddr.sin_addr = ip;
1045 InAddr.sin_len = sizeof(InAddr);
1046 pSockAddr = (struct sockaddr *)&InAddr;
1047 }
1048#if LWIP_IPV6
1049 else
1050 {
1051 In6Addr.sin6_family = AF_INET6;
1052 In6Addr.sin6_port = htons(uPort);
1053 memcpy(&In6Addr.sin6_addr, &ip6, sizeof(ip6));
1054 In6Addr.sin6_len = sizeof(In6Addr);
1055 pSockAddr = (struct sockaddr *)&In6Addr;
1056 }
1057#endif
1058 if ( pSockAddr
1059 && !lwip_connect(iSock, pSockAddr, pSockAddr->sa_len))
1060 {
1061 pSocketInt->hSock = iSock;
1062 return VINF_SUCCESS;
1063 }
1064 rc = VERR_NET_CONNECTION_REFUSED; /** @todo real solution needed */
1065 lwip_close(iSock);
1066 }
1067 else
1068 rc = VERR_NET_CONNECTION_REFUSED; /** @todo real solution needed */
1069 return rc;
1070}
1071
1072/** @interface_method_impl{VDINTERFACETCPNET,pfnClientClose} */
1073static DECLCALLBACK(int) drvvdINIPClientClose(VDSOCKET Sock)
1074{
1075 PINIPSOCKET pSocketInt = (PINIPSOCKET)Sock;
1076
1077 lwip_close(pSocketInt->hSock);
1078 pSocketInt->hSock = INT32_MAX;
1079 return VINF_SUCCESS; /** @todo real solution needed */
1080}
1081
1082/** @interface_method_impl{VDINTERFACETCPNET,pfnIsClientConnected} */
1083static DECLCALLBACK(bool) drvvdINIPIsClientConnected(VDSOCKET Sock)
1084{
1085 PINIPSOCKET pSocketInt = (PINIPSOCKET)Sock;
1086
1087 return pSocketInt->hSock != INT32_MAX;
1088}
1089
1090/** @interface_method_impl{VDINTERFACETCPNET,pfnSelectOne} */
1091static DECLCALLBACK(int) drvvdINIPSelectOne(VDSOCKET Sock, RTMSINTERVAL cMillies)
1092{
1093 PINIPSOCKET pSocketInt = (PINIPSOCKET)Sock;
1094 fd_set fdsetR;
1095 FD_ZERO(&fdsetR);
1096 FD_SET((uintptr_t)pSocketInt->hSock, &fdsetR);
1097 fd_set fdsetE = fdsetR;
1098
1099 int rc;
1100 if (cMillies == RT_INDEFINITE_WAIT)
1101 rc = lwip_select(pSocketInt->hSock + 1, &fdsetR, NULL, &fdsetE, NULL);
1102 else
1103 {
1104 struct timeval timeout;
1105 timeout.tv_sec = cMillies / 1000;
1106 timeout.tv_usec = (cMillies % 1000) * 1000;
1107 rc = lwip_select(pSocketInt->hSock + 1, &fdsetR, NULL, &fdsetE, &timeout);
1108 }
1109 if (rc > 0)
1110 return VINF_SUCCESS;
1111 if (rc == 0)
1112 return VERR_TIMEOUT;
1113 return VERR_NET_CONNECTION_REFUSED; /** @todo real solution needed */
1114}
1115
1116/** @interface_method_impl{VDINTERFACETCPNET,pfnRead} */
1117static DECLCALLBACK(int) drvvdINIPRead(VDSOCKET Sock, void *pvBuffer, size_t cbBuffer, size_t *pcbRead)
1118{
1119 PINIPSOCKET pSocketInt = (PINIPSOCKET)Sock;
1120
1121 /* Do params checking */
1122 if (!pvBuffer || !cbBuffer)
1123 {
1124 AssertMsgFailed(("Invalid params\n"));
1125 return VERR_INVALID_PARAMETER;
1126 }
1127
1128 /*
1129 * Read loop.
1130 * If pcbRead is NULL we have to fill the entire buffer!
1131 */
1132 size_t cbRead = 0;
1133 size_t cbToRead = cbBuffer;
1134 for (;;)
1135 {
1136 /** @todo this clipping here is just in case (the send function
1137 * needed it, so I added it here, too). Didn't investigate if this
1138 * really has issues. Better be safe than sorry. */
1139 ssize_t cbBytesRead = lwip_recv(pSocketInt->hSock, (char *)pvBuffer + cbRead,
1140 RT_MIN(cbToRead, 32768), 0);
1141 if (cbBytesRead < 0)
1142 return VERR_NET_CONNECTION_REFUSED; /** @todo real solution */
1143 if (cbBytesRead == 0 && errno) /** @todo r=bird: lwip_recv will not touch errno on Windows. This may apply to other hosts as well */
1144 return VERR_NET_CONNECTION_REFUSED; /** @todo real solution */
1145 if (pcbRead)
1146 {
1147 /* return partial data */
1148 *pcbRead = cbBytesRead;
1149 break;
1150 }
1151
1152 /* read more? */
1153 cbRead += cbBytesRead;
1154 if (cbRead == cbBuffer)
1155 break;
1156
1157 /* next */
1158 cbToRead = cbBuffer - cbRead;
1159 }
1160
1161 return VINF_SUCCESS;
1162}
1163
1164/** @interface_method_impl{VDINTERFACETCPNET,pfnWrite} */
1165static DECLCALLBACK(int) drvvdINIPWrite(VDSOCKET Sock, const void *pvBuffer, size_t cbBuffer)
1166{
1167 PINIPSOCKET pSocketInt = (PINIPSOCKET)Sock;
1168
1169 do
1170 {
1171 /** @todo lwip send only supports up to 65535 bytes in a single
1172 * send (stupid limitation buried in the code), so make sure we
1173 * don't get any wraparounds. This should be moved to DevINIP
1174 * stack interface once that's implemented. */
1175 ssize_t cbWritten = lwip_send(pSocketInt->hSock, (void *)pvBuffer,
1176 RT_MIN(cbBuffer, 32768), 0);
1177 if (cbWritten < 0)
1178 return VERR_NET_CONNECTION_REFUSED; /** @todo real solution needed */
1179 AssertMsg(cbBuffer >= (size_t)cbWritten, ("Wrote more than we requested!!! cbWritten=%d cbBuffer=%d\n",
1180 cbWritten, cbBuffer));
1181 cbBuffer -= cbWritten;
1182 pvBuffer = (const char *)pvBuffer + cbWritten;
1183 } while (cbBuffer);
1184
1185 return VINF_SUCCESS;
1186}
1187
1188/** @interface_method_impl{VDINTERFACETCPNET,pfnSgWrite} */
1189static DECLCALLBACK(int) drvvdINIPSgWrite(VDSOCKET Sock, PCRTSGBUF pSgBuf)
1190{
1191 int rc = VINF_SUCCESS;
1192
1193 /* This is an extremely crude emulation, however it's good enough
1194 * for our iSCSI code. INIP has no sendmsg(). */
1195 for (unsigned i = 0; i < pSgBuf->cSegs; i++)
1196 {
1197 rc = drvvdINIPWrite(Sock, pSgBuf->paSegs[i].pvSeg,
1198 pSgBuf->paSegs[i].cbSeg);
1199 if (RT_FAILURE(rc))
1200 break;
1201 }
1202 if (RT_SUCCESS(rc))
1203 drvvdINIPFlush(Sock);
1204
1205 return rc;
1206}
1207
1208/** @interface_method_impl{VDINTERFACETCPNET,pfnFlush} */
1209static DECLCALLBACK(int) drvvdINIPFlush(VDSOCKET Sock)
1210{
1211 PINIPSOCKET pSocketInt = (PINIPSOCKET)Sock;
1212
1213 int fFlag = 1;
1214 lwip_setsockopt(pSocketInt->hSock, IPPROTO_TCP, TCP_NODELAY,
1215 (const char *)&fFlag, sizeof(fFlag));
1216 fFlag = 0;
1217 lwip_setsockopt(pSocketInt->hSock, IPPROTO_TCP, TCP_NODELAY,
1218 (const char *)&fFlag, sizeof(fFlag));
1219 return VINF_SUCCESS;
1220}
1221
1222/** @interface_method_impl{VDINTERFACETCPNET,pfnSetSendCoalescing} */
1223static DECLCALLBACK(int) drvvdINIPSetSendCoalescing(VDSOCKET Sock, bool fEnable)
1224{
1225 PINIPSOCKET pSocketInt = (PINIPSOCKET)Sock;
1226
1227 int fFlag = fEnable ? 0 : 1;
1228 lwip_setsockopt(pSocketInt->hSock, IPPROTO_TCP, TCP_NODELAY,
1229 (const char *)&fFlag, sizeof(fFlag));
1230 return VINF_SUCCESS;
1231}
1232
1233/** @interface_method_impl{VDINTERFACETCPNET,pfnGetLocalAddress} */
1234static DECLCALLBACK(int) drvvdINIPGetLocalAddress(VDSOCKET Sock, PRTNETADDR pAddr)
1235{
1236 PINIPSOCKET pSocketInt = (PINIPSOCKET)Sock;
1237 INIPSOCKADDRUNION u;
1238 socklen_t cbAddr = sizeof(u);
1239 RT_ZERO(u);
1240 if (!lwip_getsockname(pSocketInt->hSock, &u.Addr, &cbAddr))
1241 {
1242 /*
1243 * Convert the address.
1244 */
1245 if ( cbAddr == sizeof(struct sockaddr_in)
1246 && u.Addr.sa_family == AF_INET)
1247 {
1248 RT_ZERO(*pAddr);
1249 pAddr->enmType = RTNETADDRTYPE_IPV4;
1250 pAddr->uPort = RT_N2H_U16(u.Ipv4.sin_port);
1251 pAddr->uAddr.IPv4.u = u.Ipv4.sin_addr.s_addr;
1252 }
1253#if LWIP_IPV6
1254 else if ( cbAddr == sizeof(struct sockaddr_in6)
1255 && u.Addr.sa_family == AF_INET6)
1256 {
1257 RT_ZERO(*pAddr);
1258 pAddr->enmType = RTNETADDRTYPE_IPV6;
1259 pAddr->uPort = RT_N2H_U16(u.Ipv6.sin6_port);
1260 memcpy(&pAddr->uAddr.IPv6, &u.Ipv6.sin6_addr, sizeof(RTNETADDRIPV6));
1261 }
1262#endif
1263 else
1264 return VERR_NET_ADDRESS_FAMILY_NOT_SUPPORTED;
1265 return VINF_SUCCESS;
1266 }
1267 return VERR_NET_OPERATION_NOT_SUPPORTED;
1268}
1269
1270/** @interface_method_impl{VDINTERFACETCPNET,pfnGetPeerAddress} */
1271static DECLCALLBACK(int) drvvdINIPGetPeerAddress(VDSOCKET Sock, PRTNETADDR pAddr)
1272{
1273 PINIPSOCKET pSocketInt = (PINIPSOCKET)Sock;
1274 INIPSOCKADDRUNION u;
1275 socklen_t cbAddr = sizeof(u);
1276 RT_ZERO(u);
1277 if (!lwip_getpeername(pSocketInt->hSock, &u.Addr, &cbAddr))
1278 {
1279 /*
1280 * Convert the address.
1281 */
1282 if ( cbAddr == sizeof(struct sockaddr_in)
1283 && u.Addr.sa_family == AF_INET)
1284 {
1285 RT_ZERO(*pAddr);
1286 pAddr->enmType = RTNETADDRTYPE_IPV4;
1287 pAddr->uPort = RT_N2H_U16(u.Ipv4.sin_port);
1288 pAddr->uAddr.IPv4.u = u.Ipv4.sin_addr.s_addr;
1289 }
1290#if LWIP_IPV6
1291 else if ( cbAddr == sizeof(struct sockaddr_in6)
1292 && u.Addr.sa_family == AF_INET6)
1293 {
1294 RT_ZERO(*pAddr);
1295 pAddr->enmType = RTNETADDRTYPE_IPV6;
1296 pAddr->uPort = RT_N2H_U16(u.Ipv6.sin6_port);
1297 memcpy(&pAddr->uAddr.IPv6, &u.Ipv6.sin6_addr, sizeof(RTNETADDRIPV6));
1298 }
1299#endif
1300 else
1301 return VERR_NET_ADDRESS_FAMILY_NOT_SUPPORTED;
1302 return VINF_SUCCESS;
1303 }
1304 return VERR_NET_OPERATION_NOT_SUPPORTED;
1305}
1306
1307/** @interface_method_impl{VDINTERFACETCPNET,pfnSelectOneEx} */
1308static DECLCALLBACK(int) drvvdINIPSelectOneEx(VDSOCKET Sock, uint32_t fEvents, uint32_t *pfEvents, RTMSINTERVAL cMillies)
1309{
1310 RT_NOREF(Sock, fEvents, pfEvents, cMillies);
1311 AssertMsgFailed(("Not supported!\n"));
1312 return VERR_NOT_SUPPORTED;
1313}
1314
1315/** @interface_method_impl{VDINTERFACETCPNET,pfnPoke} */
1316static DECLCALLBACK(int) drvvdINIPPoke(VDSOCKET Sock)
1317{
1318 RT_NOREF(Sock);
1319 AssertMsgFailed(("Not supported!\n"));
1320 return VERR_NOT_SUPPORTED;
1321}
1322
1323#endif /* VBOX_WITH_INIP */
1324
1325
1326/*********************************************************************************************************************************
1327* VD TCP network stack interface implementation - Host TCP case *
1328*********************************************************************************************************************************/
1329
1330/**
1331 * Socket data.
1332 */
1333typedef struct VDSOCKETINT
1334{
1335 /** IPRT socket handle. */
1336 RTSOCKET hSocket;
1337 /** Pollset with the wakeup pipe and socket. */
1338 RTPOLLSET hPollSet;
1339 /** Pipe endpoint - read (in the pollset). */
1340 RTPIPE hPipeR;
1341 /** Pipe endpoint - write. */
1342 RTPIPE hPipeW;
1343 /** Flag whether the thread was woken up. */
1344 volatile bool fWokenUp;
1345 /** Flag whether the thread is waiting in the select call. */
1346 volatile bool fWaiting;
1347 /** Old event mask. */
1348 uint32_t fEventsOld;
1349} VDSOCKETINT, *PVDSOCKETINT;
1350
1351/** Pollset id of the socket. */
1352#define VDSOCKET_POLL_ID_SOCKET 0
1353/** Pollset id of the pipe. */
1354#define VDSOCKET_POLL_ID_PIPE 1
1355
1356/** @interface_method_impl{VDINTERFACETCPNET,pfnSocketCreate} */
1357static DECLCALLBACK(int) drvvdTcpSocketCreate(uint32_t fFlags, PVDSOCKET pSock)
1358{
1359 int rc = VINF_SUCCESS;
1360 int rc2 = VINF_SUCCESS;
1361 PVDSOCKETINT pSockInt = NULL;
1362
1363 pSockInt = (PVDSOCKETINT)RTMemAllocZ(sizeof(VDSOCKETINT));
1364 if (!pSockInt)
1365 return VERR_NO_MEMORY;
1366
1367 pSockInt->hSocket = NIL_RTSOCKET;
1368 pSockInt->hPollSet = NIL_RTPOLLSET;
1369 pSockInt->hPipeR = NIL_RTPIPE;
1370 pSockInt->hPipeW = NIL_RTPIPE;
1371 pSockInt->fWokenUp = false;
1372 pSockInt->fWaiting = false;
1373
1374 if (fFlags & VD_INTERFACETCPNET_CONNECT_EXTENDED_SELECT)
1375 {
1376 /* Init pipe and pollset. */
1377 rc = RTPipeCreate(&pSockInt->hPipeR, &pSockInt->hPipeW, 0);
1378 if (RT_SUCCESS(rc))
1379 {
1380 rc = RTPollSetCreate(&pSockInt->hPollSet);
1381 if (RT_SUCCESS(rc))
1382 {
1383 rc = RTPollSetAddPipe(pSockInt->hPollSet, pSockInt->hPipeR,
1384 RTPOLL_EVT_READ, VDSOCKET_POLL_ID_PIPE);
1385 if (RT_SUCCESS(rc))
1386 {
1387 *pSock = pSockInt;
1388 return VINF_SUCCESS;
1389 }
1390
1391 RTPollSetRemove(pSockInt->hPollSet, VDSOCKET_POLL_ID_PIPE);
1392 rc2 = RTPollSetDestroy(pSockInt->hPollSet);
1393 AssertRC(rc2);
1394 }
1395
1396 rc2 = RTPipeClose(pSockInt->hPipeR);
1397 AssertRC(rc2);
1398 rc2 = RTPipeClose(pSockInt->hPipeW);
1399 AssertRC(rc2);
1400 }
1401 }
1402 else
1403 {
1404 *pSock = pSockInt;
1405 return VINF_SUCCESS;
1406 }
1407
1408 RTMemFree(pSockInt);
1409
1410 return rc;
1411}
1412
1413/** @interface_method_impl{VDINTERFACETCPNET,pfnSocketDestroy} */
1414static DECLCALLBACK(int) drvvdTcpSocketDestroy(VDSOCKET Sock)
1415{
1416 int rc = VINF_SUCCESS;
1417 PVDSOCKETINT pSockInt = (PVDSOCKETINT)Sock;
1418
1419 /* Destroy the pipe and pollset if necessary. */
1420 if (pSockInt->hPollSet != NIL_RTPOLLSET)
1421 {
1422 if (pSockInt->hSocket != NIL_RTSOCKET)
1423 {
1424 rc = RTPollSetRemove(pSockInt->hPollSet, VDSOCKET_POLL_ID_SOCKET);
1425 Assert(RT_SUCCESS(rc) || rc == VERR_POLL_HANDLE_ID_NOT_FOUND);
1426 }
1427 rc = RTPollSetRemove(pSockInt->hPollSet, VDSOCKET_POLL_ID_PIPE);
1428 AssertRC(rc);
1429 rc = RTPollSetDestroy(pSockInt->hPollSet);
1430 AssertRC(rc);
1431 rc = RTPipeClose(pSockInt->hPipeR);
1432 AssertRC(rc);
1433 rc = RTPipeClose(pSockInt->hPipeW);
1434 AssertRC(rc);
1435 }
1436
1437 if (pSockInt->hSocket != NIL_RTSOCKET)
1438 rc = RTTcpClientCloseEx(pSockInt->hSocket, false /*fGracefulShutdown*/);
1439
1440 RTMemFree(pSockInt);
1441
1442 return rc;
1443}
1444
1445/** @interface_method_impl{VDINTERFACETCPNET,pfnClientConnect} */
1446static DECLCALLBACK(int) drvvdTcpClientConnect(VDSOCKET Sock, const char *pszAddress, uint32_t uPort,
1447 RTMSINTERVAL cMillies)
1448{
1449 int rc = VINF_SUCCESS;
1450 PVDSOCKETINT pSockInt = (PVDSOCKETINT)Sock;
1451
1452 rc = RTTcpClientConnectEx(pszAddress, uPort, &pSockInt->hSocket, cMillies, NULL);
1453 if (RT_SUCCESS(rc))
1454 {
1455 /* Add to the pollset if required. */
1456 if (pSockInt->hPollSet != NIL_RTPOLLSET)
1457 {
1458 pSockInt->fEventsOld = RTPOLL_EVT_READ | RTPOLL_EVT_WRITE | RTPOLL_EVT_ERROR;
1459
1460 rc = RTPollSetAddSocket(pSockInt->hPollSet, pSockInt->hSocket,
1461 pSockInt->fEventsOld, VDSOCKET_POLL_ID_SOCKET);
1462 }
1463
1464 if (RT_SUCCESS(rc))
1465 return VINF_SUCCESS;
1466
1467 rc = RTTcpClientCloseEx(pSockInt->hSocket, false /*fGracefulShutdown*/);
1468 }
1469
1470 return rc;
1471}
1472
1473/** @interface_method_impl{VDINTERFACETCPNET,pfnClientClose} */
1474static DECLCALLBACK(int) drvvdTcpClientClose(VDSOCKET Sock)
1475{
1476 int rc = VINF_SUCCESS;
1477 PVDSOCKETINT pSockInt = (PVDSOCKETINT)Sock;
1478
1479 if (pSockInt->hPollSet != NIL_RTPOLLSET)
1480 {
1481 rc = RTPollSetRemove(pSockInt->hPollSet, VDSOCKET_POLL_ID_SOCKET);
1482 AssertRC(rc);
1483 }
1484
1485 rc = RTTcpClientCloseEx(pSockInt->hSocket, false /*fGracefulShutdown*/);
1486 pSockInt->hSocket = NIL_RTSOCKET;
1487
1488 return rc;
1489}
1490
1491/** @interface_method_impl{VDINTERFACETCPNET,pfnIsClientConnected} */
1492static DECLCALLBACK(bool) drvvdTcpIsClientConnected(VDSOCKET Sock)
1493{
1494 PVDSOCKETINT pSockInt = (PVDSOCKETINT)Sock;
1495
1496 return pSockInt->hSocket != NIL_RTSOCKET;
1497}
1498
1499/** @interface_method_impl{VDINTERFACETCPNET,pfnSelectOne} */
1500static DECLCALLBACK(int) drvvdTcpSelectOne(VDSOCKET Sock, RTMSINTERVAL cMillies)
1501{
1502 PVDSOCKETINT pSockInt = (PVDSOCKETINT)Sock;
1503
1504 return RTTcpSelectOne(pSockInt->hSocket, cMillies);
1505}
1506
1507/** @interface_method_impl{VDINTERFACETCPNET,pfnRead} */
1508static DECLCALLBACK(int) drvvdTcpRead(VDSOCKET Sock, void *pvBuffer, size_t cbBuffer, size_t *pcbRead)
1509{
1510 PVDSOCKETINT pSockInt = (PVDSOCKETINT)Sock;
1511
1512 return RTTcpRead(pSockInt->hSocket, pvBuffer, cbBuffer, pcbRead);
1513}
1514
1515/** @interface_method_impl{VDINTERFACETCPNET,pfnWrite} */
1516static DECLCALLBACK(int) drvvdTcpWrite(VDSOCKET Sock, const void *pvBuffer, size_t cbBuffer)
1517{
1518 PVDSOCKETINT pSockInt = (PVDSOCKETINT)Sock;
1519
1520 return RTTcpWrite(pSockInt->hSocket, pvBuffer, cbBuffer);
1521}
1522
1523/** @interface_method_impl{VDINTERFACETCPNET,pfnSgWrite} */
1524static DECLCALLBACK(int) drvvdTcpSgWrite(VDSOCKET Sock, PCRTSGBUF pSgBuf)
1525{
1526 PVDSOCKETINT pSockInt = (PVDSOCKETINT)Sock;
1527
1528 return RTTcpSgWrite(pSockInt->hSocket, pSgBuf);
1529}
1530
1531/** @interface_method_impl{VDINTERFACETCPNET,pfnReadNB} */
1532static DECLCALLBACK(int) drvvdTcpReadNB(VDSOCKET Sock, void *pvBuffer, size_t cbBuffer, size_t *pcbRead)
1533{
1534 PVDSOCKETINT pSockInt = (PVDSOCKETINT)Sock;
1535
1536 return RTTcpReadNB(pSockInt->hSocket, pvBuffer, cbBuffer, pcbRead);
1537}
1538
1539/** @interface_method_impl{VDINTERFACETCPNET,pfnWriteNB} */
1540static DECLCALLBACK(int) drvvdTcpWriteNB(VDSOCKET Sock, const void *pvBuffer, size_t cbBuffer, size_t *pcbWritten)
1541{
1542 PVDSOCKETINT pSockInt = (PVDSOCKETINT)Sock;
1543
1544 return RTTcpWriteNB(pSockInt->hSocket, pvBuffer, cbBuffer, pcbWritten);
1545}
1546
1547/** @interface_method_impl{VDINTERFACETCPNET,pfnSgWriteNB} */
1548static DECLCALLBACK(int) drvvdTcpSgWriteNB(VDSOCKET Sock, PRTSGBUF pSgBuf, size_t *pcbWritten)
1549{
1550 PVDSOCKETINT pSockInt = (PVDSOCKETINT)Sock;
1551
1552 return RTTcpSgWriteNB(pSockInt->hSocket, pSgBuf, pcbWritten);
1553}
1554
1555/** @interface_method_impl{VDINTERFACETCPNET,pfnFlush} */
1556static DECLCALLBACK(int) drvvdTcpFlush(VDSOCKET Sock)
1557{
1558 PVDSOCKETINT pSockInt = (PVDSOCKETINT)Sock;
1559
1560 return RTTcpFlush(pSockInt->hSocket);
1561}
1562
1563/** @interface_method_impl{VDINTERFACETCPNET,pfnSetSendCoalescing} */
1564static DECLCALLBACK(int) drvvdTcpSetSendCoalescing(VDSOCKET Sock, bool fEnable)
1565{
1566 PVDSOCKETINT pSockInt = (PVDSOCKETINT)Sock;
1567
1568 return RTTcpSetSendCoalescing(pSockInt->hSocket, fEnable);
1569}
1570
1571/** @interface_method_impl{VDINTERFACETCPNET,pfnGetLocalAddress} */
1572static DECLCALLBACK(int) drvvdTcpGetLocalAddress(VDSOCKET Sock, PRTNETADDR pAddr)
1573{
1574 PVDSOCKETINT pSockInt = (PVDSOCKETINT)Sock;
1575
1576 return RTTcpGetLocalAddress(pSockInt->hSocket, pAddr);
1577}
1578
1579/** @interface_method_impl{VDINTERFACETCPNET,pfnGetPeerAddress} */
1580static DECLCALLBACK(int) drvvdTcpGetPeerAddress(VDSOCKET Sock, PRTNETADDR pAddr)
1581{
1582 PVDSOCKETINT pSockInt = (PVDSOCKETINT)Sock;
1583
1584 return RTTcpGetPeerAddress(pSockInt->hSocket, pAddr);
1585}
1586
1587static DECLCALLBACK(int) drvvdTcpSelectOneExPoll(VDSOCKET Sock, uint32_t fEvents,
1588 uint32_t *pfEvents, RTMSINTERVAL cMillies)
1589{
1590 int rc = VINF_SUCCESS;
1591 uint32_t id = 0;
1592 uint32_t fEventsRecv = 0;
1593 PVDSOCKETINT pSockInt = (PVDSOCKETINT)Sock;
1594
1595 *pfEvents = 0;
1596
1597 if ( pSockInt->fEventsOld != fEvents
1598 && pSockInt->hSocket != NIL_RTSOCKET)
1599 {
1600 uint32_t fPollEvents = 0;
1601
1602 if (fEvents & VD_INTERFACETCPNET_EVT_READ)
1603 fPollEvents |= RTPOLL_EVT_READ;
1604 if (fEvents & VD_INTERFACETCPNET_EVT_WRITE)
1605 fPollEvents |= RTPOLL_EVT_WRITE;
1606 if (fEvents & VD_INTERFACETCPNET_EVT_ERROR)
1607 fPollEvents |= RTPOLL_EVT_ERROR;
1608
1609 rc = RTPollSetEventsChange(pSockInt->hPollSet, VDSOCKET_POLL_ID_SOCKET, fPollEvents);
1610 if (RT_FAILURE(rc))
1611 return rc;
1612
1613 pSockInt->fEventsOld = fEvents;
1614 }
1615
1616 ASMAtomicXchgBool(&pSockInt->fWaiting, true);
1617 if (ASMAtomicXchgBool(&pSockInt->fWokenUp, false))
1618 {
1619 ASMAtomicXchgBool(&pSockInt->fWaiting, false);
1620 return VERR_INTERRUPTED;
1621 }
1622
1623 rc = RTPoll(pSockInt->hPollSet, cMillies, &fEventsRecv, &id);
1624 Assert(RT_SUCCESS(rc) || rc == VERR_TIMEOUT);
1625
1626 ASMAtomicXchgBool(&pSockInt->fWaiting, false);
1627
1628 if (RT_SUCCESS(rc))
1629 {
1630 if (id == VDSOCKET_POLL_ID_SOCKET)
1631 {
1632 fEventsRecv &= RTPOLL_EVT_VALID_MASK;
1633
1634 if (fEventsRecv & RTPOLL_EVT_READ)
1635 *pfEvents |= VD_INTERFACETCPNET_EVT_READ;
1636 if (fEventsRecv & RTPOLL_EVT_WRITE)
1637 *pfEvents |= VD_INTERFACETCPNET_EVT_WRITE;
1638 if (fEventsRecv & RTPOLL_EVT_ERROR)
1639 *pfEvents |= VD_INTERFACETCPNET_EVT_ERROR;
1640 }
1641 else
1642 {
1643 size_t cbRead = 0;
1644 uint8_t abBuf[10];
1645 Assert(id == VDSOCKET_POLL_ID_PIPE);
1646 Assert((fEventsRecv & RTPOLL_EVT_VALID_MASK) == RTPOLL_EVT_READ);
1647
1648 /* We got interrupted, drain the pipe. */
1649 rc = RTPipeRead(pSockInt->hPipeR, abBuf, sizeof(abBuf), &cbRead);
1650 AssertRC(rc);
1651
1652 ASMAtomicXchgBool(&pSockInt->fWokenUp, false);
1653
1654 rc = VERR_INTERRUPTED;
1655 }
1656 }
1657
1658 return rc;
1659}
1660
1661/** @interface_method_impl{VDINTERFACETCPNET,pfnSelectOneEx} */
1662static DECLCALLBACK(int) drvvdTcpSelectOneExNoPoll(VDSOCKET Sock, uint32_t fEvents, uint32_t *pfEvents, RTMSINTERVAL cMillies)
1663{
1664 RT_NOREF(cMillies); /** @todo timeouts */
1665 int rc = VINF_SUCCESS;
1666 PVDSOCKETINT pSockInt = (PVDSOCKETINT)Sock;
1667
1668 *pfEvents = 0;
1669
1670 ASMAtomicXchgBool(&pSockInt->fWaiting, true);
1671 if (ASMAtomicXchgBool(&pSockInt->fWokenUp, false))
1672 {
1673 ASMAtomicXchgBool(&pSockInt->fWaiting, false);
1674 return VERR_INTERRUPTED;
1675 }
1676
1677 if ( pSockInt->hSocket == NIL_RTSOCKET
1678 || !fEvents)
1679 {
1680 /*
1681 * Only the pipe is configured or the caller doesn't wait for a socket event,
1682 * wait until there is something to read from the pipe.
1683 */
1684 size_t cbRead = 0;
1685 char ch = 0;
1686 rc = RTPipeReadBlocking(pSockInt->hPipeR, &ch, 1, &cbRead);
1687 if (RT_SUCCESS(rc))
1688 {
1689 Assert(cbRead == 1);
1690 rc = VERR_INTERRUPTED;
1691 ASMAtomicXchgBool(&pSockInt->fWokenUp, false);
1692 }
1693 }
1694 else
1695 {
1696 uint32_t fSelectEvents = 0;
1697
1698 if (fEvents & VD_INTERFACETCPNET_EVT_READ)
1699 fSelectEvents |= RTSOCKET_EVT_READ;
1700 if (fEvents & VD_INTERFACETCPNET_EVT_WRITE)
1701 fSelectEvents |= RTSOCKET_EVT_WRITE;
1702 if (fEvents & VD_INTERFACETCPNET_EVT_ERROR)
1703 fSelectEvents |= RTSOCKET_EVT_ERROR;
1704
1705 if (fEvents & VD_INTERFACETCPNET_HINT_INTERRUPT)
1706 {
1707 uint32_t fEventsRecv = 0;
1708
1709 /* Make sure the socket is not in the pollset. */
1710 rc = RTPollSetRemove(pSockInt->hPollSet, VDSOCKET_POLL_ID_SOCKET);
1711 Assert(RT_SUCCESS(rc) || rc == VERR_POLL_HANDLE_ID_NOT_FOUND);
1712
1713 for (;;)
1714 {
1715 uint32_t id = 0;
1716 rc = RTPoll(pSockInt->hPollSet, 5, &fEvents, &id);
1717 if (rc == VERR_TIMEOUT)
1718 {
1719 /* Check the socket. */
1720 rc = RTTcpSelectOneEx(pSockInt->hSocket, fSelectEvents, &fEventsRecv, 0);
1721 if (RT_SUCCESS(rc))
1722 {
1723 if (fEventsRecv & RTSOCKET_EVT_READ)
1724 *pfEvents |= VD_INTERFACETCPNET_EVT_READ;
1725 if (fEventsRecv & RTSOCKET_EVT_WRITE)
1726 *pfEvents |= VD_INTERFACETCPNET_EVT_WRITE;
1727 if (fEventsRecv & RTSOCKET_EVT_ERROR)
1728 *pfEvents |= VD_INTERFACETCPNET_EVT_ERROR;
1729 break; /* Quit */
1730 }
1731 else if (rc != VERR_TIMEOUT)
1732 break;
1733 }
1734 else if (RT_SUCCESS(rc))
1735 {
1736 size_t cbRead = 0;
1737 uint8_t abBuf[10];
1738 Assert(id == VDSOCKET_POLL_ID_PIPE);
1739 Assert((fEventsRecv & RTPOLL_EVT_VALID_MASK) == RTPOLL_EVT_READ);
1740
1741 /* We got interrupted, drain the pipe. */
1742 rc = RTPipeRead(pSockInt->hPipeR, abBuf, sizeof(abBuf), &cbRead);
1743 AssertRC(rc);
1744
1745 ASMAtomicXchgBool(&pSockInt->fWokenUp, false);
1746
1747 rc = VERR_INTERRUPTED;
1748 break;
1749 }
1750 else
1751 break;
1752 }
1753 }
1754 else /* The caller waits for a socket event. */
1755 {
1756 uint32_t fEventsRecv = 0;
1757
1758 /* Loop until we got woken up or a socket event occurred. */
1759 for (;;)
1760 {
1761 /** @todo find an adaptive wait algorithm based on the
1762 * number of wakeups in the past. */
1763 rc = RTTcpSelectOneEx(pSockInt->hSocket, fSelectEvents, &fEventsRecv, 5);
1764 if (rc == VERR_TIMEOUT)
1765 {
1766 /* Check if there is an event pending. */
1767 size_t cbRead = 0;
1768 char ch = 0;
1769 rc = RTPipeRead(pSockInt->hPipeR, &ch, 1, &cbRead);
1770 if (RT_SUCCESS(rc) && rc != VINF_TRY_AGAIN)
1771 {
1772 Assert(cbRead == 1);
1773 rc = VERR_INTERRUPTED;
1774 ASMAtomicXchgBool(&pSockInt->fWokenUp, false);
1775 break; /* Quit */
1776 }
1777 else
1778 Assert(rc == VINF_TRY_AGAIN);
1779 }
1780 else if (RT_SUCCESS(rc))
1781 {
1782 if (fEventsRecv & RTSOCKET_EVT_READ)
1783 *pfEvents |= VD_INTERFACETCPNET_EVT_READ;
1784 if (fEventsRecv & RTSOCKET_EVT_WRITE)
1785 *pfEvents |= VD_INTERFACETCPNET_EVT_WRITE;
1786 if (fEventsRecv & RTSOCKET_EVT_ERROR)
1787 *pfEvents |= VD_INTERFACETCPNET_EVT_ERROR;
1788 break; /* Quit */
1789 }
1790 else
1791 break;
1792 }
1793 }
1794 }
1795
1796 ASMAtomicXchgBool(&pSockInt->fWaiting, false);
1797
1798 return rc;
1799}
1800
1801/** @interface_method_impl{VDINTERFACETCPNET,pfnPoke} */
1802static DECLCALLBACK(int) drvvdTcpPoke(VDSOCKET Sock)
1803{
1804 int rc = VINF_SUCCESS;
1805 size_t cbWritten = 0;
1806 PVDSOCKETINT pSockInt = (PVDSOCKETINT)Sock;
1807
1808 ASMAtomicXchgBool(&pSockInt->fWokenUp, true);
1809
1810 if (ASMAtomicReadBool(&pSockInt->fWaiting))
1811 {
1812 rc = RTPipeWrite(pSockInt->hPipeW, "", 1, &cbWritten);
1813 Assert(RT_SUCCESS(rc) || cbWritten == 0);
1814 }
1815
1816 return VINF_SUCCESS;
1817}
1818
1819/**
1820 * Checks the prerequisites for encrypted I/O.
1821 *
1822 * @returns VBox status code.
1823 * @param pThis The VD driver instance data.
1824 */
1825static int drvvdKeyCheckPrereqs(PVBOXDISK pThis)
1826{
1827 if ( pThis->pCfgCrypto
1828 && !pThis->pIfSecKey)
1829 {
1830 AssertPtr(pThis->pIfSecKeyHlp);
1831 pThis->pIfSecKeyHlp->pfnKeyMissingNotify(pThis->pIfSecKeyHlp);
1832
1833 int rc = PDMDrvHlpVMSetRuntimeError(pThis->pDrvIns, VMSETRTERR_FLAGS_SUSPEND | VMSETRTERR_FLAGS_NO_WAIT, "DrvVD_DEKMISSING",
1834 N_("VD: The DEK for this disk is missing"));
1835 AssertRC(rc);
1836 return VERR_VD_DEK_MISSING;
1837 }
1838
1839 return VINF_SUCCESS;
1840}
1841
1842
1843/*********************************************************************************************************************************
1844* Media interface methods *
1845*********************************************************************************************************************************/
1846
1847/** @interface_method_impl{PDMIMEDIA,pfnRead} */
1848static DECLCALLBACK(int) drvvdRead(PPDMIMEDIA pInterface,
1849 uint64_t off, void *pvBuf, size_t cbRead)
1850{
1851 int rc = VINF_SUCCESS;
1852
1853 LogFlowFunc(("off=%#llx pvBuf=%p cbRead=%d\n", off, pvBuf, cbRead));
1854 PVBOXDISK pThis = PDMIMEDIA_2_VBOXDISK(pInterface);
1855
1856 /*
1857 * Check the state.
1858 */
1859 if (!pThis->pDisk)
1860 {
1861 AssertMsgFailed(("Invalid state! Not mounted!\n"));
1862 return VERR_PDM_MEDIA_NOT_MOUNTED;
1863 }
1864
1865 rc = drvvdKeyCheckPrereqs(pThis);
1866 if (RT_FAILURE(rc))
1867 return rc;
1868
1869 if (!pThis->fBootAccelActive)
1870 rc = VDRead(pThis->pDisk, off, pvBuf, cbRead);
1871 else
1872 {
1873 /* Can we serve the request from the buffer? */
1874 if ( off >= pThis->offDisk
1875 && off - pThis->offDisk < pThis->cbDataValid)
1876 {
1877 size_t cbToCopy = RT_MIN(cbRead, pThis->offDisk + pThis->cbDataValid - off);
1878
1879 memcpy(pvBuf, pThis->pbData + (off - pThis->offDisk), cbToCopy);
1880 cbRead -= cbToCopy;
1881 off += cbToCopy;
1882 pvBuf = (char *)pvBuf + cbToCopy;
1883 }
1884
1885 if ( cbRead > 0
1886 && cbRead < pThis->cbBootAccelBuffer)
1887 {
1888 /* Increase request to the buffer size and read. */
1889 pThis->cbDataValid = RT_MIN(pThis->cbDisk - off, pThis->cbBootAccelBuffer);
1890 pThis->offDisk = off;
1891 rc = VDRead(pThis->pDisk, off, pThis->pbData, pThis->cbDataValid);
1892 if (RT_FAILURE(rc))
1893 pThis->cbDataValid = 0;
1894 else
1895 memcpy(pvBuf, pThis->pbData, cbRead);
1896 }
1897 else if (cbRead >= pThis->cbBootAccelBuffer)
1898 {
1899 pThis->fBootAccelActive = false; /* Deactiviate */
1900 }
1901 }
1902
1903 if (RT_SUCCESS(rc))
1904 Log2(("%s: off=%#llx pvBuf=%p cbRead=%d\n%.*Rhxd\n", __FUNCTION__,
1905 off, pvBuf, cbRead, cbRead, pvBuf));
1906 LogFlowFunc(("returns %Rrc\n", rc));
1907 return rc;
1908}
1909
1910/** @interface_method_impl{PDMIMEDIA,pfnRead} */
1911static DECLCALLBACK(int) drvvdReadPcBios(PPDMIMEDIA pInterface,
1912 uint64_t off, void *pvBuf, size_t cbRead)
1913{
1914 int rc = VINF_SUCCESS;
1915
1916 LogFlowFunc(("off=%#llx pvBuf=%p cbRead=%d\n", off, pvBuf, cbRead));
1917 PVBOXDISK pThis = PDMIMEDIA_2_VBOXDISK(pInterface);
1918
1919 /*
1920 * Check the state.
1921 */
1922 if (!pThis->pDisk)
1923 {
1924 AssertMsgFailed(("Invalid state! Not mounted!\n"));
1925 return VERR_PDM_MEDIA_NOT_MOUNTED;
1926 }
1927
1928 if ( pThis->pCfgCrypto
1929 && !pThis->pIfSecKey)
1930 return VERR_VD_DEK_MISSING;
1931
1932 if (!pThis->fBootAccelActive)
1933 rc = VDRead(pThis->pDisk, off, pvBuf, cbRead);
1934 else
1935 {
1936 /* Can we serve the request from the buffer? */
1937 if ( off >= pThis->offDisk
1938 && off - pThis->offDisk < pThis->cbDataValid)
1939 {
1940 size_t cbToCopy = RT_MIN(cbRead, pThis->offDisk + pThis->cbDataValid - off);
1941
1942 memcpy(pvBuf, pThis->pbData + (off - pThis->offDisk), cbToCopy);
1943 cbRead -= cbToCopy;
1944 off += cbToCopy;
1945 pvBuf = (char *)pvBuf + cbToCopy;
1946 }
1947
1948 if ( cbRead > 0
1949 && cbRead < pThis->cbBootAccelBuffer)
1950 {
1951 /* Increase request to the buffer size and read. */
1952 pThis->cbDataValid = RT_MIN(pThis->cbDisk - off, pThis->cbBootAccelBuffer);
1953 pThis->offDisk = off;
1954 rc = VDRead(pThis->pDisk, off, pThis->pbData, pThis->cbDataValid);
1955 if (RT_FAILURE(rc))
1956 pThis->cbDataValid = 0;
1957 else
1958 memcpy(pvBuf, pThis->pbData, cbRead);
1959 }
1960 else if (cbRead >= pThis->cbBootAccelBuffer)
1961 {
1962 pThis->fBootAccelActive = false; /* Deactiviate */
1963 }
1964 }
1965
1966 if (RT_SUCCESS(rc))
1967 Log2(("%s: off=%#llx pvBuf=%p cbRead=%d\n%.*Rhxd\n", __FUNCTION__,
1968 off, pvBuf, cbRead, cbRead, pvBuf));
1969 LogFlowFunc(("returns %Rrc\n", rc));
1970 return rc;
1971}
1972
1973
1974/** @interface_method_impl{PDMIMEDIA,pfnWrite} */
1975static DECLCALLBACK(int) drvvdWrite(PPDMIMEDIA pInterface,
1976 uint64_t off, const void *pvBuf,
1977 size_t cbWrite)
1978{
1979 LogFlowFunc(("off=%#llx pvBuf=%p cbWrite=%d\n", off, pvBuf, cbWrite));
1980 PVBOXDISK pThis = PDMIMEDIA_2_VBOXDISK(pInterface);
1981 Log2(("%s: off=%#llx pvBuf=%p cbWrite=%d\n%.*Rhxd\n", __FUNCTION__,
1982 off, pvBuf, cbWrite, cbWrite, pvBuf));
1983
1984 /*
1985 * Check the state.
1986 */
1987 if (!pThis->pDisk)
1988 {
1989 AssertMsgFailed(("Invalid state! Not mounted!\n"));
1990 return VERR_PDM_MEDIA_NOT_MOUNTED;
1991 }
1992
1993 /* Set an FTM checkpoint as this operation changes the state permanently. */
1994 PDMDrvHlpFTSetCheckpoint(pThis->pDrvIns, FTMCHECKPOINTTYPE_STORAGE);
1995
1996 int rc = drvvdKeyCheckPrereqs(pThis);
1997 if (RT_FAILURE(rc))
1998 return rc;
1999
2000 /* Invalidate any buffer if boot acceleration is enabled. */
2001 if (pThis->fBootAccelActive)
2002 {
2003 pThis->cbDataValid = 0;
2004 pThis->offDisk = 0;
2005 }
2006
2007 rc = VDWrite(pThis->pDisk, off, pvBuf, cbWrite);
2008#ifdef VBOX_PERIODIC_FLUSH
2009 if (pThis->cbFlushInterval)
2010 {
2011 pThis->cbDataWritten += (uint32_t)cbWrite;
2012 if (pThis->cbDataWritten > pThis->cbFlushInterval)
2013 {
2014 pThis->cbDataWritten = 0;
2015 VDFlush(pThis->pDisk);
2016 }
2017 }
2018#endif /* VBOX_PERIODIC_FLUSH */
2019
2020 LogFlowFunc(("returns %Rrc\n", rc));
2021 return rc;
2022}
2023
2024/** @interface_method_impl{PDMIMEDIA,pfnFlush} */
2025static DECLCALLBACK(int) drvvdFlush(PPDMIMEDIA pInterface)
2026{
2027 LogFlowFunc(("\n"));
2028 PVBOXDISK pThis = PDMIMEDIA_2_VBOXDISK(pInterface);
2029
2030 /*
2031 * Check the state.
2032 */
2033 if (!pThis->pDisk)
2034 {
2035 AssertMsgFailed(("Invalid state! Not mounted!\n"));
2036 return VERR_PDM_MEDIA_NOT_MOUNTED;
2037 }
2038
2039#ifdef VBOX_IGNORE_FLUSH
2040 if (pThis->fIgnoreFlush)
2041 return VINF_SUCCESS;
2042#endif /* VBOX_IGNORE_FLUSH */
2043
2044 int rc = VDFlush(pThis->pDisk);
2045 LogFlowFunc(("returns %Rrc\n", rc));
2046 return rc;
2047}
2048
2049/** @interface_method_impl{PDMIMEDIA,pfnMerge} */
2050static DECLCALLBACK(int) drvvdMerge(PPDMIMEDIA pInterface,
2051 PFNSIMPLEPROGRESS pfnProgress,
2052 void *pvUser)
2053{
2054 LogFlowFunc(("\n"));
2055 PVBOXDISK pThis = PDMIMEDIA_2_VBOXDISK(pInterface);
2056 int rc = VINF_SUCCESS;
2057
2058 /*
2059 * Check the state.
2060 */
2061 if (!pThis->pDisk)
2062 {
2063 AssertMsgFailed(("Invalid state! Not mounted!\n"));
2064 return VERR_PDM_MEDIA_NOT_MOUNTED;
2065 }
2066
2067 /* Note: There is an unavoidable race between destruction and another
2068 * thread invoking this function. This is handled safely and gracefully by
2069 * atomically invalidating the lock handle in drvvdDestruct. */
2070 int rc2 = RTSemFastMutexRequest(pThis->MergeCompleteMutex);
2071 AssertRC(rc2);
2072 if (RT_SUCCESS(rc2) && pThis->fMergePending)
2073 {
2074 /* Take shortcut: PFNSIMPLEPROGRESS is exactly the same type as
2075 * PFNVDPROGRESS, so there's no need for a conversion function. */
2076 /** @todo maybe introduce a conversion which limits update frequency. */
2077 PVDINTERFACE pVDIfsOperation = NULL;
2078 VDINTERFACEPROGRESS VDIfProgress;
2079 VDIfProgress.pfnProgress = pfnProgress;
2080 rc2 = VDInterfaceAdd(&VDIfProgress.Core, "DrvVD_VDIProgress", VDINTERFACETYPE_PROGRESS,
2081 pvUser, sizeof(VDINTERFACEPROGRESS), &pVDIfsOperation);
2082 AssertRC(rc2);
2083 pThis->fMergePending = false;
2084 rc = VDMerge(pThis->pDisk, pThis->uMergeSource,
2085 pThis->uMergeTarget, pVDIfsOperation);
2086 }
2087 rc2 = RTSemFastMutexRelease(pThis->MergeCompleteMutex);
2088 AssertRC(rc2);
2089 LogFlowFunc(("returns %Rrc\n", rc));
2090 return rc;
2091}
2092
2093/** @interface_method_impl{PDMIMEDIA,pfnSetSecKeyIf} */
2094static DECLCALLBACK(int) drvvdSetSecKeyIf(PPDMIMEDIA pInterface, PPDMISECKEY pIfSecKey, PPDMISECKEYHLP pIfSecKeyHlp)
2095{
2096 LogFlowFunc(("\n"));
2097 PVBOXDISK pThis = PDMIMEDIA_2_VBOXDISK(pInterface);
2098 int rc = VINF_SUCCESS;
2099
2100 if (pThis->pCfgCrypto)
2101 {
2102 PVDINTERFACE pVDIfFilter = NULL;
2103
2104 pThis->pIfSecKeyHlp = pIfSecKeyHlp;
2105
2106 if ( pThis->pIfSecKey
2107 && !pIfSecKey)
2108 {
2109 /* Unload the crypto filter first to make sure it doesn't access the keys anymore. */
2110 rc = VDFilterRemove(pThis->pDisk, VD_FILTER_FLAGS_DEFAULT);
2111 AssertRC(rc);
2112
2113 pThis->pIfSecKey = NULL;
2114 }
2115
2116 if ( pIfSecKey
2117 && RT_SUCCESS(rc))
2118 {
2119 pThis->pIfSecKey = pIfSecKey;
2120
2121 rc = VDInterfaceAdd(&pThis->VDIfCfg.Core, "DrvVD_Config", VDINTERFACETYPE_CONFIG,
2122 pThis->pCfgCrypto, sizeof(VDINTERFACECONFIG), &pVDIfFilter);
2123 AssertRC(rc);
2124
2125 rc = VDInterfaceAdd(&pThis->VDIfCrypto.Core, "DrvVD_Crypto", VDINTERFACETYPE_CRYPTO,
2126 pThis, sizeof(VDINTERFACECRYPTO), &pVDIfFilter);
2127 AssertRC(rc);
2128
2129 /* Load the crypt filter plugin. */
2130 rc = VDFilterAdd(pThis->pDisk, "CRYPT", VD_FILTER_FLAGS_DEFAULT, pVDIfFilter);
2131 if (RT_FAILURE(rc))
2132 pThis->pIfSecKey = NULL;
2133 }
2134 }
2135 else
2136 rc = VERR_NOT_SUPPORTED;
2137
2138 LogFlowFunc(("returns %Rrc\n", rc));
2139 return rc;
2140}
2141
2142/** @interface_method_impl{PDMIMEDIA,pfnGetSize} */
2143static DECLCALLBACK(uint64_t) drvvdGetSize(PPDMIMEDIA pInterface)
2144{
2145 LogFlowFunc(("\n"));
2146 PVBOXDISK pThis = PDMIMEDIA_2_VBOXDISK(pInterface);
2147
2148 /*
2149 * Check the state.
2150 */
2151 if (!pThis->pDisk)
2152 return 0;
2153
2154 uint64_t cb = VDGetSize(pThis->pDisk, VD_LAST_IMAGE);
2155 LogFlowFunc(("returns %#llx (%llu)\n", cb, cb));
2156 return cb;
2157}
2158
2159/** @interface_method_impl{PDMIMEDIA,pfnGetSectorSize} */
2160static DECLCALLBACK(uint32_t) drvvdGetSectorSize(PPDMIMEDIA pInterface)
2161{
2162 LogFlowFunc(("\n"));
2163 PVBOXDISK pThis = PDMIMEDIA_2_VBOXDISK(pInterface);
2164
2165 /*
2166 * Check the state.
2167 */
2168 if (!pThis->pDisk)
2169 return 0;
2170
2171 uint32_t cb = VDGetSectorSize(pThis->pDisk, VD_LAST_IMAGE);
2172 LogFlowFunc(("returns %u\n", cb));
2173 return cb;
2174}
2175
2176/** @interface_method_impl{PDMIMEDIA,pfnIsReadOnly} */
2177static DECLCALLBACK(bool) drvvdIsReadOnly(PPDMIMEDIA pInterface)
2178{
2179 LogFlowFunc(("\n"));
2180 PVBOXDISK pThis = PDMIMEDIA_2_VBOXDISK(pInterface);
2181
2182 /*
2183 * Check the state.
2184 */
2185 if (!pThis->pDisk)
2186 return false;
2187
2188 bool f = VDIsReadOnly(pThis->pDisk);
2189 LogFlowFunc(("returns %d\n", f));
2190 return f;
2191}
2192
2193/** @interface_method_impl{PDMIMEDIA,pfnBiosGetPCHSGeometry} */
2194static DECLCALLBACK(int) drvvdBiosGetPCHSGeometry(PPDMIMEDIA pInterface,
2195 PPDMMEDIAGEOMETRY pPCHSGeometry)
2196{
2197 LogFlowFunc(("\n"));
2198 PVBOXDISK pThis = PDMIMEDIA_2_VBOXDISK(pInterface);
2199 VDGEOMETRY geo;
2200
2201 /*
2202 * Check the state.
2203 */
2204 if (!pThis->pDisk)
2205 return VERR_PDM_MEDIA_NOT_MOUNTED;
2206
2207 /*
2208 * Use configured/cached values if present.
2209 */
2210 if ( pThis->PCHSGeometry.cCylinders > 0
2211 && pThis->PCHSGeometry.cHeads > 0
2212 && pThis->PCHSGeometry.cSectors > 0)
2213 {
2214 *pPCHSGeometry = pThis->PCHSGeometry;
2215 LogFlow(("%s: returns VINF_SUCCESS {%d,%d,%d}\n", __FUNCTION__, pThis->PCHSGeometry.cCylinders, pThis->PCHSGeometry.cHeads, pThis->PCHSGeometry.cSectors));
2216 return VINF_SUCCESS;
2217 }
2218
2219 int rc = VDGetPCHSGeometry(pThis->pDisk, VD_LAST_IMAGE, &geo);
2220 if (RT_SUCCESS(rc))
2221 {
2222 pPCHSGeometry->cCylinders = geo.cCylinders;
2223 pPCHSGeometry->cHeads = geo.cHeads;
2224 pPCHSGeometry->cSectors = geo.cSectors;
2225 pThis->PCHSGeometry = *pPCHSGeometry;
2226 }
2227 else
2228 {
2229 LogFunc(("geometry not available.\n"));
2230 rc = VERR_PDM_GEOMETRY_NOT_SET;
2231 }
2232 LogFlowFunc(("returns %Rrc (CHS=%d/%d/%d)\n",
2233 rc, pPCHSGeometry->cCylinders, pPCHSGeometry->cHeads, pPCHSGeometry->cSectors));
2234 return rc;
2235}
2236
2237/** @interface_method_impl{PDMIMEDIA,pfnBiosSetPCHSGeometry} */
2238static DECLCALLBACK(int) drvvdBiosSetPCHSGeometry(PPDMIMEDIA pInterface,
2239 PCPDMMEDIAGEOMETRY pPCHSGeometry)
2240{
2241 LogFlowFunc(("CHS=%d/%d/%d\n",
2242 pPCHSGeometry->cCylinders, pPCHSGeometry->cHeads, pPCHSGeometry->cSectors));
2243 PVBOXDISK pThis = PDMIMEDIA_2_VBOXDISK(pInterface);
2244 VDGEOMETRY geo;
2245
2246 /*
2247 * Check the state.
2248 */
2249 if (!pThis->pDisk)
2250 {
2251 AssertMsgFailed(("Invalid state! Not mounted!\n"));
2252 return VERR_PDM_MEDIA_NOT_MOUNTED;
2253 }
2254
2255 geo.cCylinders = pPCHSGeometry->cCylinders;
2256 geo.cHeads = pPCHSGeometry->cHeads;
2257 geo.cSectors = pPCHSGeometry->cSectors;
2258 int rc = VDSetPCHSGeometry(pThis->pDisk, VD_LAST_IMAGE, &geo);
2259 if (rc == VERR_VD_GEOMETRY_NOT_SET)
2260 rc = VERR_PDM_GEOMETRY_NOT_SET;
2261 if (RT_SUCCESS(rc))
2262 pThis->PCHSGeometry = *pPCHSGeometry;
2263 LogFlowFunc(("returns %Rrc\n", rc));
2264 return rc;
2265}
2266
2267/** @interface_method_impl{PDMIMEDIA,pfnBiosGetLCHSGeometry} */
2268static DECLCALLBACK(int) drvvdBiosGetLCHSGeometry(PPDMIMEDIA pInterface,
2269 PPDMMEDIAGEOMETRY pLCHSGeometry)
2270{
2271 LogFlowFunc(("\n"));
2272 PVBOXDISK pThis = PDMIMEDIA_2_VBOXDISK(pInterface);
2273 VDGEOMETRY geo;
2274
2275 /*
2276 * Check the state.
2277 */
2278 if (!pThis->pDisk)
2279 return VERR_PDM_MEDIA_NOT_MOUNTED;
2280
2281 /*
2282 * Use configured/cached values if present.
2283 */
2284 if ( pThis->LCHSGeometry.cCylinders > 0
2285 && pThis->LCHSGeometry.cHeads > 0
2286 && pThis->LCHSGeometry.cSectors > 0)
2287 {
2288 *pLCHSGeometry = pThis->LCHSGeometry;
2289 LogFlow(("%s: returns VINF_SUCCESS {%d,%d,%d}\n", __FUNCTION__, pThis->LCHSGeometry.cCylinders, pThis->LCHSGeometry.cHeads, pThis->LCHSGeometry.cSectors));
2290 return VINF_SUCCESS;
2291 }
2292
2293 int rc = VDGetLCHSGeometry(pThis->pDisk, VD_LAST_IMAGE, &geo);
2294 if (RT_SUCCESS(rc))
2295 {
2296 pLCHSGeometry->cCylinders = geo.cCylinders;
2297 pLCHSGeometry->cHeads = geo.cHeads;
2298 pLCHSGeometry->cSectors = geo.cSectors;
2299 pThis->LCHSGeometry = *pLCHSGeometry;
2300 }
2301 else
2302 {
2303 LogFunc(("geometry not available.\n"));
2304 rc = VERR_PDM_GEOMETRY_NOT_SET;
2305 }
2306 LogFlowFunc(("returns %Rrc (CHS=%d/%d/%d)\n",
2307 rc, pLCHSGeometry->cCylinders, pLCHSGeometry->cHeads, pLCHSGeometry->cSectors));
2308 return rc;
2309}
2310
2311/** @interface_method_impl{PDMIMEDIA,pfnBiosSetLCHSGeometry} */
2312static DECLCALLBACK(int) drvvdBiosSetLCHSGeometry(PPDMIMEDIA pInterface,
2313 PCPDMMEDIAGEOMETRY pLCHSGeometry)
2314{
2315 LogFlowFunc(("CHS=%d/%d/%d\n",
2316 pLCHSGeometry->cCylinders, pLCHSGeometry->cHeads, pLCHSGeometry->cSectors));
2317 PVBOXDISK pThis = PDMIMEDIA_2_VBOXDISK(pInterface);
2318 VDGEOMETRY geo;
2319
2320 /*
2321 * Check the state.
2322 */
2323 if (!pThis->pDisk)
2324 {
2325 AssertMsgFailed(("Invalid state! Not mounted!\n"));
2326 return VERR_PDM_MEDIA_NOT_MOUNTED;
2327 }
2328
2329 geo.cCylinders = pLCHSGeometry->cCylinders;
2330 geo.cHeads = pLCHSGeometry->cHeads;
2331 geo.cSectors = pLCHSGeometry->cSectors;
2332 int rc = VDSetLCHSGeometry(pThis->pDisk, VD_LAST_IMAGE, &geo);
2333 if (rc == VERR_VD_GEOMETRY_NOT_SET)
2334 rc = VERR_PDM_GEOMETRY_NOT_SET;
2335 if (RT_SUCCESS(rc))
2336 pThis->LCHSGeometry = *pLCHSGeometry;
2337 LogFlowFunc(("returns %Rrc\n", rc));
2338 return rc;
2339}
2340
2341/** @interface_method_impl{PDMIMEDIA,pfnBiosIsVisible} */
2342static DECLCALLBACK(bool) drvvdBiosIsVisible(PPDMIMEDIA pInterface)
2343{
2344 PVBOXDISK pThis = PDMIMEDIA_2_VBOXDISK(pInterface);
2345 LogFlow(("drvvdBiosIsVisible: returns %d\n", pThis->fBiosVisible));
2346 return pThis->fBiosVisible;
2347}
2348
2349/** @interface_method_impl{PDMIMEDIA,pfnGetType} */
2350static DECLCALLBACK(PDMMEDIATYPE) drvvdGetType(PPDMIMEDIA pInterface)
2351{
2352 PVBOXDISK pThis = PDMIMEDIA_2_VBOXDISK(pInterface);
2353 LogFlow(("drvvdBiosIsVisible: returns %d\n", pThis->fBiosVisible));
2354 return pThis->enmType;
2355}
2356
2357/** @interface_method_impl{PDMIMEDIA,pfnGetUuid} */
2358static DECLCALLBACK(int) drvvdGetUuid(PPDMIMEDIA pInterface, PRTUUID pUuid)
2359{
2360 LogFlowFunc(("\n"));
2361 PVBOXDISK pThis = PDMIMEDIA_2_VBOXDISK(pInterface);
2362
2363 /*
2364 * Copy the uuid.
2365 */
2366 *pUuid = pThis->Uuid;
2367 LogFlowFunc(("returns {%RTuuid}\n", pUuid));
2368 return VINF_SUCCESS;
2369}
2370
2371static DECLCALLBACK(int) drvvdDiscard(PPDMIMEDIA pInterface, PCRTRANGE paRanges, unsigned cRanges)
2372{
2373 LogFlowFunc(("\n"));
2374 PVBOXDISK pThis = PDMIMEDIA_2_VBOXDISK(pInterface);
2375
2376 int rc = VDDiscardRanges(pThis->pDisk, paRanges, cRanges);
2377 LogFlowFunc(("returns %Rrc\n", rc));
2378 return rc;
2379}
2380
2381/** @interface_method_impl{PDMIMEDIA,pfnIoBufAlloc} */
2382static DECLCALLBACK(int) drvvdIoBufAlloc(PPDMIMEDIA pInterface, size_t cb, void **ppvNew)
2383{
2384 LogFlowFunc(("\n"));
2385 int rc;
2386 PVBOXDISK pThis = PDMIMEDIA_2_VBOXDISK(pInterface);
2387
2388 /* Configured encryption requires locked down memory. */
2389 if (pThis->pCfgCrypto)
2390 rc = RTMemSaferAllocZEx(ppvNew, cb, RTMEMSAFER_F_REQUIRE_NOT_PAGABLE);
2391 else
2392 {
2393 cb = RT_ALIGN_Z(cb, _4K);
2394 void *pvNew = RTMemPageAlloc(cb);
2395 if (RT_LIKELY(pvNew))
2396 {
2397 *ppvNew = pvNew;
2398 rc = VINF_SUCCESS;
2399 }
2400 else
2401 rc = VERR_NO_MEMORY;
2402 }
2403
2404 LogFlowFunc(("returns %Rrc\n", rc));
2405 return rc;
2406}
2407
2408/** @interface_method_impl{PDMIMEDIA,pfnIoBufFree} */
2409static DECLCALLBACK(int) drvvdIoBufFree(PPDMIMEDIA pInterface, void *pv, size_t cb)
2410{
2411 LogFlowFunc(("\n"));
2412 int rc = VINF_SUCCESS;
2413 PVBOXDISK pThis = PDMIMEDIA_2_VBOXDISK(pInterface);
2414
2415 if (pThis->pCfgCrypto)
2416 RTMemSaferFree(pv, cb);
2417 else
2418 {
2419 cb = RT_ALIGN_Z(cb, _4K);
2420 RTMemPageFree(pv, cb);
2421 }
2422
2423 LogFlowFunc(("returns %Rrc\n", rc));
2424 return rc;
2425}
2426
2427
2428/* -=-=-=-=- IMount -=-=-=-=- */
2429
2430/** @interface_method_impl{PDMIMOUNT,pfnUnmount} */
2431static DECLCALLBACK(int) drvvdUnmount(PPDMIMOUNT pInterface, bool fForce, bool fEject)
2432{
2433 RT_NOREF(fEject);
2434 PVBOXDISK pThis = RT_FROM_MEMBER(pInterface, VBOXDISK, IMount);
2435
2436 /*
2437 * Validate state.
2438 */
2439 if (!pThis->pDisk)
2440 {
2441 Log(("drvvdUnmount: Not mounted\n"));
2442 return VERR_PDM_MEDIA_NOT_MOUNTED;
2443 }
2444 if (pThis->fLocked && !fForce)
2445 {
2446 Log(("drvvdUnmount: Locked\n"));
2447 return VERR_PDM_MEDIA_LOCKED;
2448 }
2449
2450 /* Media is no longer locked even if it was previously. */
2451 pThis->fLocked = false;
2452 drvvdPowerOffOrDestructOrUnmount(pThis->pDrvIns);
2453
2454 /*
2455 * Notify driver/device above us.
2456 */
2457 if (pThis->pDrvMountNotify)
2458 pThis->pDrvMountNotify->pfnUnmountNotify(pThis->pDrvMountNotify);
2459 Log(("drvblockUnmount: success\n"));
2460 return VINF_SUCCESS;
2461}
2462
2463
2464/** @interface_method_impl{PDMIMOUNT,pfnIsMounted} */
2465static DECLCALLBACK(bool) drvvdIsMounted(PPDMIMOUNT pInterface)
2466{
2467 PVBOXDISK pThis = RT_FROM_MEMBER(pInterface, VBOXDISK, IMount);
2468 return pThis->pDisk != NULL;
2469}
2470
2471/** @interface_method_impl{PDMIMOUNT,pfnLock} */
2472static DECLCALLBACK(int) drvvdLock(PPDMIMOUNT pInterface)
2473{
2474 PVBOXDISK pThis = RT_FROM_MEMBER(pInterface, VBOXDISK, IMount);
2475 Log(("drvblockLock: %d -> %d\n", pThis->fLocked, true));
2476 pThis->fLocked = true;
2477 return VINF_SUCCESS;
2478}
2479
2480/** @interface_method_impl{PDMIMOUNT,pfnUnlock} */
2481static DECLCALLBACK(int) drvvdUnlock(PPDMIMOUNT pInterface)
2482{
2483 PVBOXDISK pThis = RT_FROM_MEMBER(pInterface, VBOXDISK, IMount);
2484 Log(("drvblockUnlock: %d -> %d\n", pThis->fLocked, false));
2485 pThis->fLocked = false;
2486 return VINF_SUCCESS;
2487}
2488
2489/** @interface_method_impl{PDMIMOUNT,pfnIsLocked} */
2490static DECLCALLBACK(bool) drvvdIsLocked(PPDMIMOUNT pInterface)
2491{
2492 PVBOXDISK pThis = RT_FROM_MEMBER(pInterface, VBOXDISK, IMount);
2493 return pThis->fLocked;
2494}
2495
2496
2497/*********************************************************************************************************************************
2498* Async Media interface methods *
2499*********************************************************************************************************************************/
2500
2501static DECLCALLBACK(void) drvvdAsyncReqComplete(void *pvUser1, void *pvUser2, int rcReq)
2502{
2503 PVBOXDISK pThis = (PVBOXDISK)pvUser1;
2504
2505 if (!pThis->pBlkCache)
2506 {
2507 int rc = pThis->pDrvMediaAsyncPort->pfnTransferCompleteNotify(pThis->pDrvMediaAsyncPort,
2508 pvUser2, rcReq);
2509 AssertRC(rc);
2510 }
2511 else
2512 PDMR3BlkCacheIoXferComplete(pThis->pBlkCache, (PPDMBLKCACHEIOXFER)pvUser2, rcReq);
2513}
2514
2515static DECLCALLBACK(int) drvvdStartRead(PPDMIMEDIAASYNC pInterface, uint64_t uOffset,
2516 PCRTSGSEG paSeg, unsigned cSeg,
2517 size_t cbRead, void *pvUser)
2518{
2519 LogFlowFunc(("uOffset=%#llx paSeg=%#p cSeg=%u cbRead=%d pvUser=%#p\n",
2520 uOffset, paSeg, cSeg, cbRead, pvUser));
2521 int rc = VINF_SUCCESS;
2522 PVBOXDISK pThis = PDMIMEDIAASYNC_2_VBOXDISK(pInterface);
2523
2524 /*
2525 * Check the state.
2526 */
2527 if (!pThis->pDisk)
2528 {
2529 AssertMsgFailed(("Invalid state! Not mounted!\n"));
2530 return VERR_PDM_MEDIA_NOT_MOUNTED;
2531 }
2532
2533 rc = drvvdKeyCheckPrereqs(pThis);
2534 if (RT_FAILURE(rc))
2535 return rc;
2536
2537 pThis->fBootAccelActive = false;
2538
2539 RTSGBUF SgBuf;
2540 RTSgBufInit(&SgBuf, paSeg, cSeg);
2541 if (!pThis->pBlkCache)
2542 rc = VDAsyncRead(pThis->pDisk, uOffset, cbRead, &SgBuf,
2543 drvvdAsyncReqComplete, pThis, pvUser);
2544 else
2545 {
2546 rc = PDMR3BlkCacheRead(pThis->pBlkCache, uOffset, &SgBuf, cbRead, pvUser);
2547 if (rc == VINF_AIO_TASK_PENDING)
2548 rc = VERR_VD_ASYNC_IO_IN_PROGRESS;
2549 else if (rc == VINF_SUCCESS)
2550 rc = VINF_VD_ASYNC_IO_FINISHED;
2551 }
2552
2553 LogFlowFunc(("returns %Rrc\n", rc));
2554 return rc;
2555}
2556
2557static DECLCALLBACK(int) drvvdStartWrite(PPDMIMEDIAASYNC pInterface, uint64_t uOffset,
2558 PCRTSGSEG paSeg, unsigned cSeg,
2559 size_t cbWrite, void *pvUser)
2560{
2561 LogFlowFunc(("uOffset=%#llx paSeg=%#p cSeg=%u cbWrite=%d pvUser=%#p\n",
2562 uOffset, paSeg, cSeg, cbWrite, pvUser));
2563 int rc = VINF_SUCCESS;
2564 PVBOXDISK pThis = PDMIMEDIAASYNC_2_VBOXDISK(pInterface);
2565
2566 /*
2567 * Check the state.
2568 */
2569 if (!pThis->pDisk)
2570 {
2571 AssertMsgFailed(("Invalid state! Not mounted!\n"));
2572 return VERR_PDM_MEDIA_NOT_MOUNTED;
2573 }
2574
2575 rc = drvvdKeyCheckPrereqs(pThis);
2576 if (RT_FAILURE(rc))
2577 return rc;
2578
2579 pThis->fBootAccelActive = false;
2580
2581 RTSGBUF SgBuf;
2582 RTSgBufInit(&SgBuf, paSeg, cSeg);
2583
2584 if (!pThis->pBlkCache)
2585 rc = VDAsyncWrite(pThis->pDisk, uOffset, cbWrite, &SgBuf,
2586 drvvdAsyncReqComplete, pThis, pvUser);
2587 else
2588 {
2589 rc = PDMR3BlkCacheWrite(pThis->pBlkCache, uOffset, &SgBuf, cbWrite, pvUser);
2590 if (rc == VINF_AIO_TASK_PENDING)
2591 rc = VERR_VD_ASYNC_IO_IN_PROGRESS;
2592 else if (rc == VINF_SUCCESS)
2593 rc = VINF_VD_ASYNC_IO_FINISHED;
2594 }
2595
2596 LogFlowFunc(("returns %Rrc\n", rc));
2597 return rc;
2598}
2599
2600static DECLCALLBACK(int) drvvdStartFlush(PPDMIMEDIAASYNC pInterface, void *pvUser)
2601{
2602 LogFlowFunc(("pvUser=%#p\n", pvUser));
2603 int rc = VINF_SUCCESS;
2604 PVBOXDISK pThis = PDMIMEDIAASYNC_2_VBOXDISK(pInterface);
2605
2606 /*
2607 * Check the state.
2608 */
2609 if (!pThis->pDisk)
2610 {
2611 AssertMsgFailed(("Invalid state! Not mounted!\n"));
2612 return VERR_PDM_MEDIA_NOT_MOUNTED;
2613 }
2614
2615#ifdef VBOX_IGNORE_FLUSH
2616 if (pThis->fIgnoreFlushAsync)
2617 return VINF_VD_ASYNC_IO_FINISHED;
2618#endif /* VBOX_IGNORE_FLUSH */
2619
2620 if (!pThis->pBlkCache)
2621 rc = VDAsyncFlush(pThis->pDisk, drvvdAsyncReqComplete, pThis, pvUser);
2622 else
2623 {
2624 rc = PDMR3BlkCacheFlush(pThis->pBlkCache, pvUser);
2625 if (rc == VINF_AIO_TASK_PENDING)
2626 rc = VERR_VD_ASYNC_IO_IN_PROGRESS;
2627 else if (rc == VINF_SUCCESS)
2628 rc = VINF_VD_ASYNC_IO_FINISHED;
2629 }
2630 LogFlowFunc(("returns %Rrc\n", rc));
2631 return rc;
2632}
2633
2634static DECLCALLBACK(int) drvvdStartDiscard(PPDMIMEDIAASYNC pInterface, PCRTRANGE paRanges,
2635 unsigned cRanges, void *pvUser)
2636{
2637 int rc = VINF_SUCCESS;
2638 PVBOXDISK pThis = PDMIMEDIAASYNC_2_VBOXDISK(pInterface);
2639
2640 LogFlowFunc(("paRanges=%#p cRanges=%u pvUser=%#p\n",
2641 paRanges, cRanges, pvUser));
2642
2643 /*
2644 * Check the state.
2645 */
2646 if (!pThis->pDisk)
2647 {
2648 AssertMsgFailed(("Invalid state! Not mounted!\n"));
2649 return VERR_PDM_MEDIA_NOT_MOUNTED;
2650 }
2651
2652 if (!pThis->pBlkCache)
2653 rc = VDAsyncDiscardRanges(pThis->pDisk, paRanges, cRanges, drvvdAsyncReqComplete,
2654 pThis, pvUser);
2655 else
2656 {
2657 rc = PDMR3BlkCacheDiscard(pThis->pBlkCache, paRanges, cRanges, pvUser);
2658 if (rc == VINF_AIO_TASK_PENDING)
2659 rc = VERR_VD_ASYNC_IO_IN_PROGRESS;
2660 else if (rc == VINF_SUCCESS)
2661 rc = VINF_VD_ASYNC_IO_FINISHED;
2662 }
2663 LogFlowFunc(("returns %Rrc\n", rc));
2664 return rc;
2665}
2666
2667/** @copydoc FNPDMBLKCACHEXFERCOMPLETEDRV */
2668static DECLCALLBACK(void) drvvdBlkCacheXferComplete(PPDMDRVINS pDrvIns, void *pvUser, int rcReq)
2669{
2670 PVBOXDISK pThis = PDMINS_2_DATA(pDrvIns, PVBOXDISK);
2671
2672 int rc = pThis->pDrvMediaAsyncPort->pfnTransferCompleteNotify(pThis->pDrvMediaAsyncPort,
2673 pvUser, rcReq);
2674 AssertRC(rc);
2675}
2676
2677/** @copydoc FNPDMBLKCACHEXFERENQUEUEDRV */
2678static DECLCALLBACK(int) drvvdBlkCacheXferEnqueue(PPDMDRVINS pDrvIns,
2679 PDMBLKCACHEXFERDIR enmXferDir,
2680 uint64_t off, size_t cbXfer,
2681 PCRTSGBUF pcSgBuf, PPDMBLKCACHEIOXFER hIoXfer)
2682{
2683 int rc = VINF_SUCCESS;
2684 PVBOXDISK pThis = PDMINS_2_DATA(pDrvIns, PVBOXDISK);
2685
2686 Assert (!pThis->pCfgCrypto);
2687
2688 switch (enmXferDir)
2689 {
2690 case PDMBLKCACHEXFERDIR_READ:
2691 rc = VDAsyncRead(pThis->pDisk, off, cbXfer, pcSgBuf, drvvdAsyncReqComplete,
2692 pThis, hIoXfer);
2693 break;
2694 case PDMBLKCACHEXFERDIR_WRITE:
2695 rc = VDAsyncWrite(pThis->pDisk, off, cbXfer, pcSgBuf, drvvdAsyncReqComplete,
2696 pThis, hIoXfer);
2697 break;
2698 case PDMBLKCACHEXFERDIR_FLUSH:
2699 rc = VDAsyncFlush(pThis->pDisk, drvvdAsyncReqComplete, pThis, hIoXfer);
2700 break;
2701 default:
2702 AssertMsgFailed(("Invalid transfer type %d\n", enmXferDir));
2703 rc = VERR_INVALID_PARAMETER;
2704 }
2705
2706 if (rc == VINF_VD_ASYNC_IO_FINISHED)
2707 PDMR3BlkCacheIoXferComplete(pThis->pBlkCache, hIoXfer, VINF_SUCCESS);
2708 else if (RT_FAILURE(rc) && rc != VERR_VD_ASYNC_IO_IN_PROGRESS)
2709 PDMR3BlkCacheIoXferComplete(pThis->pBlkCache, hIoXfer, rc);
2710
2711 return VINF_SUCCESS;
2712}
2713
2714/** @copydoc FNPDMBLKCACHEXFERENQUEUEDISCARDDRV */
2715static DECLCALLBACK(int) drvvdBlkCacheXferEnqueueDiscard(PPDMDRVINS pDrvIns, PCRTRANGE paRanges,
2716 unsigned cRanges, PPDMBLKCACHEIOXFER hIoXfer)
2717{
2718 int rc = VINF_SUCCESS;
2719 PVBOXDISK pThis = PDMINS_2_DATA(pDrvIns, PVBOXDISK);
2720
2721 rc = VDAsyncDiscardRanges(pThis->pDisk, paRanges, cRanges,
2722 drvvdAsyncReqComplete, pThis, hIoXfer);
2723
2724 if (rc == VINF_VD_ASYNC_IO_FINISHED)
2725 PDMR3BlkCacheIoXferComplete(pThis->pBlkCache, hIoXfer, VINF_SUCCESS);
2726 else if (RT_FAILURE(rc) && rc != VERR_VD_ASYNC_IO_IN_PROGRESS)
2727 PDMR3BlkCacheIoXferComplete(pThis->pBlkCache, hIoXfer, rc);
2728
2729 return VINF_SUCCESS;
2730}
2731
2732
2733/*********************************************************************************************************************************
2734* Extended media interface methods *
2735*********************************************************************************************************************************/
2736
2737static void drvvdMediaExIoReqWarningDiskFull(PPDMDRVINS pDrvIns)
2738{
2739 int rc;
2740 LogRel(("VD#%u: Host disk full\n", pDrvIns->iInstance));
2741 rc = PDMDrvHlpVMSetRuntimeError(pDrvIns, VMSETRTERR_FLAGS_SUSPEND | VMSETRTERR_FLAGS_NO_WAIT, "DrvVD_DISKFULL",
2742 N_("Host system reported disk full. VM execution is suspended. You can resume after freeing some space"));
2743 AssertRC(rc);
2744}
2745
2746static void drvvdMediaExIoReqWarningFileTooBig(PPDMDRVINS pDrvIns)
2747{
2748 int rc;
2749 LogRel(("VD#%u: File too big\n", pDrvIns->iInstance));
2750 rc = PDMDrvHlpVMSetRuntimeError(pDrvIns, VMSETRTERR_FLAGS_SUSPEND | VMSETRTERR_FLAGS_NO_WAIT, "DrvVD_FILETOOBIG",
2751 N_("Host system reported that the file size limit of the host file system has been exceeded. VM execution is suspended. You need to move your virtual hard disk to a filesystem which allows bigger files"));
2752 AssertRC(rc);
2753}
2754
2755static void drvvdMediaExIoReqWarningISCSI(PPDMDRVINS pDrvIns)
2756{
2757 int rc;
2758 LogRel(("VD#%u: iSCSI target unavailable\n", pDrvIns->iInstance));
2759 rc = PDMDrvHlpVMSetRuntimeError(pDrvIns, VMSETRTERR_FLAGS_SUSPEND | VMSETRTERR_FLAGS_NO_WAIT, "DrvVD_ISCSIDOWN",
2760 N_("The iSCSI target has stopped responding. VM execution is suspended. You can resume when it is available again"));
2761 AssertRC(rc);
2762}
2763
2764/**
2765 * Checks whether a given status code indicates a recoverable error
2766 * suspending the VM if it is.
2767 *
2768 * @returns Flag indicating whether the status code is a recoverable error
2769 * (full disk, broken network connection).
2770 * @param pThis VBox disk container instance data.
2771 * @param rc Status code to check.
2772 */
2773bool drvvdMediaExIoReqIsRedoSetWarning(PVBOXDISK pThis, int rc)
2774{
2775 if (rc == VERR_DISK_FULL)
2776 {
2777 if (ASMAtomicCmpXchgBool(&pThis->fRedo, true, false))
2778 drvvdMediaExIoReqWarningDiskFull(pThis->pDrvIns);
2779 return true;
2780 }
2781 if (rc == VERR_FILE_TOO_BIG)
2782 {
2783 if (ASMAtomicCmpXchgBool(&pThis->fRedo, true, false))
2784 drvvdMediaExIoReqWarningFileTooBig(pThis->pDrvIns);
2785 return true;
2786 }
2787 if (rc == VERR_BROKEN_PIPE || rc == VERR_NET_CONNECTION_REFUSED)
2788 {
2789 /* iSCSI connection abort (first error) or failure to reestablish
2790 * connection (second error). Pause VM. On resume we'll retry. */
2791 if (ASMAtomicCmpXchgBool(&pThis->fRedo, true, false))
2792 drvvdMediaExIoReqWarningISCSI(pThis->pDrvIns);
2793 return true;
2794 }
2795 if (rc == VERR_VD_DEK_MISSING)
2796 {
2797 /* Error message already set. */
2798 ASMAtomicCmpXchgBool(&pThis->fRedo, true, false);
2799 return true;
2800 }
2801
2802 return false;
2803}
2804
2805/**
2806 * Syncs the memory buffers between the I/O request allocator and the internal buffer.
2807 *
2808 * @returns VBox status code.
2809 * @param pThis VBox disk container instance data.
2810 * @param pIoReq I/O request to sync.
2811 * @param fToIoBuf Flag indicating the sync direction.
2812 * true to copy data from the allocators buffer to our internal buffer.
2813 * false for the other direction.
2814 */
2815DECLINLINE(int) drvvdMediaExIoReqBufSync(PVBOXDISK pThis, PPDMMEDIAEXIOREQINT pIoReq, bool fToIoBuf)
2816{
2817 int rc = VINF_SUCCESS;
2818
2819 Assert(pIoReq->enmType == PDMMEDIAEXIOREQTYPE_READ || pIoReq->enmType == PDMMEDIAEXIOREQTYPE_WRITE);
2820
2821 /* Make sure the buffer is reset. */
2822 RTSgBufReset(&pIoReq->ReadWrite.IoBuf.SgBuf);
2823
2824 size_t const offSrc = pIoReq->ReadWrite.cbReq - pIoReq->ReadWrite.cbReqLeft;
2825 Assert((uint32_t)offSrc == offSrc);
2826 if (fToIoBuf)
2827 rc = pThis->pDrvMediaExPort->pfnIoReqCopyToBuf(pThis->pDrvMediaExPort, pIoReq, &pIoReq->abAlloc[0], (uint32_t)offSrc,
2828 &pIoReq->ReadWrite.IoBuf.SgBuf,
2829 RT_MIN(pIoReq->ReadWrite.cbIoBuf, pIoReq->ReadWrite.cbReqLeft));
2830 else
2831 rc = pThis->pDrvMediaExPort->pfnIoReqCopyFromBuf(pThis->pDrvMediaExPort, pIoReq, &pIoReq->abAlloc[0], (uint32_t)offSrc,
2832 &pIoReq->ReadWrite.IoBuf.SgBuf,
2833 (uint32_t)RT_MIN(pIoReq->ReadWrite.cbIoBuf, pIoReq->ReadWrite.cbReqLeft));
2834
2835 RTSgBufReset(&pIoReq->ReadWrite.IoBuf.SgBuf);
2836 return rc;
2837}
2838
2839/**
2840 * Hashes the I/O request ID to an index for the allocated I/O request bin.
2841 */
2842DECLINLINE(unsigned) drvvdMediaExIoReqIdHash(PDMMEDIAEXIOREQID uIoReqId)
2843{
2844 return uIoReqId % DRVVD_VDIOREQ_ALLOC_BINS; /** @todo Find something better? */
2845}
2846
2847/**
2848 * Inserts the given I/O request in to the list of allocated I/O requests.
2849 *
2850 * @returns VBox status code.
2851 * @param pThis VBox disk container instance data.
2852 * @param pIoReq I/O request to insert.
2853 */
2854static int drvvdMediaExIoReqInsert(PVBOXDISK pThis, PPDMMEDIAEXIOREQINT pIoReq)
2855{
2856 int rc = VINF_SUCCESS;
2857 unsigned idxBin = drvvdMediaExIoReqIdHash(pIoReq->uIoReqId);
2858
2859 rc = RTSemFastMutexRequest(pThis->aIoReqAllocBins[idxBin].hMtxLstIoReqAlloc);
2860 if (RT_SUCCESS(rc))
2861 {
2862 /* Search for conflicting I/O request ID. */
2863 PPDMMEDIAEXIOREQINT pIt;
2864 RTListForEach(&pThis->aIoReqAllocBins[idxBin].LstIoReqAlloc, pIt, PDMMEDIAEXIOREQINT, NdAllocatedList)
2865 {
2866 if (RT_UNLIKELY(pIt->uIoReqId == pIoReq->uIoReqId))
2867 {
2868 rc = VERR_PDM_MEDIAEX_IOREQID_CONFLICT;
2869 break;
2870 }
2871 }
2872 if (RT_SUCCESS(rc))
2873 RTListAppend(&pThis->aIoReqAllocBins[idxBin].LstIoReqAlloc, &pIoReq->NdAllocatedList);
2874 RTSemFastMutexRelease(pThis->aIoReqAllocBins[idxBin].hMtxLstIoReqAlloc);
2875 }
2876
2877 return rc;
2878}
2879
2880/**
2881 * Removes the given I/O request from the list of allocated I/O requests.
2882 *
2883 * @returns VBox status code.
2884 * @param pThis VBox disk container instance data.
2885 * @param pIoReq I/O request to insert.
2886 */
2887static int drvvdMediaExIoReqRemove(PVBOXDISK pThis, PPDMMEDIAEXIOREQINT pIoReq)
2888{
2889 int rc = VINF_SUCCESS;
2890 unsigned idxBin = drvvdMediaExIoReqIdHash(pIoReq->uIoReqId);
2891
2892 rc = RTSemFastMutexRequest(pThis->aIoReqAllocBins[idxBin].hMtxLstIoReqAlloc);
2893 if (RT_SUCCESS(rc))
2894 {
2895 RTListNodeRemove(&pIoReq->NdAllocatedList);
2896 RTSemFastMutexRelease(pThis->aIoReqAllocBins[idxBin].hMtxLstIoReqAlloc);
2897 }
2898
2899 return rc;
2900}
2901
2902/**
2903 * I/O request completion worker.
2904 *
2905 * @returns VBox status code.
2906 * @param pThis VBox disk container instance data.
2907 * @param pIoReq I/O request to complete.
2908 * @param rcReq The status code the request completed with.
2909 * @param fUpNotify Flag whether to notify the driver/device above us about the completion.
2910 */
2911static int drvvdMediaExIoReqCompleteWorker(PVBOXDISK pThis, PPDMMEDIAEXIOREQINT pIoReq, int rcReq, bool fUpNotify)
2912{
2913 int rc;
2914 bool fXchg = ASMAtomicCmpXchgU32((volatile uint32_t *)&pIoReq->enmState, VDIOREQSTATE_COMPLETING, VDIOREQSTATE_ACTIVE);
2915 if (fXchg)
2916 ASMAtomicDecU32(&pThis->cIoReqsActive);
2917 else
2918 {
2919 Assert(pIoReq->enmState == VDIOREQSTATE_CANCELED);
2920 rcReq = VERR_PDM_MEDIAEX_IOREQ_CANCELED;
2921 }
2922
2923 ASMAtomicXchgU32((volatile uint32_t *)&pIoReq->enmState, VDIOREQSTATE_COMPLETED);
2924 drvvdMediaExIoReqBufFree(pThis, pIoReq);
2925
2926 /*
2927 * Leave a release log entry if the request was active for more than 25 seconds
2928 * (30 seconds is the timeout of the guest).
2929 */
2930 uint64_t tsNow = RTTimeMilliTS();
2931 if (tsNow - pIoReq->tsSubmit >= 25 * 1000)
2932 {
2933 const char *pcszReq = NULL;
2934
2935 switch (pIoReq->enmType)
2936 {
2937 case PDMMEDIAEXIOREQTYPE_READ:
2938 pcszReq = "Read";
2939 break;
2940 case PDMMEDIAEXIOREQTYPE_WRITE:
2941 pcszReq = "Write";
2942 break;
2943 case PDMMEDIAEXIOREQTYPE_FLUSH:
2944 pcszReq = "Flush";
2945 break;
2946 case PDMMEDIAEXIOREQTYPE_DISCARD:
2947 pcszReq = "Discard";
2948 break;
2949 default:
2950 pcszReq = "<Invalid>";
2951 }
2952
2953 LogRel(("VD#%u: %s request was active for %llu seconds\n",
2954 pThis->pDrvIns->iInstance, pcszReq, (tsNow - pIoReq->tsSubmit) / 1000));
2955 }
2956
2957 if (RT_FAILURE(rcReq))
2958 {
2959 /* Log the error. */
2960 if (pThis->cErrors++ < DRVVD_MAX_LOG_REL_ERRORS)
2961 {
2962 if (rcReq == VERR_PDM_MEDIAEX_IOREQ_CANCELED)
2963 {
2964 if (pIoReq->enmType == PDMMEDIAEXIOREQTYPE_FLUSH)
2965 LogRel(("VD#%u: Aborted flush returned rc=%Rrc\n",
2966 pThis->pDrvIns->iInstance, rcReq));
2967 else
2968 LogRel(("VD#%u: Aborted %s (%u bytes left) returned rc=%Rrc\n",
2969 pThis->pDrvIns->iInstance,
2970 pIoReq->enmType == PDMMEDIAEXIOREQTYPE_READ
2971 ? "read"
2972 : "write",
2973 pIoReq->ReadWrite.cbReqLeft, rcReq));
2974 }
2975 else
2976 {
2977 if (pIoReq->enmType == PDMMEDIAEXIOREQTYPE_FLUSH)
2978 LogRel(("VD#%u: Flush returned rc=%Rrc\n",
2979 pThis->pDrvIns->iInstance, rcReq));
2980 else
2981 LogRel(("VD#%u: %s (%u bytes left) returned rc=%Rrc\n",
2982 pThis->pDrvIns->iInstance,
2983 pIoReq->enmType == PDMMEDIAEXIOREQTYPE_READ
2984 ? "Read"
2985 : "Write",
2986 pIoReq->ReadWrite.cbReqLeft, rcReq));
2987 }
2988 }
2989 }
2990
2991 if (fUpNotify)
2992 {
2993 rc = pThis->pDrvMediaExPort->pfnIoReqCompleteNotify(pThis->pDrvMediaExPort,
2994 pIoReq, &pIoReq->abAlloc[0], rcReq);
2995 AssertRC(rc);
2996 }
2997
2998 return rcReq;
2999}
3000
3001
3002/**
3003 * Allocates a memory buffer suitable for I/O for the given request.
3004 *
3005 * @returns VBox status code.
3006 * @param VINF_PDM_MEDIAEX_IOREQ_IN_PROGRESS if there is no I/O memory available to allocate and
3007 * the request was placed on a waiting list.
3008 * @param pThis VBox disk container instance data.
3009 * @param pIoReq I/O request to allocate memory for.
3010 * @param cb Size of the buffer.
3011 */
3012DECLINLINE(int) drvvdMediaExIoReqBufAlloc(PVBOXDISK pThis, PPDMMEDIAEXIOREQINT pIoReq, size_t cb)
3013{
3014 int rc = IOBUFMgrAllocBuf(pThis->hIoBufMgr, &pIoReq->ReadWrite.IoBuf, cb, &pIoReq->ReadWrite.cbIoBuf);
3015 if (rc == VERR_NO_MEMORY)
3016 {
3017 RTCritSectEnter(&pThis->CritSectIoReqsIoBufWait);
3018 RTListAppend(&pThis->LstIoReqIoBufWait, &pIoReq->NdLstWait);
3019 RTCritSectLeave(&pThis->CritSectIoReqsIoBufWait);
3020 ASMAtomicIncU32(&pThis->cIoReqsWaiting);
3021 rc = VINF_PDM_MEDIAEX_IOREQ_IN_PROGRESS;
3022 }
3023
3024 return rc;
3025}
3026
3027
3028/**
3029 * Processes a read/write request.
3030 *
3031 * @returns VBox status code.
3032 * @param pThis VBox disk container instance data.
3033 * @param pIoReq I/O request to process.
3034 * @param fUpNotify Flag whether to notify the driver/device above us about the completion.
3035 */
3036static int drvvdMediaExIoReqReadWriteProcess(PVBOXDISK pThis, PPDMMEDIAEXIOREQINT pIoReq, bool fUpNotify)
3037{
3038 int rc = VINF_SUCCESS;
3039
3040 Assert(pIoReq->enmType == PDMMEDIAEXIOREQTYPE_READ || pIoReq->enmType == PDMMEDIAEXIOREQTYPE_WRITE);
3041
3042 while ( pIoReq->ReadWrite.cbReqLeft
3043 && rc == VINF_SUCCESS)
3044 {
3045 size_t cbReqIo = RT_MIN(pIoReq->ReadWrite.cbReqLeft, pIoReq->ReadWrite.cbIoBuf);
3046
3047 if (pIoReq->enmType == PDMMEDIAEXIOREQTYPE_READ)
3048 {
3049 if (pThis->fAsyncIOSupported)
3050 rc = VDAsyncRead(pThis->pDisk, pIoReq->ReadWrite.offStart, cbReqIo, &pIoReq->ReadWrite.IoBuf.SgBuf,
3051 drvvdMediaExIoReqComplete, pThis, pIoReq);
3052 else
3053 {
3054 void *pvBuf = RTSgBufGetNextSegment(&pIoReq->ReadWrite.IoBuf.SgBuf, &cbReqIo);
3055
3056 Assert(cbReqIo > 0 && VALID_PTR(pvBuf));
3057 rc = VDRead(pThis->pDisk, pIoReq->ReadWrite.offStart, pvBuf, cbReqIo);
3058 if (RT_SUCCESS(rc))
3059 rc = VINF_VD_ASYNC_IO_FINISHED;
3060 }
3061 }
3062 else
3063 {
3064 /* Sync memory buffer from the request initiator. */
3065 rc = drvvdMediaExIoReqBufSync(pThis, pIoReq, true /* fToIoBuf */);
3066 if (RT_SUCCESS(rc))
3067 {
3068 if (pThis->fAsyncIOSupported)
3069 rc = VDAsyncWrite(pThis->pDisk, pIoReq->ReadWrite.offStart, cbReqIo,
3070 &pIoReq->ReadWrite.IoBuf.SgBuf,
3071 drvvdMediaExIoReqComplete, pThis, pIoReq);
3072 else
3073 {
3074 void *pvBuf = RTSgBufGetNextSegment(&pIoReq->ReadWrite.IoBuf.SgBuf, &cbReqIo);
3075
3076 Assert(cbReqIo > 0 && VALID_PTR(pvBuf));
3077 rc = VDWrite(pThis->pDisk, pIoReq->ReadWrite.offStart, pvBuf, cbReqIo);
3078 if (RT_SUCCESS(rc))
3079 rc = VINF_VD_ASYNC_IO_FINISHED;
3080 }
3081 }
3082 }
3083
3084 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
3085 rc = VINF_PDM_MEDIAEX_IOREQ_IN_PROGRESS;
3086 else if (rc == VINF_VD_ASYNC_IO_FINISHED)
3087 {
3088 if (pIoReq->enmType == PDMMEDIAEXIOREQTYPE_READ)
3089 rc = drvvdMediaExIoReqBufSync(pThis, pIoReq, false /* fToIoBuf */);
3090 else
3091 rc = VINF_SUCCESS;
3092 pIoReq->ReadWrite.offStart += cbReqIo;
3093 pIoReq->ReadWrite.cbReqLeft -= cbReqIo;
3094 }
3095 }
3096
3097 if (rc != VINF_PDM_MEDIAEX_IOREQ_IN_PROGRESS)
3098 {
3099 Assert(!pIoReq->ReadWrite.cbReqLeft || RT_FAILURE(rc));
3100 rc = drvvdMediaExIoReqCompleteWorker(pThis, pIoReq, rc, fUpNotify);
3101 }
3102
3103 return rc;
3104}
3105
3106
3107/**
3108 * Frees a I/O memory buffer allocated previously.
3109 *
3110 * @returns nothing.
3111 * @param pThis VBox disk container instance data.
3112 * @param pIoReq I/O request for which to free memory.
3113 */
3114DECLINLINE(void) drvvdMediaExIoReqBufFree(PVBOXDISK pThis, PPDMMEDIAEXIOREQINT pIoReq)
3115{
3116 if ( pIoReq->enmType == PDMMEDIAEXIOREQTYPE_READ
3117 || pIoReq->enmType == PDMMEDIAEXIOREQTYPE_WRITE)
3118 {
3119 IOBUFMgrFreeBuf(&pIoReq->ReadWrite.IoBuf);
3120
3121 if (ASMAtomicReadU32(&pThis->cIoReqsWaiting) > 0)
3122 {
3123 /* Try to process as many requests as possible. */
3124 RTCritSectEnter(&pThis->CritSectIoReqsIoBufWait);
3125 PPDMMEDIAEXIOREQINT pIoReqCur, pIoReqNext;
3126
3127 RTListForEachSafe(&pThis->LstIoReqIoBufWait, pIoReqCur, pIoReqNext, PDMMEDIAEXIOREQINT, NdLstWait)
3128 {
3129 /* Allocate a suitable I/O buffer for this request. */
3130 int rc = IOBUFMgrAllocBuf(pThis->hIoBufMgr, &pIoReqCur->ReadWrite.IoBuf, pIoReqCur->ReadWrite.cbReq,
3131 &pIoReqCur->ReadWrite.cbIoBuf);
3132 if (rc == VINF_SUCCESS)
3133 {
3134 ASMAtomicDecU32(&pThis->cIoReqsWaiting);
3135 RTListNodeRemove(&pIoReqCur->NdLstWait);
3136
3137 bool fXchg = ASMAtomicCmpXchgU32((volatile uint32_t *)&pIoReqCur->enmState, VDIOREQSTATE_ACTIVE, VDIOREQSTATE_ALLOCATED);
3138 if (RT_UNLIKELY(!fXchg))
3139 {
3140 /* Must have been canceled inbetween. */
3141 Assert(pIoReq->enmState == VDIOREQSTATE_CANCELED);
3142 drvvdMediaExIoReqCompleteWorker(pThis, pIoReqCur, VERR_PDM_MEDIAEX_IOREQ_CANCELED, true /* fUpNotify */);
3143 }
3144 ASMAtomicIncU32(&pThis->cIoReqsActive);
3145 rc = drvvdMediaExIoReqReadWriteProcess(pThis, pIoReqCur, true /* fUpNotify */);
3146 }
3147 else
3148 {
3149 Assert(rc == VERR_NO_MEMORY);
3150 break;
3151 }
3152 }
3153 RTCritSectLeave(&pThis->CritSectIoReqsIoBufWait);
3154 }
3155 }
3156}
3157
3158
3159/**
3160 * Returns whether the VM is in a running state.
3161 *
3162 * @returns Flag indicating whether the VM is currently in a running state.
3163 * @param pThis VBox disk container instance data.
3164 */
3165DECLINLINE(bool) drvvdMediaExIoReqIsVmRunning(PVBOXDISK pThis)
3166{
3167 VMSTATE enmVmState = PDMDrvHlpVMState(pThis->pDrvIns);
3168 if ( enmVmState == VMSTATE_RESUMING
3169 || enmVmState == VMSTATE_RUNNING
3170 || enmVmState == VMSTATE_RUNNING_LS
3171 || enmVmState == VMSTATE_RUNNING_FT
3172 || enmVmState == VMSTATE_RESETTING
3173 || enmVmState == VMSTATE_RESETTING_LS
3174 || enmVmState == VMSTATE_SOFT_RESETTING
3175 || enmVmState == VMSTATE_SOFT_RESETTING_LS
3176 || enmVmState == VMSTATE_SUSPENDING
3177 || enmVmState == VMSTATE_SUSPENDING_LS
3178 || enmVmState == VMSTATE_SUSPENDING_EXT_LS)
3179 return true;
3180
3181 return false;
3182}
3183
3184/**
3185 * @copydoc FNVDASYNCTRANSFERCOMPLETE
3186 */
3187static DECLCALLBACK(void) drvvdMediaExIoReqComplete(void *pvUser1, void *pvUser2, int rcReq)
3188{
3189 PVBOXDISK pThis = (PVBOXDISK)pvUser1;
3190 PPDMMEDIAEXIOREQINT pIoReq = (PPDMMEDIAEXIOREQINT)pvUser2;
3191
3192 /*
3193 * For a read we need to sync the memory before continuing to process
3194 * the request further.
3195 */
3196 if ( RT_SUCCESS(rcReq)
3197 && pIoReq->enmType == PDMMEDIAEXIOREQTYPE_READ)
3198 rcReq = drvvdMediaExIoReqBufSync(pThis, pIoReq, false /* fToIoBuf */);
3199
3200 /*
3201 * When the request owner instructs us to handle recoverable errors like full disks
3202 * do it. Mark the request as suspended, notify the owner and put the request on the
3203 * redo list.
3204 */
3205 if ( RT_FAILURE(rcReq)
3206 && (pIoReq->fFlags & PDMIMEDIAEX_F_SUSPEND_ON_RECOVERABLE_ERR)
3207 && drvvdMediaExIoReqIsRedoSetWarning(pThis, rcReq))
3208 {
3209 bool fXchg = ASMAtomicCmpXchgU32((volatile uint32_t *)&pIoReq->enmState, VDIOREQSTATE_SUSPENDED, VDIOREQSTATE_ACTIVE);
3210 if (fXchg)
3211 {
3212 /* Put on redo list and adjust active request counter. */
3213 RTCritSectEnter(&pThis->CritSectIoReqRedo);
3214 RTListAppend(&pThis->LstIoReqRedo, &pIoReq->NdLstWait);
3215 RTCritSectLeave(&pThis->CritSectIoReqRedo);
3216 ASMAtomicDecU32(&pThis->cIoReqsActive);
3217 pThis->pDrvMediaExPort->pfnIoReqStateChanged(pThis->pDrvMediaExPort, pIoReq, &pIoReq->abAlloc[0],
3218 PDMMEDIAEXIOREQSTATE_SUSPENDED);
3219 }
3220 else
3221 {
3222 /* Request was canceled inbetween, so don't care and notify the owner about the completed request. */
3223 Assert(pIoReq->enmState == VDIOREQSTATE_CANCELED);
3224 drvvdMediaExIoReqCompleteWorker(pThis, pIoReq, rcReq, true /* fUpNotify */);
3225 }
3226 }
3227 else
3228 {
3229 /* Adjust the remaining amount to transfer. */
3230 size_t cbReqIo = RT_MIN(pIoReq->ReadWrite.cbReqLeft, pIoReq->ReadWrite.cbIoBuf);
3231 pIoReq->ReadWrite.offStart += cbReqIo;
3232 pIoReq->ReadWrite.cbReqLeft -= cbReqIo;
3233
3234 if ( RT_FAILURE(rcReq)
3235 || !pIoReq->ReadWrite.cbReqLeft
3236 || ( pIoReq->enmType != PDMMEDIAEXIOREQTYPE_READ
3237 && pIoReq->enmType != PDMMEDIAEXIOREQTYPE_WRITE))
3238 drvvdMediaExIoReqCompleteWorker(pThis, pIoReq, rcReq, true /* fUpNotify */);
3239 else
3240 drvvdMediaExIoReqReadWriteProcess(pThis, pIoReq, true /* fUpNotify */);
3241 }
3242}
3243
3244/**
3245 * @interface_method_impl{PDMIMEDIAEX,pfnIoReqAllocSizeSet}
3246 */
3247static DECLCALLBACK(int) drvvdIoReqAllocSizeSet(PPDMIMEDIAEX pInterface, size_t cbIoReqAlloc)
3248{
3249 PVBOXDISK pThis = RT_FROM_MEMBER(pInterface, VBOXDISK, IMediaEx);
3250 if (RT_UNLIKELY(pThis->hIoReqCache != NIL_RTMEMCACHE))
3251 return VERR_INVALID_STATE;
3252
3253 return RTMemCacheCreate(&pThis->hIoReqCache, sizeof(PDMMEDIAEXIOREQINT) + cbIoReqAlloc, 0, UINT32_MAX,
3254 NULL, NULL, NULL, 0);
3255}
3256
3257/**
3258 * @interface_method_impl{PDMIMEDIAEX,pfnIoReqAlloc}
3259 */
3260static DECLCALLBACK(int) drvvdIoReqAlloc(PPDMIMEDIAEX pInterface, PPDMMEDIAEXIOREQ phIoReq, void **ppvIoReqAlloc,
3261 PDMMEDIAEXIOREQID uIoReqId, uint32_t fFlags)
3262{
3263 PVBOXDISK pThis = RT_FROM_MEMBER(pInterface, VBOXDISK, IMediaEx);
3264
3265 AssertReturn(!(fFlags & ~PDMIMEDIAEX_F_VALID), VERR_INVALID_PARAMETER);
3266
3267 PPDMMEDIAEXIOREQINT pIoReq = (PPDMMEDIAEXIOREQINT)RTMemCacheAlloc(pThis->hIoReqCache);
3268
3269 if (RT_UNLIKELY(!pIoReq))
3270 return VERR_NO_MEMORY;
3271
3272 pIoReq->uIoReqId = uIoReqId;
3273 pIoReq->fFlags = fFlags;
3274 pIoReq->pDisk = pThis;
3275 pIoReq->enmState = VDIOREQSTATE_ALLOCATED;
3276 pIoReq->enmType = PDMMEDIAEXIOREQTYPE_INVALID;
3277
3278 int rc = drvvdMediaExIoReqInsert(pThis, pIoReq);
3279 if (RT_SUCCESS(rc))
3280 {
3281 *phIoReq = pIoReq;
3282 *ppvIoReqAlloc = &pIoReq->abAlloc[0];
3283 }
3284 else
3285 RTMemCacheFree(pThis->hIoReqCache, pIoReq);
3286
3287 return rc;
3288}
3289
3290/**
3291 * @interface_method_impl{PDMIMEDIAEX,pfnIoReqFree}
3292 */
3293static DECLCALLBACK(int) drvvdIoReqFree(PPDMIMEDIAEX pInterface, PDMMEDIAEXIOREQ hIoReq)
3294{
3295 PVBOXDISK pThis = RT_FROM_MEMBER(pInterface, VBOXDISK, IMediaEx);
3296 PPDMMEDIAEXIOREQINT pIoReq = hIoReq;
3297
3298 if ( pIoReq->enmState != VDIOREQSTATE_COMPLETED
3299 && pIoReq->enmState != VDIOREQSTATE_ALLOCATED)
3300 return VERR_PDM_MEDIAEX_IOREQ_INVALID_STATE;
3301
3302 /* Remove from allocated list. */
3303 int rc = drvvdMediaExIoReqRemove(pThis, pIoReq);
3304 if (RT_FAILURE(rc))
3305 return rc;
3306
3307 /* Free any associated I/O memory. */
3308 drvvdMediaExIoReqBufFree(pThis, pIoReq);
3309
3310 /* For discard request discard the range array. */
3311 if ( pIoReq->enmType == PDMMEDIAEXIOREQTYPE_DISCARD
3312 && pIoReq->Discard.paRanges)
3313 {
3314 RTMemFree(pIoReq->Discard.paRanges);
3315 pIoReq->Discard.paRanges = NULL;
3316 }
3317
3318 pIoReq->enmState = VDIOREQSTATE_FREE;
3319 RTMemCacheFree(pThis->hIoReqCache, pIoReq);
3320 return VINF_SUCCESS;
3321}
3322
3323/**
3324 * @interface_method_impl{PDMIMEDIAEX,pfnIoReqCancel}
3325 */
3326static DECLCALLBACK(int) drvvdIoReqCancel(PPDMIMEDIAEX pInterface, PDMMEDIAEXIOREQID uIoReqId)
3327{
3328 PVBOXDISK pThis = RT_FROM_MEMBER(pInterface, VBOXDISK, IMediaEx);
3329 unsigned idxBin = drvvdMediaExIoReqIdHash(uIoReqId);
3330
3331 int rc = RTSemFastMutexRequest(pThis->aIoReqAllocBins[idxBin].hMtxLstIoReqAlloc);
3332 if (RT_SUCCESS(rc))
3333 {
3334 /* Search for I/O request with ID. */
3335 PPDMMEDIAEXIOREQINT pIt;
3336 rc = VERR_PDM_MEDIAEX_IOREQID_NOT_FOUND;
3337
3338 RTListForEach(&pThis->aIoReqAllocBins[idxBin].LstIoReqAlloc, pIt, PDMMEDIAEXIOREQINT, NdAllocatedList)
3339 {
3340 if (pIt->uIoReqId == uIoReqId)
3341 {
3342 bool fXchg = true;
3343 VDIOREQSTATE enmStateOld = (VDIOREQSTATE)ASMAtomicReadU32((volatile uint32_t *)&pIt->enmState);
3344
3345 /*
3346 * We might have to try canceling the request multiple times if it transitioned from
3347 * ALLOCATED to ACTIVE or to SUSPENDED between reading the state and trying to change it.
3348 */
3349 while ( ( enmStateOld == VDIOREQSTATE_ALLOCATED
3350 || enmStateOld == VDIOREQSTATE_ACTIVE
3351 || enmStateOld == VDIOREQSTATE_SUSPENDED)
3352 && !fXchg)
3353 {
3354 fXchg = ASMAtomicCmpXchgU32((volatile uint32_t *)&pIt->enmState, VDIOREQSTATE_CANCELED, enmStateOld);
3355 if (!fXchg)
3356 enmStateOld = (VDIOREQSTATE)ASMAtomicReadU32((volatile uint32_t *)&pIt->enmState);
3357 }
3358
3359 if (fXchg)
3360 {
3361 ASMAtomicDecU32(&pThis->cIoReqsActive);
3362 rc = VINF_SUCCESS;
3363 }
3364 break;
3365 }
3366 }
3367 RTSemFastMutexRelease(pThis->aIoReqAllocBins[idxBin].hMtxLstIoReqAlloc);
3368 }
3369
3370 return rc;
3371}
3372
3373/**
3374 * @interface_method_impl{PDMIMEDIAEX,pfnIoReqRead}
3375 */
3376static DECLCALLBACK(int) drvvdIoReqRead(PPDMIMEDIAEX pInterface, PDMMEDIAEXIOREQ hIoReq, uint64_t off, size_t cbRead)
3377{
3378 PVBOXDISK pThis = RT_FROM_MEMBER(pInterface, VBOXDISK, IMediaEx);
3379 PPDMMEDIAEXIOREQINT pIoReq = hIoReq;
3380 VDIOREQSTATE enmState = (VDIOREQSTATE)ASMAtomicReadU32((volatile uint32_t *)&pIoReq->enmState);
3381
3382 if (RT_UNLIKELY(enmState == VDIOREQSTATE_CANCELED))
3383 return VERR_PDM_MEDIAEX_IOREQ_CANCELED;
3384
3385 if (RT_UNLIKELY(enmState != VDIOREQSTATE_ALLOCATED))
3386 return VERR_PDM_MEDIAEX_IOREQ_INVALID_STATE;
3387
3388 pIoReq->enmType = PDMMEDIAEXIOREQTYPE_READ;
3389 pIoReq->tsSubmit = RTTimeMilliTS();
3390 pIoReq->ReadWrite.offStart = off;
3391 pIoReq->ReadWrite.cbReq = cbRead;
3392 pIoReq->ReadWrite.cbReqLeft = cbRead;
3393 /* Allocate a suitable I/O buffer for this request. */
3394 int rc = drvvdMediaExIoReqBufAlloc(pThis, pIoReq, cbRead);
3395 if (rc == VINF_SUCCESS)
3396 {
3397 bool fXchg = ASMAtomicCmpXchgU32((volatile uint32_t *)&pIoReq->enmState, VDIOREQSTATE_ACTIVE, VDIOREQSTATE_ALLOCATED);
3398 if (RT_UNLIKELY(!fXchg))
3399 {
3400 /* Must have been canceled inbetween. */
3401 Assert(pIoReq->enmState == VDIOREQSTATE_CANCELED);
3402 return VERR_PDM_MEDIAEX_IOREQ_CANCELED;
3403 }
3404 ASMAtomicIncU32(&pThis->cIoReqsActive);
3405
3406 rc = drvvdMediaExIoReqReadWriteProcess(pThis, pIoReq, false /* fUpNotify */);
3407 }
3408
3409 return rc;
3410}
3411
3412/**
3413 * @interface_method_impl{PDMIMEDIAEX,pfnIoReqWrite}
3414 */
3415static DECLCALLBACK(int) drvvdIoReqWrite(PPDMIMEDIAEX pInterface, PDMMEDIAEXIOREQ hIoReq, uint64_t off, size_t cbWrite)
3416{
3417 PVBOXDISK pThis = RT_FROM_MEMBER(pInterface, VBOXDISK, IMediaEx);
3418 PPDMMEDIAEXIOREQINT pIoReq = hIoReq;
3419 VDIOREQSTATE enmState = (VDIOREQSTATE)ASMAtomicReadU32((volatile uint32_t *)&pIoReq->enmState);
3420
3421 if (RT_UNLIKELY(enmState == VDIOREQSTATE_CANCELED))
3422 return VERR_PDM_MEDIAEX_IOREQ_CANCELED;
3423
3424 if (RT_UNLIKELY(enmState != VDIOREQSTATE_ALLOCATED))
3425 return VERR_PDM_MEDIAEX_IOREQ_INVALID_STATE;
3426
3427 pIoReq->enmType = PDMMEDIAEXIOREQTYPE_WRITE;
3428 pIoReq->tsSubmit = RTTimeMilliTS();
3429 pIoReq->ReadWrite.offStart = off;
3430 pIoReq->ReadWrite.cbReq = cbWrite;
3431 pIoReq->ReadWrite.cbReqLeft = cbWrite;
3432 /* Allocate a suitable I/O buffer for this request. */
3433 int rc = drvvdMediaExIoReqBufAlloc(pThis, pIoReq, cbWrite);
3434 if (rc == VINF_SUCCESS)
3435 {
3436 bool fXchg = ASMAtomicCmpXchgU32((volatile uint32_t *)&pIoReq->enmState, VDIOREQSTATE_ACTIVE, VDIOREQSTATE_ALLOCATED);
3437 if (RT_UNLIKELY(!fXchg))
3438 {
3439 /* Must have been canceled inbetween. */
3440 Assert(pIoReq->enmState == VDIOREQSTATE_CANCELED);
3441 return VERR_PDM_MEDIAEX_IOREQ_CANCELED;
3442 }
3443 ASMAtomicIncU32(&pThis->cIoReqsActive);
3444
3445 rc = drvvdMediaExIoReqReadWriteProcess(pThis, pIoReq, false /* fUpNotify */);
3446 }
3447
3448 return rc;
3449}
3450
3451/**
3452 * @interface_method_impl{PDMIMEDIAEX,pfnIoReqFlush}
3453 */
3454static DECLCALLBACK(int) drvvdIoReqFlush(PPDMIMEDIAEX pInterface, PDMMEDIAEXIOREQ hIoReq)
3455{
3456 PVBOXDISK pThis = RT_FROM_MEMBER(pInterface, VBOXDISK, IMediaEx);
3457 PPDMMEDIAEXIOREQINT pIoReq = hIoReq;
3458 VDIOREQSTATE enmState = (VDIOREQSTATE)ASMAtomicReadU32((volatile uint32_t *)&pIoReq->enmState);
3459
3460 if (RT_UNLIKELY(enmState == VDIOREQSTATE_CANCELED))
3461 return VERR_PDM_MEDIAEX_IOREQ_CANCELED;
3462
3463 if (RT_UNLIKELY(enmState != VDIOREQSTATE_ALLOCATED))
3464 return VERR_PDM_MEDIAEX_IOREQ_INVALID_STATE;
3465
3466 pIoReq->enmType = PDMMEDIAEXIOREQTYPE_FLUSH;
3467 pIoReq->tsSubmit = RTTimeMilliTS();
3468 bool fXchg = ASMAtomicCmpXchgU32((volatile uint32_t *)&pIoReq->enmState, VDIOREQSTATE_ACTIVE, VDIOREQSTATE_ALLOCATED);
3469 if (RT_UNLIKELY(!fXchg))
3470 {
3471 /* Must have been canceled inbetween. */
3472 Assert(pIoReq->enmState == VDIOREQSTATE_CANCELED);
3473 return VERR_PDM_MEDIAEX_IOREQ_CANCELED;
3474 }
3475
3476 ASMAtomicIncU32(&pThis->cIoReqsActive);
3477 int rc = VINF_SUCCESS;
3478 if (pThis->fAsyncIOSupported)
3479 rc = VDAsyncFlush(pThis->pDisk, drvvdMediaExIoReqComplete, pThis, pIoReq);
3480 else
3481 rc = VDFlush(pThis->pDisk);
3482
3483 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
3484 rc = VINF_PDM_MEDIAEX_IOREQ_IN_PROGRESS;
3485 else if (rc == VINF_VD_ASYNC_IO_FINISHED)
3486 rc = VINF_SUCCESS;
3487
3488 if (rc != VINF_PDM_MEDIAEX_IOREQ_IN_PROGRESS)
3489 rc = drvvdMediaExIoReqCompleteWorker(pThis, pIoReq, rc, false /* fUpNotify */);
3490
3491 return rc;
3492}
3493
3494/**
3495 * @interface_method_impl{PDMIMEDIAEX,pfnIoReqDiscard}
3496 */
3497static DECLCALLBACK(int) drvvdIoReqDiscard(PPDMIMEDIAEX pInterface, PDMMEDIAEXIOREQ hIoReq, PCRTRANGE paRanges, unsigned cRanges)
3498{
3499 PVBOXDISK pThis = RT_FROM_MEMBER(pInterface, VBOXDISK, IMediaEx);
3500 PPDMMEDIAEXIOREQINT pIoReq = hIoReq;
3501 VDIOREQSTATE enmState = (VDIOREQSTATE)ASMAtomicReadU32((volatile uint32_t *)&pIoReq->enmState);
3502
3503 if (RT_UNLIKELY(enmState == VDIOREQSTATE_CANCELED))
3504 return VERR_PDM_MEDIAEX_IOREQ_CANCELED;
3505
3506 if (RT_UNLIKELY(enmState != VDIOREQSTATE_ALLOCATED))
3507 return VERR_PDM_MEDIAEX_IOREQ_INVALID_STATE;
3508
3509 pIoReq->enmType = PDMMEDIAEXIOREQTYPE_DISCARD;
3510 pIoReq->tsSubmit = RTTimeMilliTS();
3511 /* Copy the ranges over because they might not be valid anymore when this method returns. */
3512 pIoReq->Discard.paRanges = (PRTRANGE)RTMemDup(paRanges, cRanges * sizeof(RTRANGE));
3513 if (RT_UNLIKELY(!pIoReq->Discard.paRanges))
3514 return VERR_NO_MEMORY;
3515
3516 bool fXchg = ASMAtomicCmpXchgU32((volatile uint32_t *)&pIoReq->enmState, VDIOREQSTATE_ACTIVE, VDIOREQSTATE_ALLOCATED);
3517 if (RT_UNLIKELY(!fXchg))
3518 {
3519 /* Must have been canceled inbetween. */
3520 Assert(pIoReq->enmState == VDIOREQSTATE_CANCELED);
3521 return VERR_PDM_MEDIAEX_IOREQ_CANCELED;
3522 }
3523
3524 ASMAtomicIncU32(&pThis->cIoReqsActive);
3525 int rc = VDAsyncDiscardRanges(pThis->pDisk, paRanges, cRanges,
3526 drvvdMediaExIoReqComplete, pThis, pIoReq);
3527 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
3528 rc = VINF_PDM_MEDIAEX_IOREQ_IN_PROGRESS;
3529 else if (rc == VINF_VD_ASYNC_IO_FINISHED)
3530 rc = VINF_SUCCESS;
3531
3532 if (rc != VINF_PDM_MEDIAEX_IOREQ_IN_PROGRESS)
3533 rc = drvvdMediaExIoReqCompleteWorker(pThis, pIoReq, rc, false /* fUpNotify */);
3534
3535 return rc;
3536}
3537
3538/**
3539 * @interface_method_impl{PDMIMEDIAEX,pfnIoReqGetActiveCount}
3540 */
3541static DECLCALLBACK(uint32_t) drvvdIoReqGetActiveCount(PPDMIMEDIAEX pInterface)
3542{
3543 PVBOXDISK pThis = RT_FROM_MEMBER(pInterface, VBOXDISK, IMediaEx);
3544 return ASMAtomicReadU32(&pThis->cIoReqsActive);
3545}
3546
3547/**
3548 * @interface_method_impl{PDMIMEDIAEX,pfnIoReqGetSuspendedCount}
3549 */
3550static DECLCALLBACK(uint32_t) drvvdIoReqGetSuspendedCount(PPDMIMEDIAEX pInterface)
3551{
3552 PVBOXDISK pThis = RT_FROM_MEMBER(pInterface, VBOXDISK, IMediaEx);
3553
3554 AssertReturn(!drvvdMediaExIoReqIsVmRunning(pThis), 0);
3555
3556 uint32_t cIoReqSuspended = 0;
3557 PPDMMEDIAEXIOREQINT pIoReq;
3558 RTCritSectEnter(&pThis->CritSectIoReqRedo);
3559 RTListForEach(&pThis->LstIoReqRedo, pIoReq, PDMMEDIAEXIOREQINT, NdLstWait)
3560 {
3561 cIoReqSuspended++;
3562 }
3563 RTCritSectLeave(&pThis->CritSectIoReqRedo);
3564
3565 return cIoReqSuspended;
3566}
3567
3568/**
3569 * @interface_method_impl{PDMIMEDIAEX,pfnIoReqQuerySuspendedFirst}
3570 */
3571static DECLCALLBACK(int) drvvdIoReqQuerySuspendedStart(PPDMIMEDIAEX pInterface, PPDMMEDIAEXIOREQ phIoReq,
3572 void **ppvIoReqAlloc)
3573{
3574 PVBOXDISK pThis = RT_FROM_MEMBER(pInterface, VBOXDISK, IMediaEx);
3575
3576 AssertReturn(!drvvdMediaExIoReqIsVmRunning(pThis), VERR_INVALID_STATE);
3577 AssertReturn(!RTListIsEmpty(&pThis->LstIoReqRedo), VERR_NOT_FOUND);
3578
3579 RTCritSectEnter(&pThis->CritSectIoReqRedo);
3580 PPDMMEDIAEXIOREQINT pIoReq = RTListGetFirst(&pThis->LstIoReqRedo, PDMMEDIAEXIOREQINT, NdLstWait);
3581 *phIoReq = pIoReq;
3582 *ppvIoReqAlloc = &pIoReq->abAlloc[0];
3583 RTCritSectLeave(&pThis->CritSectIoReqRedo);
3584
3585 return VINF_SUCCESS;
3586}
3587
3588/**
3589 * @interface_method_impl{PDMIMEDIAEX,pfnIoReqQuerySuspendedNext}
3590 */
3591static DECLCALLBACK(int) drvvdIoReqQuerySuspendedNext(PPDMIMEDIAEX pInterface, PDMMEDIAEXIOREQ hIoReq,
3592 PPDMMEDIAEXIOREQ phIoReqNext, void **ppvIoReqAllocNext)
3593{
3594 PVBOXDISK pThis = RT_FROM_MEMBER(pInterface, VBOXDISK, IMediaEx);
3595 PPDMMEDIAEXIOREQINT pIoReq = hIoReq;
3596
3597 AssertReturn(!drvvdMediaExIoReqIsVmRunning(pThis), VERR_INVALID_STATE);
3598 AssertPtrReturn(pIoReq, VERR_INVALID_HANDLE);
3599 AssertReturn(!RTListNodeIsLast(&pThis->LstIoReqRedo, &pIoReq->NdLstWait), VERR_NOT_FOUND);
3600
3601 RTCritSectEnter(&pThis->CritSectIoReqRedo);
3602 PPDMMEDIAEXIOREQINT pIoReqNext = RTListNodeGetNext(&pIoReq->NdLstWait, PDMMEDIAEXIOREQINT, NdLstWait);
3603 *phIoReqNext = pIoReqNext;
3604 *ppvIoReqAllocNext = &pIoReqNext->abAlloc[0];
3605 RTCritSectLeave(&pThis->CritSectIoReqRedo);
3606
3607 return VINF_SUCCESS;
3608}
3609
3610/**
3611 * @interface_method_impl{PDMIMEDIAEX,pfnIoReqSuspendedSave}
3612 */
3613static DECLCALLBACK(int) drvvdIoReqSuspendedSave(PPDMIMEDIAEX pInterface, PSSMHANDLE pSSM, PDMMEDIAEXIOREQ hIoReq)
3614{
3615 PVBOXDISK pThis = RT_FROM_MEMBER(pInterface, VBOXDISK, IMediaEx);
3616 PPDMMEDIAEXIOREQINT pIoReq = hIoReq;
3617
3618 AssertReturn(!drvvdMediaExIoReqIsVmRunning(pThis), VERR_INVALID_STATE);
3619 AssertPtrReturn(pIoReq, VERR_INVALID_HANDLE);
3620 AssertReturn(pIoReq->enmState == VDIOREQSTATE_SUSPENDED, VERR_INVALID_STATE);
3621
3622 SSMR3PutU32(pSSM, DRVVD_IOREQ_SAVED_STATE_VERSION);
3623 SSMR3PutU32(pSSM, (uint32_t)pIoReq->enmType);
3624 SSMR3PutU32(pSSM, pIoReq->uIoReqId);
3625 SSMR3PutU32(pSSM, pIoReq->fFlags);
3626 if ( pIoReq->enmType == PDMMEDIAEXIOREQTYPE_READ
3627 || pIoReq->enmType == PDMMEDIAEXIOREQTYPE_WRITE)
3628 {
3629 SSMR3PutU64(pSSM, pIoReq->ReadWrite.offStart);
3630 SSMR3PutU64(pSSM, pIoReq->ReadWrite.cbReq);
3631 SSMR3PutU64(pSSM, pIoReq->ReadWrite.cbReqLeft);
3632 }
3633 else if (pIoReq->enmType == PDMMEDIAEXIOREQTYPE_DISCARD)
3634 {
3635 SSMR3PutU32(pSSM, pIoReq->Discard.cRanges);
3636 for (unsigned i = 0; i < pIoReq->Discard.cRanges; i++)
3637 {
3638 SSMR3PutU64(pSSM, pIoReq->Discard.paRanges[i].offStart);
3639 SSMR3PutU64(pSSM, pIoReq->Discard.paRanges[i].cbRange);
3640 }
3641 }
3642
3643 return SSMR3PutU32(pSSM, UINT32_MAX); /* sanity/terminator */
3644}
3645
3646/**
3647 * @interface_method_impl{PDMIMEDIAEX,pfnIoReqSuspendedLoad}
3648 */
3649static DECLCALLBACK(int) drvvdIoReqSuspendedLoad(PPDMIMEDIAEX pInterface, PSSMHANDLE pSSM, PDMMEDIAEXIOREQ hIoReq)
3650{
3651 PVBOXDISK pThis = RT_FROM_MEMBER(pInterface, VBOXDISK, IMediaEx);
3652 PPDMMEDIAEXIOREQINT pIoReq = hIoReq;
3653
3654 AssertReturn(!drvvdMediaExIoReqIsVmRunning(pThis), VERR_INVALID_STATE);
3655 AssertPtrReturn(pIoReq, VERR_INVALID_HANDLE);
3656 AssertReturn(pIoReq->enmState == VDIOREQSTATE_ALLOCATED, VERR_INVALID_STATE);
3657
3658 uint32_t u32;
3659 uint64_t u64;
3660 int rc = VINF_SUCCESS;
3661 bool fPlaceOnRedoList = true;
3662
3663 SSMR3GetU32(pSSM, &u32);
3664 if (u32 <= DRVVD_IOREQ_SAVED_STATE_VERSION)
3665 {
3666 SSMR3GetU32(pSSM, &u32);
3667 AssertReturn( u32 == PDMMEDIAEXIOREQTYPE_WRITE
3668 || u32 == PDMMEDIAEXIOREQTYPE_READ
3669 || u32 == PDMMEDIAEXIOREQTYPE_DISCARD
3670 || u32 == PDMMEDIAEXIOREQTYPE_FLUSH,
3671 VERR_SSM_DATA_UNIT_FORMAT_CHANGED);
3672 pIoReq->enmType = (PDMMEDIAEXIOREQTYPE)u32;
3673
3674 SSMR3GetU32(pSSM, &u32);
3675 AssertReturn(u32 == pIoReq->uIoReqId, VERR_SSM_DATA_UNIT_FORMAT_CHANGED);
3676
3677 SSMR3GetU32(pSSM, &u32);
3678 AssertReturn(u32 == pIoReq->fFlags, VERR_SSM_DATA_UNIT_FORMAT_CHANGED);
3679
3680 if ( pIoReq->enmType == PDMMEDIAEXIOREQTYPE_READ
3681 || pIoReq->enmType == PDMMEDIAEXIOREQTYPE_WRITE)
3682 {
3683 SSMR3GetU64(pSSM, &pIoReq->ReadWrite.offStart);
3684 SSMR3GetU64(pSSM, &u64);
3685 pIoReq->ReadWrite.cbReq = (size_t)u64;
3686 SSMR3GetU64(pSSM, &u64);
3687 pIoReq->ReadWrite.cbReqLeft = (size_t)u64;
3688
3689 /*
3690 * Try to allocate enough I/O buffer, if this fails for some reason put it onto the
3691 * waitign list instead of the redo list.
3692 */
3693 pIoReq->ReadWrite.cbIoBuf = 0;
3694 rc = IOBUFMgrAllocBuf(pThis->hIoBufMgr, &pIoReq->ReadWrite.IoBuf, pIoReq->ReadWrite.cbReqLeft,
3695 &pIoReq->ReadWrite.cbIoBuf);
3696 if (rc == VERR_NO_MEMORY)
3697 {
3698 pIoReq->enmState = VDIOREQSTATE_ALLOCATED;
3699 ASMAtomicIncU32(&pThis->cIoReqsWaiting);
3700 RTListAppend(&pThis->LstIoReqIoBufWait, &pIoReq->NdLstWait);
3701 fPlaceOnRedoList = false;
3702 rc = VINF_SUCCESS;
3703 }
3704 }
3705 else if (pIoReq->enmType == PDMMEDIAEXIOREQTYPE_DISCARD)
3706 {
3707 rc = SSMR3GetU32(pSSM, &pIoReq->Discard.cRanges);
3708 if (RT_SUCCESS(rc))
3709 {
3710 pIoReq->Discard.paRanges = (PRTRANGE)RTMemAllocZ(pIoReq->Discard.cRanges * sizeof(RTRANGE));
3711 if (RT_LIKELY(pIoReq->Discard.paRanges))
3712 {
3713 for (unsigned i = 0; i < pIoReq->Discard.cRanges; i++)
3714 {
3715 SSMR3GetU64(pSSM, &pIoReq->Discard.paRanges[i].offStart);
3716 SSMR3GetU64(pSSM, &u64);
3717 pIoReq->Discard.paRanges[i].cbRange = (size_t)u64;
3718 }
3719 }
3720 else
3721 rc = VERR_NO_MEMORY;
3722 }
3723 }
3724
3725 if (RT_SUCCESS(rc))
3726 rc = SSMR3GetU32(pSSM, &u32); /* sanity/terminator */
3727 if (RT_SUCCESS(rc))
3728 AssertReturn(u32 == UINT32_MAX, VERR_SSM_DATA_UNIT_FORMAT_CHANGED);
3729 if ( RT_SUCCESS(rc)
3730 && fPlaceOnRedoList)
3731 {
3732 /* Mark as suspended */
3733 pIoReq->enmState = VDIOREQSTATE_SUSPENDED;
3734
3735 /* Link into suspended list so it gets kicked off again when we resume. */
3736 RTCritSectEnter(&pThis->CritSectIoReqRedo);
3737 RTListAppend(&pThis->LstIoReqRedo, &pIoReq->NdLstWait);
3738 RTCritSectLeave(&pThis->CritSectIoReqRedo);
3739 }
3740 }
3741
3742 return rc;
3743}
3744
3745/**
3746 * Loads all configured plugins.
3747 *
3748 * @returns VBox status code.
3749 * @param pCfg CFGM node holding plugin list.
3750 */
3751static int drvvdLoadPlugins(PCFGMNODE pCfg)
3752{
3753 PCFGMNODE pCfgPlugins = CFGMR3GetChild(pCfg, "Plugins");
3754
3755 if (pCfgPlugins)
3756 {
3757 PCFGMNODE pPluginCur = CFGMR3GetFirstChild(pCfgPlugins);
3758 while (pPluginCur)
3759 {
3760 int rc = VINF_SUCCESS;
3761 char *pszPluginFilename = NULL;
3762 rc = CFGMR3QueryStringAlloc(pPluginCur, "Path", &pszPluginFilename);
3763 if (RT_SUCCESS(rc))
3764 rc = VDPluginLoadFromFilename(pszPluginFilename);
3765
3766 if (RT_FAILURE(rc))
3767 LogRel(("VD: Failed to load plugin '%s' with %Rrc, continuing\n", pszPluginFilename, rc));
3768
3769 pPluginCur = CFGMR3GetNextChild(pPluginCur);
3770 }
3771 }
3772
3773 return VINF_SUCCESS;
3774}
3775
3776
3777/**
3778 * Sets up the disk filter chain.
3779 *
3780 * @returns VBox status code.
3781 * @param pThis The disk instance.
3782 * @param pCfg CFGM node holding the filter parameters.
3783 */
3784static int drvvdSetupFilters(PVBOXDISK pThis, PCFGMNODE pCfg)
3785{
3786 int rc = VINF_SUCCESS;
3787 PCFGMNODE pCfgFilter = CFGMR3GetChild(pCfg, "Filters");
3788
3789 if (pCfgFilter)
3790 {
3791 PCFGMNODE pCfgFilterConfig = CFGMR3GetChild(pCfgFilter, "VDConfig");
3792 char *pszFilterName = NULL;
3793 VDINTERFACECONFIG VDIfConfig;
3794 PVDINTERFACE pVDIfsFilter = NULL;
3795
3796 rc = CFGMR3QueryStringAlloc(pCfgFilter, "FilterName", &pszFilterName);
3797 if (RT_SUCCESS(rc))
3798 {
3799 VDIfConfig.pfnAreKeysValid = drvvdCfgAreKeysValid;
3800 VDIfConfig.pfnQuerySize = drvvdCfgQuerySize;
3801 VDIfConfig.pfnQuery = drvvdCfgQuery;
3802 VDIfConfig.pfnQueryBytes = drvvdCfgQueryBytes;
3803 rc = VDInterfaceAdd(&VDIfConfig.Core, "DrvVD_Config", VDINTERFACETYPE_CONFIG,
3804 pCfgFilterConfig, sizeof(VDINTERFACECONFIG), &pVDIfsFilter);
3805 AssertRC(rc);
3806
3807 rc = VDFilterAdd(pThis->pDisk, pszFilterName, VD_FILTER_FLAGS_DEFAULT, pVDIfsFilter);
3808
3809 MMR3HeapFree(pszFilterName);
3810 }
3811 }
3812
3813 return rc;
3814}
3815
3816
3817/**
3818 * Translates a PDMMEDIATYPE value into a string.
3819 *
3820 * @returns Read only string.
3821 * @param enmType The type value.
3822 */
3823static const char *drvvdGetTypeName(PDMMEDIATYPE enmType)
3824{
3825 switch (enmType)
3826 {
3827 case PDMMEDIATYPE_ERROR: return "ERROR";
3828 case PDMMEDIATYPE_FLOPPY_360: return "FLOPPY_360";
3829 case PDMMEDIATYPE_FLOPPY_720: return "FLOPPY_720";
3830 case PDMMEDIATYPE_FLOPPY_1_20: return "FLOPPY_1_20";
3831 case PDMMEDIATYPE_FLOPPY_1_44: return "FLOPPY_1_44";
3832 case PDMMEDIATYPE_FLOPPY_2_88: return "FLOPPY_2_88";
3833 case PDMMEDIATYPE_FLOPPY_FAKE_15_6: return "FLOPPY_FAKE_15_6";
3834 case PDMMEDIATYPE_FLOPPY_FAKE_63_5: return "FLOPPY_FAKE_63_5";
3835 case PDMMEDIATYPE_CDROM: return "CDROM";
3836 case PDMMEDIATYPE_DVD: return "DVD";
3837 case PDMMEDIATYPE_HARD_DISK: return "HARD_DISK";
3838 default: return "Unknown";
3839 }
3840}
3841
3842/**
3843 * Returns the appropriate PDMMEDIATYPE for t he given string.
3844 *
3845 * @returns PDMMEDIATYPE
3846 * @param pszType The string representation of the media type.
3847 */
3848static PDMMEDIATYPE drvvdGetMediaTypeFromString(const char *pszType)
3849{
3850 PDMMEDIATYPE enmType = PDMMEDIATYPE_ERROR;
3851
3852 if (!strcmp(pszType, "HardDisk"))
3853 enmType = PDMMEDIATYPE_HARD_DISK;
3854 else if (!strcmp(pszType, "DVD"))
3855 enmType = PDMMEDIATYPE_DVD;
3856 else if (!strcmp(pszType, "CDROM"))
3857 enmType = PDMMEDIATYPE_CDROM;
3858 else if (!strcmp(pszType, "Floppy 2.88"))
3859 enmType = PDMMEDIATYPE_FLOPPY_2_88;
3860 else if (!strcmp(pszType, "Floppy 1.44"))
3861 enmType = PDMMEDIATYPE_FLOPPY_1_44;
3862 else if (!strcmp(pszType, "Floppy 1.20"))
3863 enmType = PDMMEDIATYPE_FLOPPY_1_20;
3864 else if (!strcmp(pszType, "Floppy 720"))
3865 enmType = PDMMEDIATYPE_FLOPPY_720;
3866 else if (!strcmp(pszType, "Floppy 360"))
3867 enmType = PDMMEDIATYPE_FLOPPY_360;
3868 else if (!strcmp(pszType, "Floppy 15.6"))
3869 enmType = PDMMEDIATYPE_FLOPPY_FAKE_15_6;
3870 else if (!strcmp(pszType, "Floppy 63.5"))
3871 enmType = PDMMEDIATYPE_FLOPPY_FAKE_63_5;
3872
3873 return enmType;
3874}
3875
3876/**
3877 * Converts PDMMEDIATYPE to the appropriate VDTYPE.
3878 *
3879 * @returns The VDTYPE.
3880 * @param enmType The PDMMEDIATYPE to convert from.
3881 */
3882static VDTYPE drvvdGetVDFromMediaType(PDMMEDIATYPE enmType)
3883{
3884 if (PDMMEDIATYPE_IS_FLOPPY(enmType))
3885 return VDTYPE_FLOPPY;
3886 else if (enmType == PDMMEDIATYPE_DVD || enmType == PDMMEDIATYPE_CDROM)
3887 return VDTYPE_DVD;
3888 else if (enmType == PDMMEDIATYPE_HARD_DISK)
3889 return VDTYPE_HDD;
3890
3891 AssertMsgFailed(("Invalid media type %d{%s} given!\n", enmType, drvvdGetTypeName(enmType)));
3892 return VDTYPE_HDD;
3893}
3894
3895
3896/*********************************************************************************************************************************
3897* Base interface methods *
3898*********************************************************************************************************************************/
3899
3900/**
3901 * @interface_method_impl{PDMIBASE,pfnQueryInterface}
3902 */
3903static DECLCALLBACK(void *) drvvdQueryInterface(PPDMIBASE pInterface, const char *pszIID)
3904{
3905 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
3906 PVBOXDISK pThis = PDMINS_2_DATA(pDrvIns, PVBOXDISK);
3907
3908 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pDrvIns->IBase);
3909 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIMEDIA, &pThis->IMedia);
3910 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIMOUNT, pThis->fMountable ? &pThis->IMount : NULL);
3911 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIMEDIAASYNC, pThis->fAsyncIOSupported ? &pThis->IMediaAsync : NULL);
3912 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIMEDIAEX, pThis->pDrvMediaExPort ? &pThis->IMediaEx : NULL);
3913 return NULL;
3914}
3915
3916
3917/*********************************************************************************************************************************
3918* Saved state notification methods *
3919*********************************************************************************************************************************/
3920
3921/**
3922 * Load done callback for re-opening the image writable during teleportation.
3923 *
3924 * This is called both for successful and failed load runs, we only care about
3925 * successful ones.
3926 *
3927 * @returns VBox status code.
3928 * @param pDrvIns The driver instance.
3929 * @param pSSM The saved state handle.
3930 */
3931static DECLCALLBACK(int) drvvdLoadDone(PPDMDRVINS pDrvIns, PSSMHANDLE pSSM)
3932{
3933 PVBOXDISK pThis = PDMINS_2_DATA(pDrvIns, PVBOXDISK);
3934 Assert(!pThis->fErrorUseRuntime);
3935
3936 /* Drop out if we don't have any work to do or if it's a failed load. */
3937 if ( !pThis->fTempReadOnly
3938 || RT_FAILURE(SSMR3HandleGetStatus(pSSM)))
3939 return VINF_SUCCESS;
3940
3941 int rc = drvvdSetWritable(pThis);
3942 if (RT_FAILURE(rc)) /** @todo does the bugger set any errors? */
3943 return SSMR3SetLoadError(pSSM, rc, RT_SRC_POS,
3944 N_("Failed to write lock the images"));
3945 return VINF_SUCCESS;
3946}
3947
3948
3949/*********************************************************************************************************************************
3950* Driver methods *
3951*********************************************************************************************************************************/
3952
3953/**
3954 * Worker for the power off or destruct callback.
3955 *
3956 * @returns nothing.
3957 * @param pDrvIns The driver instance.
3958 */
3959static void drvvdPowerOffOrDestructOrUnmount(PPDMDRVINS pDrvIns)
3960{
3961 PVBOXDISK pThis = PDMINS_2_DATA(pDrvIns, PVBOXDISK);
3962 LogFlowFunc(("\n"));
3963
3964 RTSEMFASTMUTEX mutex;
3965 ASMAtomicXchgHandle(&pThis->MergeCompleteMutex, NIL_RTSEMFASTMUTEX, &mutex);
3966 if (mutex != NIL_RTSEMFASTMUTEX)
3967 {
3968 /* Request the semaphore to wait until a potentially running merge
3969 * operation has been finished. */
3970 int rc = RTSemFastMutexRequest(mutex);
3971 AssertRC(rc);
3972 pThis->fMergePending = false;
3973 rc = RTSemFastMutexRelease(mutex);
3974 AssertRC(rc);
3975 rc = RTSemFastMutexDestroy(mutex);
3976 AssertRC(rc);
3977 }
3978
3979 if (RT_VALID_PTR(pThis->pBlkCache))
3980 {
3981 PDMR3BlkCacheRelease(pThis->pBlkCache);
3982 pThis->pBlkCache = NULL;
3983 }
3984
3985 if (RT_VALID_PTR(pThis->pDisk))
3986 {
3987 VDDestroy(pThis->pDisk);
3988 pThis->pDisk = NULL;
3989 }
3990 drvvdFreeImages(pThis);
3991}
3992
3993/**
3994 * @copydoc FNPDMDRVPOWEROFF
3995 */
3996static DECLCALLBACK(void) drvvdPowerOff(PPDMDRVINS pDrvIns)
3997{
3998 PDMDRV_CHECK_VERSIONS_RETURN_VOID(pDrvIns);
3999 drvvdPowerOffOrDestructOrUnmount(pDrvIns);
4000}
4001
4002/**
4003 * @callback_method_impl{FNPDMDRVRESUME}
4004 *
4005 * VM resume notification that we use to undo what the temporary read-only image
4006 * mode set by drvvdSuspend.
4007 *
4008 * Also switch to runtime error mode if we're resuming after a state load
4009 * without having been powered on first.
4010 *
4011 * @todo The VMSetError vs VMSetRuntimeError mess must be fixed elsewhere,
4012 * we're making assumptions about Main behavior here!
4013 */
4014static DECLCALLBACK(void) drvvdResume(PPDMDRVINS pDrvIns)
4015{
4016 LogFlowFunc(("\n"));
4017 PVBOXDISK pThis = PDMINS_2_DATA(pDrvIns, PVBOXDISK);
4018
4019 drvvdSetWritable(pThis);
4020 pThis->fErrorUseRuntime = true;
4021
4022 if (pThis->pBlkCache)
4023 {
4024 int rc = PDMR3BlkCacheResume(pThis->pBlkCache);
4025 AssertRC(rc);
4026 }
4027
4028 if (pThis->pDrvMediaExPort)
4029 {
4030 /* Kick of any request we have to redo. */
4031 PPDMMEDIAEXIOREQINT pIoReq, pIoReqNext;
4032 RTCritSectEnter(&pThis->CritSectIoReqRedo);
4033 RTListForEachSafe(&pThis->LstIoReqRedo, pIoReq, pIoReqNext, PDMMEDIAEXIOREQINT, NdLstWait)
4034 {
4035 int rc = VINF_SUCCESS;
4036 bool fXchg = ASMAtomicCmpXchgU32((volatile uint32_t *)&pIoReq->enmState, VDIOREQSTATE_ACTIVE, VDIOREQSTATE_SUSPENDED);
4037
4038 RTListNodeRemove(&pIoReq->NdLstWait);
4039 ASMAtomicIncU32(&pThis->cIoReqsActive);
4040
4041 if (fXchg)
4042 {
4043 pThis->pDrvMediaExPort->pfnIoReqStateChanged(pThis->pDrvMediaExPort, pIoReq, &pIoReq->abAlloc[0],
4044 PDMMEDIAEXIOREQSTATE_ACTIVE);
4045 if ( pIoReq->enmType == PDMMEDIAEXIOREQTYPE_READ
4046 || pIoReq->enmType == PDMMEDIAEXIOREQTYPE_WRITE)
4047 rc = drvvdMediaExIoReqReadWriteProcess(pThis, pIoReq, false /* fUpNotify */);
4048 else if (pIoReq->enmType == PDMMEDIAEXIOREQTYPE_FLUSH)
4049 {
4050 rc = VDAsyncFlush(pThis->pDisk, drvvdMediaExIoReqComplete, pThis, pIoReq);
4051 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
4052 rc = VINF_PDM_MEDIAEX_IOREQ_IN_PROGRESS;
4053 else if (rc == VINF_VD_ASYNC_IO_FINISHED)
4054 rc = VINF_SUCCESS;
4055 }
4056 else if (pIoReq->enmType == PDMMEDIAEXIOREQTYPE_DISCARD)
4057 {
4058 rc = VDAsyncDiscardRanges(pThis->pDisk, pIoReq->Discard.paRanges, pIoReq->Discard.cRanges,
4059 drvvdMediaExIoReqComplete, pThis, pIoReq);
4060 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
4061 rc = VINF_PDM_MEDIAEX_IOREQ_IN_PROGRESS;
4062 else if (rc == VINF_VD_ASYNC_IO_FINISHED)
4063 rc = VINF_SUCCESS;
4064 }
4065 else
4066 AssertMsgFailed(("Invalid request type %u\n", pIoReq->enmType));
4067
4068 if (rc != VINF_PDM_MEDIAEX_IOREQ_IN_PROGRESS)
4069 {
4070 Assert( ( pIoReq->enmType != PDMMEDIAEXIOREQTYPE_WRITE
4071 && pIoReq->enmType != PDMMEDIAEXIOREQTYPE_READ)
4072 || !pIoReq->ReadWrite.cbReqLeft
4073 || RT_FAILURE(rc));
4074 drvvdMediaExIoReqCompleteWorker(pThis, pIoReq, rc, true /* fUpNotify */);
4075 }
4076
4077 }
4078 else
4079 {
4080 /* Request was canceled inbetween, so don't care and notify the owner about the completed request. */
4081 Assert(pIoReq->enmState == VDIOREQSTATE_CANCELED);
4082 drvvdMediaExIoReqCompleteWorker(pThis, pIoReq, VERR_PDM_MEDIAEX_IOREQ_CANCELED, true /* fUpNotify */);
4083 }
4084 }
4085 Assert(RTListIsEmpty(&pThis->LstIoReqRedo));
4086 RTCritSectLeave(&pThis->CritSectIoReqRedo);
4087 }
4088}
4089
4090/**
4091 * @callback_method_impl{FNPDMDRVSUSPEND}
4092 *
4093 * When the VM is being suspended, temporarily change to read-only image mode.
4094 *
4095 * This is important for several reasons:
4096 * -# It makes sure that there are no pending writes to the image. Most
4097 * backends implements this by closing and reopening the image in read-only
4098 * mode.
4099 * -# It allows Main to read the images during snapshotting without having
4100 * to account for concurrent writes.
4101 * -# This is essential for making teleportation targets sharing images work
4102 * right. Both with regards to caching and with regards to file sharing
4103 * locks (RTFILE_O_DENY_*). (See also drvvdLoadDone.)
4104 */
4105static DECLCALLBACK(void) drvvdSuspend(PPDMDRVINS pDrvIns)
4106{
4107 LogFlowFunc(("\n"));
4108 PVBOXDISK pThis = PDMINS_2_DATA(pDrvIns, PVBOXDISK);
4109
4110 if (pThis->pBlkCache)
4111 {
4112 int rc = PDMR3BlkCacheSuspend(pThis->pBlkCache);
4113 AssertRC(rc);
4114 }
4115
4116 drvvdSetReadonly(pThis);
4117}
4118
4119/**
4120 * @callback_method_impl{FNPDMDRVPOWERON}
4121 */
4122static DECLCALLBACK(void) drvvdPowerOn(PPDMDRVINS pDrvIns)
4123{
4124 LogFlowFunc(("\n"));
4125 PVBOXDISK pThis = PDMINS_2_DATA(pDrvIns, PVBOXDISK);
4126 drvvdSetWritable(pThis);
4127 pThis->fErrorUseRuntime = true;
4128}
4129
4130/**
4131 * @callback_method_impl{FNPDMDRVRESET}
4132 */
4133static DECLCALLBACK(void) drvvdReset(PPDMDRVINS pDrvIns)
4134{
4135 LogFlowFunc(("\n"));
4136 PVBOXDISK pThis = PDMINS_2_DATA(pDrvIns, PVBOXDISK);
4137
4138 if (pThis->pBlkCache)
4139 {
4140 int rc = PDMR3BlkCacheClear(pThis->pBlkCache);
4141 AssertRC(rc);
4142 }
4143
4144 if (pThis->fBootAccelEnabled)
4145 {
4146 pThis->fBootAccelActive = true;
4147 pThis->cbDataValid = 0;
4148 pThis->offDisk = 0;
4149 }
4150}
4151
4152/**
4153 * @callback_method_impl{FNPDMDRVDESTRUCT}
4154 */
4155static DECLCALLBACK(void) drvvdDestruct(PPDMDRVINS pDrvIns)
4156{
4157 PDMDRV_CHECK_VERSIONS_RETURN_VOID(pDrvIns);
4158 PVBOXDISK pThis = PDMINS_2_DATA(pDrvIns, PVBOXDISK);
4159 LogFlowFunc(("\n"));
4160
4161 /*
4162 * Make sure the block cache and disks are closed when this driver is
4163 * destroyed. This method will get called without calling the power off
4164 * callback first when we reconfigure the driver chain after a snapshot.
4165 */
4166 drvvdPowerOffOrDestructOrUnmount(pDrvIns);
4167 if (pThis->MergeLock != NIL_RTSEMRW)
4168 {
4169 int rc = RTSemRWDestroy(pThis->MergeLock);
4170 AssertRC(rc);
4171 pThis->MergeLock = NIL_RTSEMRW;
4172 }
4173 if (pThis->pbData)
4174 {
4175 RTMemFree(pThis->pbData);
4176 pThis->pbData = NULL;
4177 }
4178 if (pThis->pszBwGroup)
4179 {
4180 MMR3HeapFree(pThis->pszBwGroup);
4181 pThis->pszBwGroup = NULL;
4182 }
4183 if (pThis->hHbdMgr != NIL_HBDMGR)
4184 HBDMgrDestroy(pThis->hHbdMgr);
4185 if (pThis->hIoReqCache != NIL_RTMEMCACHE)
4186 RTMemCacheDestroy(pThis->hIoReqCache);
4187 if (pThis->hIoBufMgr != NIL_IOBUFMGR)
4188 IOBUFMgrDestroy(pThis->hIoBufMgr);
4189 if (RTCritSectIsInitialized(&pThis->CritSectIoReqsIoBufWait))
4190 RTCritSectDelete(&pThis->CritSectIoReqsIoBufWait);
4191 if (RTCritSectIsInitialized(&pThis->CritSectIoReqRedo))
4192 RTCritSectDelete(&pThis->CritSectIoReqRedo);
4193 for (unsigned i = 0; i < RT_ELEMENTS(pThis->aIoReqAllocBins); i++)
4194 if (pThis->aIoReqAllocBins[i].hMtxLstIoReqAlloc != NIL_RTSEMFASTMUTEX)
4195 RTSemFastMutexDestroy(pThis->aIoReqAllocBins[i].hMtxLstIoReqAlloc);
4196}
4197
4198/**
4199 * @callback_method_impl{FNPDMDRVCONSTRUCT,
4200 * Construct a VBox disk media driver instance.}
4201 */
4202static DECLCALLBACK(int) drvvdConstruct(PPDMDRVINS pDrvIns, PCFGMNODE pCfg, uint32_t fFlags)
4203{
4204 RT_NOREF(fFlags);
4205 LogFlowFunc(("\n"));
4206 PDMDRV_CHECK_VERSIONS_RETURN(pDrvIns);
4207 PVBOXDISK pThis = PDMINS_2_DATA(pDrvIns, PVBOXDISK);
4208 int rc = VINF_SUCCESS;
4209 char *pszName = NULL; /* The path of the disk image file. */
4210 char *pszFormat = NULL; /* The format backed to use for this image. */
4211 char *pszCachePath = NULL; /* The path to the cache image. */
4212 char *pszCacheFormat = NULL; /* The format backend to use for the cache image. */
4213 bool fReadOnly = false; /* True if the media is read-only. */
4214 bool fMaybeReadOnly = false; /* True if the media may or may not be read-only. */
4215 bool fHonorZeroWrites = false; /* True if zero blocks should be written. */
4216
4217 /*
4218 * Init the static parts.
4219 */
4220 pDrvIns->IBase.pfnQueryInterface = drvvdQueryInterface;
4221 pThis->pDrvIns = pDrvIns;
4222 pThis->fTempReadOnly = false;
4223 pThis->pDisk = NULL;
4224 pThis->fAsyncIOSupported = false;
4225 pThis->fShareable = false;
4226 pThis->fMergePending = false;
4227 pThis->MergeCompleteMutex = NIL_RTSEMFASTMUTEX;
4228 pThis->MergeLock = NIL_RTSEMRW;
4229 pThis->uMergeSource = VD_LAST_IMAGE;
4230 pThis->uMergeTarget = VD_LAST_IMAGE;
4231 pThis->pCfgCrypto = NULL;
4232 pThis->pIfSecKey = NULL;
4233 pThis->hIoReqCache = NIL_RTMEMCACHE;
4234 pThis->hIoBufMgr = NIL_IOBUFMGR;
4235
4236 for (unsigned i = 0; i < RT_ELEMENTS(pThis->aIoReqAllocBins); i++)
4237 pThis->aIoReqAllocBins[i].hMtxLstIoReqAlloc = NIL_RTSEMFASTMUTEX;
4238
4239 /* IMedia */
4240 pThis->IMedia.pfnRead = drvvdRead;
4241 pThis->IMedia.pfnReadPcBios = drvvdReadPcBios;
4242 pThis->IMedia.pfnWrite = drvvdWrite;
4243 pThis->IMedia.pfnFlush = drvvdFlush;
4244 pThis->IMedia.pfnMerge = drvvdMerge;
4245 pThis->IMedia.pfnSetSecKeyIf = drvvdSetSecKeyIf;
4246 pThis->IMedia.pfnGetSize = drvvdGetSize;
4247 pThis->IMedia.pfnGetSectorSize = drvvdGetSectorSize;
4248 pThis->IMedia.pfnIsReadOnly = drvvdIsReadOnly;
4249 pThis->IMedia.pfnBiosGetPCHSGeometry = drvvdBiosGetPCHSGeometry;
4250 pThis->IMedia.pfnBiosSetPCHSGeometry = drvvdBiosSetPCHSGeometry;
4251 pThis->IMedia.pfnBiosGetLCHSGeometry = drvvdBiosGetLCHSGeometry;
4252 pThis->IMedia.pfnBiosSetLCHSGeometry = drvvdBiosSetLCHSGeometry;
4253 pThis->IMedia.pfnBiosIsVisible = drvvdBiosIsVisible;
4254 pThis->IMedia.pfnGetType = drvvdGetType;
4255 pThis->IMedia.pfnGetUuid = drvvdGetUuid;
4256 pThis->IMedia.pfnDiscard = drvvdDiscard;
4257 pThis->IMedia.pfnIoBufAlloc = drvvdIoBufAlloc;
4258 pThis->IMedia.pfnIoBufFree = drvvdIoBufFree;
4259 pThis->IMedia.pfnSendCmd = NULL;
4260
4261 /* IMount */
4262 pThis->IMount.pfnUnmount = drvvdUnmount;
4263 pThis->IMount.pfnIsMounted = drvvdIsMounted;
4264 pThis->IMount.pfnLock = drvvdLock;
4265 pThis->IMount.pfnUnlock = drvvdUnlock;
4266 pThis->IMount.pfnIsLocked = drvvdIsLocked;
4267
4268 /* IMediaAsync */
4269 pThis->IMediaAsync.pfnStartRead = drvvdStartRead;
4270 pThis->IMediaAsync.pfnStartWrite = drvvdStartWrite;
4271 pThis->IMediaAsync.pfnStartFlush = drvvdStartFlush;
4272 pThis->IMediaAsync.pfnStartDiscard = drvvdStartDiscard;
4273
4274 /* IMediaEx */
4275 pThis->IMediaEx.pfnIoReqAllocSizeSet = drvvdIoReqAllocSizeSet;
4276 pThis->IMediaEx.pfnIoReqAlloc = drvvdIoReqAlloc;
4277 pThis->IMediaEx.pfnIoReqFree = drvvdIoReqFree;
4278 pThis->IMediaEx.pfnIoReqCancel = drvvdIoReqCancel;
4279 pThis->IMediaEx.pfnIoReqRead = drvvdIoReqRead;
4280 pThis->IMediaEx.pfnIoReqWrite = drvvdIoReqWrite;
4281 pThis->IMediaEx.pfnIoReqFlush = drvvdIoReqFlush;
4282 pThis->IMediaEx.pfnIoReqDiscard = drvvdIoReqDiscard;
4283 pThis->IMediaEx.pfnIoReqGetActiveCount = drvvdIoReqGetActiveCount;
4284 pThis->IMediaEx.pfnIoReqGetSuspendedCount = drvvdIoReqGetSuspendedCount;
4285 pThis->IMediaEx.pfnIoReqQuerySuspendedStart = drvvdIoReqQuerySuspendedStart;
4286 pThis->IMediaEx.pfnIoReqQuerySuspendedNext = drvvdIoReqQuerySuspendedNext;
4287 pThis->IMediaEx.pfnIoReqSuspendedSave = drvvdIoReqSuspendedSave;
4288 pThis->IMediaEx.pfnIoReqSuspendedLoad = drvvdIoReqSuspendedLoad;
4289
4290 /* Initialize supported VD interfaces. */
4291 pThis->pVDIfsDisk = NULL;
4292
4293 pThis->VDIfError.pfnError = drvvdErrorCallback;
4294 pThis->VDIfError.pfnMessage = NULL;
4295 rc = VDInterfaceAdd(&pThis->VDIfError.Core, "DrvVD_VDIError", VDINTERFACETYPE_ERROR,
4296 pDrvIns, sizeof(VDINTERFACEERROR), &pThis->pVDIfsDisk);
4297 AssertRC(rc);
4298
4299 /* List of images is empty now. */
4300 pThis->pImages = NULL;
4301
4302 pThis->pDrvMediaPort = PDMIBASE_QUERY_INTERFACE(pDrvIns->pUpBase, PDMIMEDIAPORT);
4303 if (!pThis->pDrvMediaPort)
4304 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_MISSING_INTERFACE_ABOVE,
4305 N_("No media port interface above"));
4306
4307 /* Try to attach async media port interface above.*/
4308 pThis->pDrvMediaAsyncPort = PDMIBASE_QUERY_INTERFACE(pDrvIns->pUpBase, PDMIMEDIAASYNCPORT);
4309 pThis->pDrvMountNotify = PDMIBASE_QUERY_INTERFACE(pDrvIns->pUpBase, PDMIMOUNTNOTIFY);
4310
4311 /*
4312 * Try to attach the optional extended media interface port above and initialize associated
4313 * structures if available.
4314 */
4315 pThis->pDrvMediaExPort = PDMIBASE_QUERY_INTERFACE(pDrvIns->pUpBase, PDMIMEDIAEXPORT);
4316 if (pThis->pDrvMediaExPort)
4317 {
4318 for (unsigned i = 0; i < RT_ELEMENTS(pThis->aIoReqAllocBins); i++)
4319 {
4320 rc = RTSemFastMutexCreate(&pThis->aIoReqAllocBins[i].hMtxLstIoReqAlloc);
4321 if (RT_FAILURE(rc))
4322 break;
4323 RTListInit(&pThis->aIoReqAllocBins[i].LstIoReqAlloc);
4324 }
4325
4326 if (RT_SUCCESS(rc))
4327 rc = RTCritSectInit(&pThis->CritSectIoReqsIoBufWait);
4328
4329 if (RT_SUCCESS(rc))
4330 rc = RTCritSectInit(&pThis->CritSectIoReqRedo);
4331
4332 if (RT_FAILURE(rc))
4333 return PDMDRV_SET_ERROR(pDrvIns, rc, N_("Creating Mutex failed"));
4334
4335 RTListInit(&pThis->LstIoReqIoBufWait);
4336 RTListInit(&pThis->LstIoReqRedo);
4337 }
4338
4339 /* Before we access any VD API load all given plugins. */
4340 rc = drvvdLoadPlugins(pCfg);
4341 if (RT_FAILURE(rc))
4342 return PDMDRV_SET_ERROR(pDrvIns, rc, N_("Loading VD plugins failed"));
4343
4344 /*
4345 * Validate configuration and find all parent images.
4346 * It's sort of up side down from the image dependency tree.
4347 */
4348 bool fHostIP = false;
4349 bool fUseNewIo = false;
4350 bool fUseBlockCache = false;
4351 bool fDiscard = false;
4352 bool fInformAboutZeroBlocks = false;
4353 bool fSkipConsistencyChecks = false;
4354 bool fEmptyDrive = false;
4355 unsigned iLevel = 0;
4356 PCFGMNODE pCurNode = pCfg;
4357 uint32_t cbIoBufMax = 0;
4358
4359 for (;;)
4360 {
4361 bool fValid;
4362
4363 if (pCurNode == pCfg)
4364 {
4365 /* Toplevel configuration additionally contains the global image
4366 * open flags. Some might be converted to per-image flags later. */
4367 fValid = CFGMR3AreValuesValid(pCurNode,
4368 "Format\0Path\0"
4369 "ReadOnly\0MaybeReadOnly\0TempReadOnly\0Shareable\0HonorZeroWrites\0"
4370 "HostIPStack\0UseNewIo\0BootAcceleration\0BootAccelerationBuffer\0"
4371 "SetupMerge\0MergeSource\0MergeTarget\0BwGroup\0Type\0BlockCache\0"
4372 "CachePath\0CacheFormat\0Discard\0InformAboutZeroBlocks\0"
4373 "SkipConsistencyChecks\0"
4374 "Locked\0BIOSVisible\0Cylinders\0Heads\0Sectors\0Mountable\0"
4375 "EmptyDrive\0IoBufMax\0"
4376#if defined(VBOX_PERIODIC_FLUSH) || defined(VBOX_IGNORE_FLUSH)
4377 "FlushInterval\0IgnoreFlush\0IgnoreFlushAsync\0"
4378#endif /* !(VBOX_PERIODIC_FLUSH || VBOX_IGNORE_FLUSH) */
4379 );
4380 }
4381 else
4382 {
4383 /* All other image configurations only contain image name and
4384 * the format information. */
4385 fValid = CFGMR3AreValuesValid(pCurNode, "Format\0Path\0"
4386 "MergeSource\0MergeTarget\0");
4387 }
4388 if (!fValid)
4389 {
4390 rc = PDMDrvHlpVMSetError(pDrvIns, VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES,
4391 RT_SRC_POS, N_("DrvVD: Configuration error: keys incorrect at level %d"), iLevel);
4392 break;
4393 }
4394
4395 if (pCurNode == pCfg)
4396 {
4397 rc = CFGMR3QueryBoolDef(pCurNode, "HostIPStack", &fHostIP, true);
4398 if (RT_FAILURE(rc))
4399 {
4400 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
4401 N_("DrvVD: Configuration error: Querying \"HostIPStack\" as boolean failed"));
4402 break;
4403 }
4404
4405 rc = CFGMR3QueryBoolDef(pCurNode, "HonorZeroWrites", &fHonorZeroWrites, false);
4406 if (RT_FAILURE(rc))
4407 {
4408 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
4409 N_("DrvVD: Configuration error: Querying \"HonorZeroWrites\" as boolean failed"));
4410 break;
4411 }
4412
4413 rc = CFGMR3QueryBoolDef(pCurNode, "ReadOnly", &fReadOnly, false);
4414 if (RT_FAILURE(rc))
4415 {
4416 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
4417 N_("DrvVD: Configuration error: Querying \"ReadOnly\" as boolean failed"));
4418 break;
4419 }
4420
4421 rc = CFGMR3QueryBoolDef(pCurNode, "MaybeReadOnly", &fMaybeReadOnly, false);
4422 if (RT_FAILURE(rc))
4423 {
4424 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
4425 N_("DrvVD: Configuration error: Querying \"MaybeReadOnly\" as boolean failed"));
4426 break;
4427 }
4428
4429 rc = CFGMR3QueryBoolDef(pCurNode, "TempReadOnly", &pThis->fTempReadOnly, false);
4430 if (RT_FAILURE(rc))
4431 {
4432 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
4433 N_("DrvVD: Configuration error: Querying \"TempReadOnly\" as boolean failed"));
4434 break;
4435 }
4436 if (fReadOnly && pThis->fTempReadOnly)
4437 {
4438 rc = PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_DRIVER_INVALID_PROPERTIES,
4439 N_("DrvVD: Configuration error: Both \"ReadOnly\" and \"TempReadOnly\" are set"));
4440 break;
4441 }
4442
4443 rc = CFGMR3QueryBoolDef(pCurNode, "Shareable", &pThis->fShareable, false);
4444 if (RT_FAILURE(rc))
4445 {
4446 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
4447 N_("DrvVD: Configuration error: Querying \"Shareable\" as boolean failed"));
4448 break;
4449 }
4450
4451 rc = CFGMR3QueryBoolDef(pCurNode, "UseNewIo", &fUseNewIo, false);
4452 if (RT_FAILURE(rc))
4453 {
4454 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
4455 N_("DrvVD: Configuration error: Querying \"UseNewIo\" as boolean failed"));
4456 break;
4457 }
4458 rc = CFGMR3QueryBoolDef(pCurNode, "SetupMerge", &pThis->fMergePending, false);
4459 if (RT_FAILURE(rc))
4460 {
4461 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
4462 N_("DrvVD: Configuration error: Querying \"SetupMerge\" as boolean failed"));
4463 break;
4464 }
4465 if (fReadOnly && pThis->fMergePending)
4466 {
4467 rc = PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_DRIVER_INVALID_PROPERTIES,
4468 N_("DrvVD: Configuration error: Both \"ReadOnly\" and \"MergePending\" are set"));
4469 break;
4470 }
4471 rc = CFGMR3QueryBoolDef(pCurNode, "BootAcceleration", &pThis->fBootAccelEnabled, false);
4472 if (RT_FAILURE(rc))
4473 {
4474 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
4475 N_("DrvVD: Configuration error: Querying \"BootAcceleration\" as boolean failed"));
4476 break;
4477 }
4478 rc = CFGMR3QueryU32Def(pCurNode, "BootAccelerationBuffer", (uint32_t *)&pThis->cbBootAccelBuffer, 16 * _1K);
4479 if (RT_FAILURE(rc))
4480 {
4481 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
4482 N_("DrvVD: Configuration error: Querying \"BootAccelerationBuffer\" as integer failed"));
4483 break;
4484 }
4485 rc = CFGMR3QueryBoolDef(pCurNode, "BlockCache", &fUseBlockCache, false);
4486 if (RT_FAILURE(rc))
4487 {
4488 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
4489 N_("DrvVD: Configuration error: Querying \"BlockCache\" as boolean failed"));
4490 break;
4491 }
4492 rc = CFGMR3QueryStringAlloc(pCurNode, "BwGroup", &pThis->pszBwGroup);
4493 if (RT_FAILURE(rc) && rc != VERR_CFGM_VALUE_NOT_FOUND)
4494 {
4495 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
4496 N_("DrvVD: Configuration error: Querying \"BwGroup\" as string failed"));
4497 break;
4498 }
4499 else
4500 rc = VINF_SUCCESS;
4501 rc = CFGMR3QueryBoolDef(pCurNode, "Discard", &fDiscard, false);
4502 if (RT_FAILURE(rc))
4503 {
4504 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
4505 N_("DrvVD: Configuration error: Querying \"Discard\" as boolean failed"));
4506 break;
4507 }
4508 if (fReadOnly && fDiscard)
4509 {
4510 rc = PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_DRIVER_INVALID_PROPERTIES,
4511 N_("DrvVD: Configuration error: Both \"ReadOnly\" and \"Discard\" are set"));
4512 break;
4513 }
4514 rc = CFGMR3QueryBoolDef(pCurNode, "InformAboutZeroBlocks", &fInformAboutZeroBlocks, false);
4515 if (RT_FAILURE(rc))
4516 {
4517 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
4518 N_("DrvVD: Configuration error: Querying \"InformAboutZeroBlocks\" as boolean failed"));
4519 break;
4520 }
4521 rc = CFGMR3QueryBoolDef(pCurNode, "SkipConsistencyChecks", &fSkipConsistencyChecks, true);
4522 if (RT_FAILURE(rc))
4523 {
4524 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
4525 N_("DrvVD: Configuration error: Querying \"SKipConsistencyChecks\" as boolean failed"));
4526 break;
4527 }
4528
4529 char *psz = NULL;
4530 rc = CFGMR3QueryStringAlloc(pCfg, "Type", &psz);
4531 if (RT_FAILURE(rc))
4532 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_BLOCK_NO_TYPE, N_("Failed to obtain the sub type"));
4533 pThis->enmType = drvvdGetMediaTypeFromString(psz);
4534 if (pThis->enmType == PDMMEDIATYPE_ERROR)
4535 {
4536 PDMDrvHlpVMSetError(pDrvIns, VERR_PDM_BLOCK_UNKNOWN_TYPE, RT_SRC_POS,
4537 N_("Unknown type \"%s\""), psz);
4538 MMR3HeapFree(psz);
4539 return VERR_PDM_BLOCK_UNKNOWN_TYPE;
4540 }
4541 MMR3HeapFree(psz); psz = NULL;
4542
4543 rc = CFGMR3QueryStringAlloc(pCurNode, "CachePath", &pszCachePath);
4544 if (RT_FAILURE(rc) && rc != VERR_CFGM_VALUE_NOT_FOUND)
4545 {
4546 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
4547 N_("DrvVD: Configuration error: Querying \"CachePath\" as string failed"));
4548 break;
4549 }
4550 else
4551 rc = VINF_SUCCESS;
4552
4553 if (pszCachePath)
4554 {
4555 rc = CFGMR3QueryStringAlloc(pCurNode, "CacheFormat", &pszCacheFormat);
4556 if (RT_FAILURE(rc))
4557 {
4558 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
4559 N_("DrvVD: Configuration error: Querying \"CacheFormat\" as string failed"));
4560 break;
4561 }
4562 }
4563
4564 /* Mountable */
4565 rc = CFGMR3QueryBoolDef(pCfg, "Mountable", &pThis->fMountable, false);
4566 if (RT_FAILURE(rc))
4567 return PDMDRV_SET_ERROR(pDrvIns, rc, N_("Failed to query \"Mountable\" from the config"));
4568
4569 /* Locked */
4570 rc = CFGMR3QueryBoolDef(pCfg, "Locked", &pThis->fLocked, false);
4571 if (RT_FAILURE(rc))
4572 return PDMDRV_SET_ERROR(pDrvIns, rc, N_("Failed to query \"Locked\" from the config"));
4573
4574 /* BIOS visible */
4575 rc = CFGMR3QueryBoolDef(pCfg, "BIOSVisible", &pThis->fBiosVisible, true);
4576 if (RT_FAILURE(rc))
4577 return PDMDRV_SET_ERROR(pDrvIns, rc, N_("Failed to query \"BIOSVisible\" from the config"));
4578
4579 /* Cylinders */
4580 rc = CFGMR3QueryU32Def(pCfg, "Cylinders", &pThis->LCHSGeometry.cCylinders, 0);
4581 if (RT_FAILURE(rc))
4582 return PDMDRV_SET_ERROR(pDrvIns, rc, N_("Failed to query \"Cylinders\" from the config"));
4583
4584 /* Heads */
4585 rc = CFGMR3QueryU32Def(pCfg, "Heads", &pThis->LCHSGeometry.cHeads, 0);
4586 if (RT_FAILURE(rc))
4587 return PDMDRV_SET_ERROR(pDrvIns, rc, N_("Failed to query \"Heads\" from the config"));
4588
4589 /* Sectors */
4590 rc = CFGMR3QueryU32Def(pCfg, "Sectors", &pThis->LCHSGeometry.cSectors, 0);
4591 if (RT_FAILURE(rc))
4592 return PDMDRV_SET_ERROR(pDrvIns, rc, N_("Failed to query \"Sectors\" from the config"));
4593
4594 /* Uuid */
4595 rc = CFGMR3QueryStringAlloc(pCfg, "Uuid", &psz);
4596 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
4597 RTUuidClear(&pThis->Uuid);
4598 else if (RT_SUCCESS(rc))
4599 {
4600 rc = RTUuidFromStr(&pThis->Uuid, psz);
4601 if (RT_FAILURE(rc))
4602 {
4603 PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("Uuid from string failed on \"%s\""), psz);
4604 MMR3HeapFree(psz);
4605 return rc;
4606 }
4607 MMR3HeapFree(psz); psz = NULL;
4608 }
4609 else
4610 return PDMDRV_SET_ERROR(pDrvIns, rc, N_("Failed to query \"Uuid\" from the config"));
4611
4612#ifdef VBOX_PERIODIC_FLUSH
4613 rc = CFGMR3QueryU32Def(pCfg, "FlushInterval", &pThis->cbFlushInterval, 0);
4614 if (RT_FAILURE(rc))
4615 return PDMDRV_SET_ERROR(pDrvIns, rc, N_("Failed to query \"FlushInterval\" from the config"));
4616#endif /* VBOX_PERIODIC_FLUSH */
4617
4618#ifdef VBOX_IGNORE_FLUSH
4619 rc = CFGMR3QueryBoolDef(pCfg, "IgnoreFlush", &pThis->fIgnoreFlush, true);
4620 if (RT_FAILURE(rc))
4621 return PDMDRV_SET_ERROR(pDrvIns, rc, N_("Failed to query \"IgnoreFlush\" from the config"));
4622
4623 if (pThis->fIgnoreFlush)
4624 LogRel(("DrvVD: Flushes will be ignored\n"));
4625 else
4626 LogRel(("DrvVD: Flushes will be passed to the disk\n"));
4627
4628 rc = CFGMR3QueryBoolDef(pCfg, "IgnoreFlushAsync", &pThis->fIgnoreFlushAsync, false);
4629 if (RT_FAILURE(rc))
4630 return PDMDRV_SET_ERROR(pDrvIns, rc, N_("Failed to query \"IgnoreFlushAsync\" from the config"));
4631
4632 if (pThis->fIgnoreFlushAsync)
4633 LogRel(("DrvVD: Async flushes will be ignored\n"));
4634 else
4635 LogRel(("DrvVD: Async flushes will be passed to the disk\n"));
4636#endif /* VBOX_IGNORE_FLUSH */
4637
4638 rc = CFGMR3QueryBoolDef(pCurNode, "EmptyDrive", &fEmptyDrive, false);
4639 if (RT_FAILURE(rc))
4640 {
4641 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
4642 N_("DrvVD: Configuration error: Querying \"EmptyDrive\" as boolean failed"));
4643 break;
4644 }
4645
4646 rc = CFGMR3QueryU32Def(pCfg, "IoBufMax", &cbIoBufMax, 5 * _1M);
4647 if (RT_FAILURE(rc))
4648 return PDMDRV_SET_ERROR(pDrvIns, rc, N_("Failed to query \"IoBufMax\" from the config"));
4649 }
4650
4651 PCFGMNODE pParent = CFGMR3GetChild(pCurNode, "Parent");
4652 if (!pParent)
4653 break;
4654 pCurNode = pParent;
4655 iLevel++;
4656 }
4657
4658 if (pThis->pDrvMediaExPort)
4659 rc = IOBUFMgrCreate(&pThis->hIoBufMgr, cbIoBufMax, pThis->pCfgCrypto ? IOBUFMGR_F_REQUIRE_NOT_PAGABLE : IOBUFMGR_F_DEFAULT);
4660
4661 if ( !fEmptyDrive
4662 && RT_SUCCESS(rc))
4663 {
4664 /*
4665 * Create the image container and the necessary interfaces.
4666 */
4667 if (RT_SUCCESS(rc))
4668 {
4669 /*
4670 * The image has a bandwidth group but the host cache is enabled.
4671 * Use the async I/O framework but tell it to enable the host cache.
4672 */
4673 if (!fUseNewIo && pThis->pszBwGroup)
4674 {
4675 pThis->fAsyncIoWithHostCache = true;
4676 fUseNewIo = true;
4677 }
4678
4679 /** @todo quick hack to work around problems in the async I/O
4680 * implementation (rw semaphore thread ownership problem)
4681 * while a merge is running. Remove once this is fixed. */
4682 if (pThis->fMergePending)
4683 fUseNewIo = false;
4684
4685 if (RT_SUCCESS(rc) && pThis->fMergePending)
4686 {
4687 rc = RTSemFastMutexCreate(&pThis->MergeCompleteMutex);
4688 if (RT_SUCCESS(rc))
4689 rc = RTSemRWCreate(&pThis->MergeLock);
4690 if (RT_SUCCESS(rc))
4691 {
4692 pThis->VDIfThreadSync.pfnStartRead = drvvdThreadStartRead;
4693 pThis->VDIfThreadSync.pfnFinishRead = drvvdThreadFinishRead;
4694 pThis->VDIfThreadSync.pfnStartWrite = drvvdThreadStartWrite;
4695 pThis->VDIfThreadSync.pfnFinishWrite = drvvdThreadFinishWrite;
4696
4697 rc = VDInterfaceAdd(&pThis->VDIfThreadSync.Core, "DrvVD_ThreadSync", VDINTERFACETYPE_THREADSYNC,
4698 pThis, sizeof(VDINTERFACETHREADSYNC), &pThis->pVDIfsDisk);
4699 }
4700 else
4701 {
4702 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
4703 N_("DrvVD: Failed to create semaphores for \"MergePending\""));
4704 }
4705 }
4706
4707 if (RT_SUCCESS(rc))
4708 {
4709 rc = VDCreate(pThis->pVDIfsDisk, drvvdGetVDFromMediaType(pThis->enmType), &pThis->pDisk);
4710 /* Error message is already set correctly. */
4711 }
4712 }
4713
4714 if (pThis->pDrvMediaAsyncPort && fUseNewIo)
4715 pThis->fAsyncIOSupported = true;
4716
4717 uint64_t tsStart = RTTimeNanoTS();
4718
4719 unsigned iImageIdx = 0;
4720 while (pCurNode && RT_SUCCESS(rc))
4721 {
4722 /* Allocate per-image data. */
4723 PVBOXIMAGE pImage = drvvdNewImage(pThis);
4724 if (!pImage)
4725 {
4726 rc = VERR_NO_MEMORY;
4727 break;
4728 }
4729
4730 /*
4731 * Read the image configuration.
4732 */
4733 rc = CFGMR3QueryStringAlloc(pCurNode, "Path", &pszName);
4734 if (RT_FAILURE(rc))
4735 {
4736 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
4737 N_("DrvVD: Configuration error: Querying \"Path\" as string failed"));
4738 break;
4739 }
4740
4741 rc = CFGMR3QueryStringAlloc(pCurNode, "Format", &pszFormat);
4742 if (RT_FAILURE(rc))
4743 {
4744 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
4745 N_("DrvVD: Configuration error: Querying \"Format\" as string failed"));
4746 break;
4747 }
4748
4749 bool fMergeSource;
4750 rc = CFGMR3QueryBoolDef(pCurNode, "MergeSource", &fMergeSource, false);
4751 if (RT_FAILURE(rc))
4752 {
4753 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
4754 N_("DrvVD: Configuration error: Querying \"MergeSource\" as boolean failed"));
4755 break;
4756 }
4757 if (fMergeSource)
4758 {
4759 if (pThis->uMergeSource == VD_LAST_IMAGE)
4760 pThis->uMergeSource = iImageIdx;
4761 else
4762 {
4763 rc = PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_DRIVER_INVALID_PROPERTIES,
4764 N_("DrvVD: Configuration error: Multiple \"MergeSource\" occurrences"));
4765 break;
4766 }
4767 }
4768
4769 bool fMergeTarget;
4770 rc = CFGMR3QueryBoolDef(pCurNode, "MergeTarget", &fMergeTarget, false);
4771 if (RT_FAILURE(rc))
4772 {
4773 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
4774 N_("DrvVD: Configuration error: Querying \"MergeTarget\" as boolean failed"));
4775 break;
4776 }
4777 if (fMergeTarget)
4778 {
4779 if (pThis->uMergeTarget == VD_LAST_IMAGE)
4780 pThis->uMergeTarget = iImageIdx;
4781 else
4782 {
4783 rc = PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_DRIVER_INVALID_PROPERTIES,
4784 N_("DrvVD: Configuration error: Multiple \"MergeTarget\" occurrences"));
4785 break;
4786 }
4787 }
4788
4789 PCFGMNODE pCfgVDConfig = CFGMR3GetChild(pCurNode, "VDConfig");
4790 pImage->VDIfConfig.pfnAreKeysValid = drvvdCfgAreKeysValid;
4791 pImage->VDIfConfig.pfnQuerySize = drvvdCfgQuerySize;
4792 pImage->VDIfConfig.pfnQuery = drvvdCfgQuery;
4793 pImage->VDIfConfig.pfnQueryBytes = NULL;
4794 rc = VDInterfaceAdd(&pImage->VDIfConfig.Core, "DrvVD_Config", VDINTERFACETYPE_CONFIG,
4795 pCfgVDConfig, sizeof(VDINTERFACECONFIG), &pImage->pVDIfsImage);
4796 AssertRC(rc);
4797
4798 /* Check VDConfig for encryption config. */
4799 if (pCfgVDConfig)
4800 pThis->pCfgCrypto = CFGMR3GetChild(pCfgVDConfig, "CRYPT");
4801
4802 if (pThis->pCfgCrypto)
4803 {
4804 /* Setup VDConfig interface for disk encryption support. */
4805 pThis->VDIfCfg.pfnAreKeysValid = drvvdCfgAreKeysValid;
4806 pThis->VDIfCfg.pfnQuerySize = drvvdCfgQuerySize;
4807 pThis->VDIfCfg.pfnQuery = drvvdCfgQuery;
4808 pThis->VDIfCfg.pfnQueryBytes = NULL;
4809
4810 pThis->VDIfCrypto.pfnKeyRetain = drvvdCryptoKeyRetain;
4811 pThis->VDIfCrypto.pfnKeyRelease = drvvdCryptoKeyRelease;
4812 pThis->VDIfCrypto.pfnKeyStorePasswordRetain = drvvdCryptoKeyStorePasswordRetain;
4813 pThis->VDIfCrypto.pfnKeyStorePasswordRelease = drvvdCryptoKeyStorePasswordRelease;
4814 }
4815
4816 /* Unconditionally insert the TCPNET interface, don't bother to check
4817 * if an image really needs it. Will be ignored. Since the TCPNET
4818 * interface is per image we could make this more flexible in the
4819 * future if we want to. */
4820 /* Construct TCPNET callback table depending on the config. This is
4821 * done unconditionally, as uninterested backends will ignore it. */
4822 if (fHostIP)
4823 {
4824 pImage->VDIfTcpNet.pfnSocketCreate = drvvdTcpSocketCreate;
4825 pImage->VDIfTcpNet.pfnSocketDestroy = drvvdTcpSocketDestroy;
4826 pImage->VDIfTcpNet.pfnClientConnect = drvvdTcpClientConnect;
4827 pImage->VDIfTcpNet.pfnIsClientConnected = drvvdTcpIsClientConnected;
4828 pImage->VDIfTcpNet.pfnClientClose = drvvdTcpClientClose;
4829 pImage->VDIfTcpNet.pfnSelectOne = drvvdTcpSelectOne;
4830 pImage->VDIfTcpNet.pfnRead = drvvdTcpRead;
4831 pImage->VDIfTcpNet.pfnWrite = drvvdTcpWrite;
4832 pImage->VDIfTcpNet.pfnSgWrite = drvvdTcpSgWrite;
4833 pImage->VDIfTcpNet.pfnReadNB = drvvdTcpReadNB;
4834 pImage->VDIfTcpNet.pfnWriteNB = drvvdTcpWriteNB;
4835 pImage->VDIfTcpNet.pfnSgWriteNB = drvvdTcpSgWriteNB;
4836 pImage->VDIfTcpNet.pfnFlush = drvvdTcpFlush;
4837 pImage->VDIfTcpNet.pfnSetSendCoalescing = drvvdTcpSetSendCoalescing;
4838 pImage->VDIfTcpNet.pfnGetLocalAddress = drvvdTcpGetLocalAddress;
4839 pImage->VDIfTcpNet.pfnGetPeerAddress = drvvdTcpGetPeerAddress;
4840
4841 /*
4842 * There is a 15ms delay between receiving the data and marking the socket
4843 * as readable on Windows XP which hurts async I/O performance of
4844 * TCP backends badly. Provide a different select method without
4845 * using poll on XP.
4846 * This is only used on XP because it is not as efficient as the one using poll
4847 * and all other Windows versions are working fine.
4848 */
4849 char szOS[64];
4850 memset(szOS, 0, sizeof(szOS));
4851 rc = RTSystemQueryOSInfo(RTSYSOSINFO_PRODUCT, &szOS[0], sizeof(szOS));
4852
4853 if (RT_SUCCESS(rc) && !strncmp(szOS, "Windows XP", 10))
4854 {
4855 LogRel(("VD: Detected Windows XP, disabled poll based waiting for TCP\n"));
4856 pImage->VDIfTcpNet.pfnSelectOneEx = drvvdTcpSelectOneExNoPoll;
4857 }
4858 else
4859 pImage->VDIfTcpNet.pfnSelectOneEx = drvvdTcpSelectOneExPoll;
4860
4861 pImage->VDIfTcpNet.pfnPoke = drvvdTcpPoke;
4862 }
4863 else
4864 {
4865#ifndef VBOX_WITH_INIP
4866 rc = PDMDrvHlpVMSetError(pDrvIns, VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES,
4867 RT_SRC_POS, N_("DrvVD: Configuration error: TCP over Internal Networking not compiled in"));
4868#else /* VBOX_WITH_INIP */
4869 pImage->VDIfTcpNet.pfnSocketCreate = drvvdINIPSocketCreate;
4870 pImage->VDIfTcpNet.pfnSocketDestroy = drvvdINIPSocketDestroy;
4871 pImage->VDIfTcpNet.pfnClientConnect = drvvdINIPClientConnect;
4872 pImage->VDIfTcpNet.pfnClientClose = drvvdINIPClientClose;
4873 pImage->VDIfTcpNet.pfnIsClientConnected = drvvdINIPIsClientConnected;
4874 pImage->VDIfTcpNet.pfnSelectOne = drvvdINIPSelectOne;
4875 pImage->VDIfTcpNet.pfnRead = drvvdINIPRead;
4876 pImage->VDIfTcpNet.pfnWrite = drvvdINIPWrite;
4877 pImage->VDIfTcpNet.pfnSgWrite = drvvdINIPSgWrite;
4878 pImage->VDIfTcpNet.pfnFlush = drvvdINIPFlush;
4879 pImage->VDIfTcpNet.pfnSetSendCoalescing = drvvdINIPSetSendCoalescing;
4880 pImage->VDIfTcpNet.pfnGetLocalAddress = drvvdINIPGetLocalAddress;
4881 pImage->VDIfTcpNet.pfnGetPeerAddress = drvvdINIPGetPeerAddress;
4882 pImage->VDIfTcpNet.pfnSelectOneEx = drvvdINIPSelectOneEx;
4883 pImage->VDIfTcpNet.pfnPoke = drvvdINIPPoke;
4884#endif /* VBOX_WITH_INIP */
4885 }
4886 rc = VDInterfaceAdd(&pImage->VDIfTcpNet.Core, "DrvVD_TCPNET",
4887 VDINTERFACETYPE_TCPNET, NULL,
4888 sizeof(VDINTERFACETCPNET), &pImage->pVDIfsImage);
4889 AssertRC(rc);
4890
4891 /* Insert the custom I/O interface only if we're told to use new IO.
4892 * Since the I/O interface is per image we could make this more
4893 * flexible in the future if we want to. */
4894 if (fUseNewIo)
4895 {
4896#ifdef VBOX_WITH_PDM_ASYNC_COMPLETION
4897 pImage->VDIfIo.pfnOpen = drvvdAsyncIOOpen;
4898 pImage->VDIfIo.pfnClose = drvvdAsyncIOClose;
4899 pImage->VDIfIo.pfnGetSize = drvvdAsyncIOGetSize;
4900 pImage->VDIfIo.pfnSetSize = drvvdAsyncIOSetSize;
4901 pImage->VDIfIo.pfnSetAllocationSize = drvvdAsyncIOSetAllocationSize;
4902 pImage->VDIfIo.pfnReadSync = drvvdAsyncIOReadSync;
4903 pImage->VDIfIo.pfnWriteSync = drvvdAsyncIOWriteSync;
4904 pImage->VDIfIo.pfnFlushSync = drvvdAsyncIOFlushSync;
4905 pImage->VDIfIo.pfnReadAsync = drvvdAsyncIOReadAsync;
4906 pImage->VDIfIo.pfnWriteAsync = drvvdAsyncIOWriteAsync;
4907 pImage->VDIfIo.pfnFlushAsync = drvvdAsyncIOFlushAsync;
4908#else /* !VBOX_WITH_PDM_ASYNC_COMPLETION */
4909 rc = PDMDrvHlpVMSetError(pDrvIns, VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES,
4910 RT_SRC_POS, N_("DrvVD: Configuration error: Async Completion Framework not compiled in"));
4911#endif /* !VBOX_WITH_PDM_ASYNC_COMPLETION */
4912 if (RT_SUCCESS(rc))
4913 rc = VDInterfaceAdd(&pImage->VDIfIo.Core, "DrvVD_IO", VDINTERFACETYPE_IO,
4914 pThis, sizeof(VDINTERFACEIO), &pImage->pVDIfsImage);
4915 AssertRC(rc);
4916 }
4917
4918 /*
4919 * Open the image.
4920 */
4921 unsigned uOpenFlags;
4922 if (fReadOnly || pThis->fTempReadOnly || iLevel != 0)
4923 uOpenFlags = VD_OPEN_FLAGS_READONLY;
4924 else
4925 uOpenFlags = VD_OPEN_FLAGS_NORMAL;
4926 if (fHonorZeroWrites)
4927 uOpenFlags |= VD_OPEN_FLAGS_HONOR_ZEROES;
4928 if (pThis->fAsyncIOSupported)
4929 uOpenFlags |= VD_OPEN_FLAGS_ASYNC_IO;
4930 if (pThis->fShareable)
4931 uOpenFlags |= VD_OPEN_FLAGS_SHAREABLE;
4932 if (fDiscard && iLevel == 0)
4933 uOpenFlags |= VD_OPEN_FLAGS_DISCARD;
4934 if (fInformAboutZeroBlocks)
4935 uOpenFlags |= VD_OPEN_FLAGS_INFORM_ABOUT_ZERO_BLOCKS;
4936 if ( (uOpenFlags & VD_OPEN_FLAGS_READONLY)
4937 && fSkipConsistencyChecks)
4938 uOpenFlags |= VD_OPEN_FLAGS_SKIP_CONSISTENCY_CHECKS;
4939
4940 /* Try to open backend in async I/O mode first. */
4941 rc = VDOpen(pThis->pDisk, pszFormat, pszName, uOpenFlags, pImage->pVDIfsImage);
4942 if (rc == VERR_NOT_SUPPORTED)
4943 {
4944 pThis->fAsyncIOSupported = false;
4945 uOpenFlags &= ~VD_OPEN_FLAGS_ASYNC_IO;
4946 rc = VDOpen(pThis->pDisk, pszFormat, pszName, uOpenFlags, pImage->pVDIfsImage);
4947 }
4948
4949 if (rc == VERR_VD_DISCARD_NOT_SUPPORTED)
4950 {
4951 fDiscard = false;
4952 uOpenFlags &= ~VD_OPEN_FLAGS_DISCARD;
4953 rc = VDOpen(pThis->pDisk, pszFormat, pszName, uOpenFlags, pImage->pVDIfsImage);
4954 }
4955
4956 if (!fDiscard)
4957 {
4958 pThis->IMedia.pfnDiscard = NULL;
4959 pThis->IMediaAsync.pfnStartDiscard = NULL;
4960 }
4961
4962 if (RT_SUCCESS(rc))
4963 {
4964 LogFunc(("%d - Opened '%s' in %s mode\n",
4965 iLevel, pszName,
4966 VDIsReadOnly(pThis->pDisk) ? "read-only" : "read-write"));
4967 if ( VDIsReadOnly(pThis->pDisk)
4968 && !fReadOnly
4969 && !fMaybeReadOnly
4970 && !pThis->fTempReadOnly
4971 && iLevel == 0)
4972 {
4973 rc = PDMDrvHlpVMSetError(pDrvIns, VERR_VD_IMAGE_READ_ONLY, RT_SRC_POS,
4974 N_("Failed to open image '%s' for writing due to wrong permissions"),
4975 pszName);
4976 break;
4977 }
4978 }
4979 else
4980 {
4981 rc = PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS,
4982 N_("Failed to open image '%s' in %s mode"), pszName,
4983 (uOpenFlags & VD_OPEN_FLAGS_READONLY) ? "read-only" : "read-write");
4984 break;
4985 }
4986
4987 MMR3HeapFree(pszName);
4988 pszName = NULL;
4989 MMR3HeapFree(pszFormat);
4990 pszFormat = NULL;
4991
4992 /* next */
4993 iLevel--;
4994 iImageIdx++;
4995 pCurNode = CFGMR3GetParent(pCurNode);
4996 }
4997
4998 LogRel(("VD: Opening the disk took %lld ns\n", RTTimeNanoTS() - tsStart));
4999
5000 /* Open the cache image if set. */
5001 if ( RT_SUCCESS(rc)
5002 && RT_VALID_PTR(pszCachePath))
5003 {
5004 /* Insert the custom I/O interface only if we're told to use new IO.
5005 * Since the I/O interface is per image we could make this more
5006 * flexible in the future if we want to. */
5007 if (fUseNewIo)
5008 {
5009#ifdef VBOX_WITH_PDM_ASYNC_COMPLETION
5010 pThis->VDIfIoCache.pfnOpen = drvvdAsyncIOOpen;
5011 pThis->VDIfIoCache.pfnClose = drvvdAsyncIOClose;
5012 pThis->VDIfIoCache.pfnGetSize = drvvdAsyncIOGetSize;
5013 pThis->VDIfIoCache.pfnSetSize = drvvdAsyncIOSetSize;
5014 pThis->VDIfIoCache.pfnReadSync = drvvdAsyncIOReadSync;
5015 pThis->VDIfIoCache.pfnWriteSync = drvvdAsyncIOWriteSync;
5016 pThis->VDIfIoCache.pfnFlushSync = drvvdAsyncIOFlushSync;
5017 pThis->VDIfIoCache.pfnReadAsync = drvvdAsyncIOReadAsync;
5018 pThis->VDIfIoCache.pfnWriteAsync = drvvdAsyncIOWriteAsync;
5019 pThis->VDIfIoCache.pfnFlushAsync = drvvdAsyncIOFlushAsync;
5020#else /* !VBOX_WITH_PDM_ASYNC_COMPLETION */
5021 rc = PDMDrvHlpVMSetError(pDrvIns, VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES,
5022 RT_SRC_POS, N_("DrvVD: Configuration error: Async Completion Framework not compiled in"));
5023#endif /* !VBOX_WITH_PDM_ASYNC_COMPLETION */
5024 if (RT_SUCCESS(rc))
5025 rc = VDInterfaceAdd(&pThis->VDIfIoCache.Core, "DrvVD_IO", VDINTERFACETYPE_IO,
5026 pThis, sizeof(VDINTERFACEIO), &pThis->pVDIfsCache);
5027 AssertRC(rc);
5028 }
5029
5030 rc = VDCacheOpen(pThis->pDisk, pszCacheFormat, pszCachePath, VD_OPEN_FLAGS_NORMAL, pThis->pVDIfsCache);
5031 if (RT_FAILURE(rc))
5032 rc = PDMDRV_SET_ERROR(pDrvIns, rc, N_("DrvVD: Could not open cache image"));
5033 }
5034
5035 if (RT_VALID_PTR(pszCachePath))
5036 MMR3HeapFree(pszCachePath);
5037 if (RT_VALID_PTR(pszCacheFormat))
5038 MMR3HeapFree(pszCacheFormat);
5039
5040 if ( RT_SUCCESS(rc)
5041 && pThis->fMergePending
5042 && ( pThis->uMergeSource == VD_LAST_IMAGE
5043 || pThis->uMergeTarget == VD_LAST_IMAGE))
5044 {
5045 rc = PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_DRIVER_INVALID_PROPERTIES,
5046 N_("DrvVD: Configuration error: Inconsistent image merge data"));
5047 }
5048
5049 /* Create the block cache if enabled. */
5050 if ( fUseBlockCache
5051 && !pThis->fShareable
5052 && !fDiscard
5053 && !pThis->pCfgCrypto /* Disk encryption disables the block cache for security reasons */
5054 && RT_SUCCESS(rc))
5055 {
5056 /*
5057 * We need a unique ID for the block cache (to identify the owner of data
5058 * blocks in a saved state). UUIDs are not really suitable because
5059 * there are image formats which don't support them. Furthermore it is
5060 * possible that a new diff image was attached after a saved state
5061 * which changes the UUID.
5062 * However the device "name + device instance + LUN" triple the disk is
5063 * attached to is always constant for saved states.
5064 */
5065 char *pszId = NULL;
5066 uint32_t iInstance, iLUN;
5067 const char *pcszController;
5068
5069 rc = pThis->pDrvMediaPort->pfnQueryDeviceLocation(pThis->pDrvMediaPort, &pcszController,
5070 &iInstance, &iLUN);
5071 if (RT_FAILURE(rc))
5072 rc = PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_DRIVER_INVALID_PROPERTIES,
5073 N_("DrvVD: Configuration error: Could not query device data"));
5074 else
5075 {
5076 int cbStr = RTStrAPrintf(&pszId, "%s-%d-%d", pcszController, iInstance, iLUN);
5077
5078 if (cbStr > 0)
5079 {
5080 rc = PDMDrvHlpBlkCacheRetain(pDrvIns, &pThis->pBlkCache,
5081 drvvdBlkCacheXferComplete,
5082 drvvdBlkCacheXferEnqueue,
5083 drvvdBlkCacheXferEnqueueDiscard,
5084 pszId);
5085 if (rc == VERR_NOT_SUPPORTED)
5086 {
5087 LogRel(("VD: Block cache is not supported\n"));
5088 rc = VINF_SUCCESS;
5089 }
5090 else
5091 AssertRC(rc);
5092
5093 RTStrFree(pszId);
5094 }
5095 else
5096 rc = PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_DRIVER_INVALID_PROPERTIES,
5097 N_("DrvVD: Out of memory when creating block cache"));
5098 }
5099 }
5100
5101 if (RT_SUCCESS(rc))
5102 rc = drvvdSetupFilters(pThis, pCfg);
5103
5104 /*
5105 * Register a load-done callback so we can undo TempReadOnly config before
5106 * we get to drvvdResume. Autoamtically deregistered upon destruction.
5107 */
5108 if (RT_SUCCESS(rc))
5109 rc = PDMDrvHlpSSMRegisterEx(pDrvIns, 0 /* version */, 0 /* cbGuess */,
5110 NULL /*pfnLivePrep*/, NULL /*pfnLiveExec*/, NULL /*pfnLiveVote*/,
5111 NULL /*pfnSavePrep*/, NULL /*pfnSaveExec*/, NULL /*pfnSaveDone*/,
5112 NULL /*pfnDonePrep*/, NULL /*pfnLoadExec*/, drvvdLoadDone);
5113
5114 /* Setup the boot acceleration stuff if enabled. */
5115 if (RT_SUCCESS(rc) && pThis->fBootAccelEnabled)
5116 {
5117 pThis->cbDisk = VDGetSize(pThis->pDisk, VD_LAST_IMAGE);
5118 Assert(pThis->cbDisk > 0);
5119 pThis->pbData = (uint8_t *)RTMemAllocZ(pThis->cbBootAccelBuffer);
5120 if (pThis->pbData)
5121 {
5122 pThis->fBootAccelActive = true;
5123 pThis->offDisk = 0;
5124 pThis->cbDataValid = 0;
5125 LogRel(("VD: Boot acceleration enabled\n"));
5126 }
5127 else
5128 LogRel(("VD: Boot acceleration, out of memory, disabled\n"));
5129 }
5130
5131 if ( RTUuidIsNull(&pThis->Uuid)
5132 && pThis->enmType == PDMMEDIATYPE_HARD_DISK)
5133 VDGetUuid(pThis->pDisk, 0, &pThis->Uuid);
5134
5135 /*
5136 * Automatically upgrade the floppy drive if the specified one is too
5137 * small to represent the whole boot time image. (We cannot do this later
5138 * since the BIOS (and others) gets the info via CMOS.)
5139 *
5140 * This trick should make 2.88 images as well as the fake 15.6 and 63.5 MB
5141 * images despite the hardcoded default 1.44 drive.
5142 */
5143 if ( PDMMEDIATYPE_IS_FLOPPY(pThis->enmType)
5144 && pThis->pDisk)
5145 {
5146 uint64_t const cbFloppyImg = VDGetSize(pThis->pDisk, VD_LAST_IMAGE);
5147 PDMMEDIATYPE const enmCfgType = pThis->enmType;
5148 switch (enmCfgType)
5149 {
5150 default:
5151 AssertFailed();
5152 case PDMMEDIATYPE_FLOPPY_360:
5153 if (cbFloppyImg > 40 * 2 * 9 * 512)
5154 pThis->enmType = PDMMEDIATYPE_FLOPPY_720;
5155 /* fall thru */
5156 case PDMMEDIATYPE_FLOPPY_720:
5157 if (cbFloppyImg > 80 * 2 * 14 * 512)
5158 pThis->enmType = PDMMEDIATYPE_FLOPPY_1_20;
5159 /* fall thru */
5160 case PDMMEDIATYPE_FLOPPY_1_20:
5161 if (cbFloppyImg > 80 * 2 * 20 * 512)
5162 pThis->enmType = PDMMEDIATYPE_FLOPPY_1_44;
5163 /* fall thru */
5164 case PDMMEDIATYPE_FLOPPY_1_44:
5165 if (cbFloppyImg > 80 * 2 * 24 * 512)
5166 pThis->enmType = PDMMEDIATYPE_FLOPPY_2_88;
5167 /* fall thru */
5168 case PDMMEDIATYPE_FLOPPY_2_88:
5169 if (cbFloppyImg > 80 * 2 * 48 * 512)
5170 pThis->enmType = PDMMEDIATYPE_FLOPPY_FAKE_15_6;
5171 /* fall thru */
5172 case PDMMEDIATYPE_FLOPPY_FAKE_15_6:
5173 if (cbFloppyImg > 255 * 2 * 63 * 512)
5174 pThis->enmType = PDMMEDIATYPE_FLOPPY_FAKE_63_5;
5175 case PDMMEDIATYPE_FLOPPY_FAKE_63_5:
5176 if (cbFloppyImg > 255 * 2 * 255 * 512)
5177 LogRel(("Warning: Floppy image is larger that 63.5 MB! (%llu bytes)\n", cbFloppyImg));
5178 break;
5179 }
5180 if (pThis->enmType != enmCfgType)
5181 LogRel(("DrvVD: Automatically upgraded floppy drive from %s to %s to better support the %u byte image\n",
5182 drvvdGetTypeName(enmCfgType), drvvdGetTypeName(pThis->enmType), cbFloppyImg));
5183 }
5184 } /* !fEmptyDrive */
5185
5186 if (RT_FAILURE(rc))
5187 {
5188 if (RT_VALID_PTR(pszName))
5189 MMR3HeapFree(pszName);
5190 if (RT_VALID_PTR(pszFormat))
5191 MMR3HeapFree(pszFormat);
5192 /* drvvdDestruct does the rest. */
5193 }
5194
5195 LogFlowFunc(("returns %Rrc\n", rc));
5196 return rc;
5197}
5198
5199/**
5200 * VBox disk container media driver registration record.
5201 */
5202const PDMDRVREG g_DrvVD =
5203{
5204 /* u32Version */
5205 PDM_DRVREG_VERSION,
5206 /* szName */
5207 "VD",
5208 /* szRCMod */
5209 "",
5210 /* szR0Mod */
5211 "",
5212 /* pszDescription */
5213 "Generic VBox disk media driver.",
5214 /* fFlags */
5215 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
5216 /* fClass. */
5217 PDM_DRVREG_CLASS_MEDIA,
5218 /* cMaxInstances */
5219 ~0U,
5220 /* cbInstance */
5221 sizeof(VBOXDISK),
5222 /* pfnConstruct */
5223 drvvdConstruct,
5224 /* pfnDestruct */
5225 drvvdDestruct,
5226 /* pfnRelocate */
5227 NULL,
5228 /* pfnIOCtl */
5229 NULL,
5230 /* pfnPowerOn */
5231 drvvdPowerOn,
5232 /* pfnReset */
5233 drvvdReset,
5234 /* pfnSuspend */
5235 drvvdSuspend,
5236 /* pfnResume */
5237 drvvdResume,
5238 /* pfnAttach */
5239 NULL,
5240 /* pfnDetach */
5241 NULL,
5242 /* pfnPowerOff */
5243 drvvdPowerOff,
5244 /* pfnSoftReset */
5245 NULL,
5246 /* u32EndVersion */
5247 PDM_DRVREG_VERSION
5248};
5249
Note: See TracBrowser for help on using the repository browser.

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