VirtualBox

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

Last change on this file since 89197 was 82968, checked in by vboxsync, 5 years ago

Copyright year updates by scm.

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