VirtualBox

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

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

Devices/Storage/DrvVD: Missing places to account for read/written bytes

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