VirtualBox

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

Last change on this file since 81019 was 80590, checked in by vboxsync, 5 years ago

Devices/Storage: Add two new parameters to PDMIMEDIAEX::pfnIoReqSendScsiCmd to return the amount ofsense data written and the determined transfer direction from parsed CDB, bugref:9440 [build fix]

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 201.9 KB
Line 
1/* $Id: DrvVD.cpp 80590 2019-09-04 18:24:48Z vboxsync $ */
2/** @file
3 * DrvVD - Generic VBox disk media driver.
4 */
5
6/*
7 * Copyright (C) 2006-2019 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 uint32_t iInstance, iLUN;
4063 const char *pcszController;
4064
4065 int rc = pThis->pDrvMediaPort->pfnQueryDeviceLocation(pThis->pDrvMediaPort, &pcszController,
4066 &iInstance, &iLUN);
4067 if (RT_SUCCESS(rc))
4068 {
4069 char *pszCtrlUpper = RTStrDup(pcszController);
4070 if (pszCtrlUpper)
4071 {
4072 RTStrToUpper(pszCtrlUpper);
4073
4074 PDMDrvHlpSTAMRegisterF(pDrvIns, &pThis->StatQueryBufAttempts, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS,
4075 STAMUNIT_COUNT, "Number of attempts to query a direct buffer.",
4076 "/Devices/%s%u/Port%u/QueryBufAttempts", pszCtrlUpper, iInstance, iLUN);
4077 PDMDrvHlpSTAMRegisterF(pDrvIns, &pThis->StatQueryBufSuccess, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS,
4078 STAMUNIT_COUNT, "Number of succeeded attempts to query a direct buffer.",
4079 "/Devices/%s%u/Port%u/QueryBufSuccess", pszCtrlUpper, iInstance, iLUN);
4080
4081 PDMDrvHlpSTAMRegisterF(pDrvIns, &pThis->StatBytesRead, STAMTYPE_COUNTER, STAMVISIBILITY_USED, STAMUNIT_BYTES,
4082 "Amount of data read.", "/Devices/%s%u/Port%u/ReadBytes", pszCtrlUpper, iInstance, iLUN);
4083 PDMDrvHlpSTAMRegisterF(pDrvIns, &pThis->StatBytesWritten, STAMTYPE_COUNTER, STAMVISIBILITY_USED, STAMUNIT_BYTES,
4084 "Amount of data written.", "/Devices/%s%u/Port%u/WrittenBytes", pszCtrlUpper, iInstance, iLUN);
4085
4086 PDMDrvHlpSTAMRegisterF(pDrvIns, &pThis->StatReqsSubmitted, STAMTYPE_COUNTER, STAMVISIBILITY_USED, STAMUNIT_COUNT,
4087 "Number of I/O requests submitted.", "/Devices/%s%u/Port%u/ReqsSubmitted", pszCtrlUpper, iInstance, iLUN);
4088 PDMDrvHlpSTAMRegisterF(pDrvIns, &pThis->StatReqsFailed, STAMTYPE_COUNTER, STAMVISIBILITY_USED, STAMUNIT_COUNT,
4089 "Number of I/O requests failed.", "/Devices/%s%u/Port%u/ReqsFailed", pszCtrlUpper, iInstance, iLUN);
4090 PDMDrvHlpSTAMRegisterF(pDrvIns, &pThis->StatReqsSucceeded, STAMTYPE_COUNTER, STAMVISIBILITY_USED, STAMUNIT_COUNT,
4091 "Number of I/O requests succeeded.", "/Devices/%s%u/Port%u/ReqsSucceeded", pszCtrlUpper, iInstance, iLUN);
4092 PDMDrvHlpSTAMRegisterF(pDrvIns, &pThis->StatReqsFlush, STAMTYPE_COUNTER, STAMVISIBILITY_USED, STAMUNIT_COUNT,
4093 "Number of flush I/O requests submitted.", "/Devices/%s%u/Port%u/ReqsFlush", pszCtrlUpper, iInstance, iLUN);
4094 PDMDrvHlpSTAMRegisterF(pDrvIns, &pThis->StatReqsWrite, STAMTYPE_COUNTER, STAMVISIBILITY_USED, STAMUNIT_COUNT,
4095 "Number of write I/O requests submitted.", "/Devices/%s%u/Port%u/ReqsWrite", pszCtrlUpper, iInstance, iLUN);
4096 PDMDrvHlpSTAMRegisterF(pDrvIns, &pThis->StatReqsRead, STAMTYPE_COUNTER, STAMVISIBILITY_USED, STAMUNIT_COUNT,
4097 "Number of read I/O requests submitted.", "/Devices/%s%u/Port%u/ReqsRead", pszCtrlUpper, iInstance, iLUN);
4098 PDMDrvHlpSTAMRegisterF(pDrvIns, &pThis->StatReqsDiscard, STAMTYPE_COUNTER, STAMVISIBILITY_USED, STAMUNIT_COUNT,
4099 "Number of discard I/O requests submitted.", "/Devices/%s%u/Port%u/ReqsDiscard", pszCtrlUpper, iInstance, iLUN);
4100
4101 PDMDrvHlpSTAMRegisterF(pDrvIns, &pThis->StatReqsPerSec, STAMTYPE_COUNTER, STAMVISIBILITY_USED, STAMUNIT_OCCURENCES,
4102 "Number of processed I/O requests per second.", "/Devices/%s%u/Port%u/ReqsPerSec",
4103 pszCtrlUpper, iInstance, iLUN);
4104
4105 RTStrFree(pszCtrlUpper);
4106 }
4107 else
4108 rc = VERR_NO_STR_MEMORY;
4109 }
4110
4111 return rc;
4112}
4113
4114/**
4115 * Deregisters statistics associated with the given media driver.
4116 *
4117 * @returns nothing.
4118 * @param pThis The media driver instance.
4119 */
4120static void drvvdStatsDeregister(PVBOXDISK pThis)
4121{
4122 PPDMDRVINS pDrvIns = pThis->pDrvIns;
4123
4124 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->StatQueryBufAttempts);
4125 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->StatQueryBufSuccess);
4126
4127 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->StatBytesRead);
4128 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->StatBytesWritten);
4129 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->StatReqsSubmitted);
4130 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->StatReqsFailed);
4131 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->StatReqsSucceeded);
4132 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->StatReqsFlush);
4133 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->StatReqsWrite);
4134 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->StatReqsRead);
4135 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->StatReqsDiscard);
4136 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->StatReqsPerSec);
4137}
4138
4139
4140/*********************************************************************************************************************************
4141* Base interface methods *
4142*********************************************************************************************************************************/
4143
4144/**
4145 * @interface_method_impl{PDMIBASE,pfnQueryInterface}
4146 */
4147static DECLCALLBACK(void *) drvvdQueryInterface(PPDMIBASE pInterface, const char *pszIID)
4148{
4149 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
4150 PVBOXDISK pThis = PDMINS_2_DATA(pDrvIns, PVBOXDISK);
4151
4152 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pDrvIns->IBase);
4153 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIMEDIA, &pThis->IMedia);
4154 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIMOUNT, pThis->fMountable ? &pThis->IMount : NULL);
4155 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIMEDIAEX, pThis->pDrvMediaExPort ? &pThis->IMediaEx : NULL);
4156 return NULL;
4157}
4158
4159
4160/*********************************************************************************************************************************
4161* Saved state notification methods *
4162*********************************************************************************************************************************/
4163
4164/**
4165 * Load done callback for re-opening the image writable during teleportation.
4166 *
4167 * This is called both for successful and failed load runs, we only care about
4168 * successful ones.
4169 *
4170 * @returns VBox status code.
4171 * @param pDrvIns The driver instance.
4172 * @param pSSM The saved state handle.
4173 */
4174static DECLCALLBACK(int) drvvdLoadDone(PPDMDRVINS pDrvIns, PSSMHANDLE pSSM)
4175{
4176 PVBOXDISK pThis = PDMINS_2_DATA(pDrvIns, PVBOXDISK);
4177 Assert(!pThis->fErrorUseRuntime);
4178
4179 /* Drop out if we don't have any work to do or if it's a failed load. */
4180 if ( !pThis->fTempReadOnly
4181 || RT_FAILURE(SSMR3HandleGetStatus(pSSM)))
4182 return VINF_SUCCESS;
4183
4184 int rc = drvvdSetWritable(pThis);
4185 if (RT_FAILURE(rc)) /** @todo does the bugger set any errors? */
4186 return SSMR3SetLoadError(pSSM, rc, RT_SRC_POS,
4187 N_("Failed to write lock the images"));
4188 return VINF_SUCCESS;
4189}
4190
4191
4192/*********************************************************************************************************************************
4193* Driver methods *
4194*********************************************************************************************************************************/
4195
4196/**
4197 * Worker for the power off or destruct callback.
4198 *
4199 * @returns nothing.
4200 * @param pDrvIns The driver instance.
4201 */
4202static void drvvdPowerOffOrDestructOrUnmount(PPDMDRVINS pDrvIns)
4203{
4204 PVBOXDISK pThis = PDMINS_2_DATA(pDrvIns, PVBOXDISK);
4205 LogFlowFunc(("\n"));
4206
4207 RTSEMFASTMUTEX mutex;
4208 ASMAtomicXchgHandle(&pThis->MergeCompleteMutex, NIL_RTSEMFASTMUTEX, &mutex);
4209 if (mutex != NIL_RTSEMFASTMUTEX)
4210 {
4211 /* Request the semaphore to wait until a potentially running merge
4212 * operation has been finished. */
4213 int rc = RTSemFastMutexRequest(mutex);
4214 AssertRC(rc);
4215 pThis->fMergePending = false;
4216 rc = RTSemFastMutexRelease(mutex);
4217 AssertRC(rc);
4218 rc = RTSemFastMutexDestroy(mutex);
4219 AssertRC(rc);
4220 }
4221
4222 if (RT_VALID_PTR(pThis->pBlkCache))
4223 {
4224 PDMR3BlkCacheRelease(pThis->pBlkCache);
4225 pThis->pBlkCache = NULL;
4226 }
4227
4228 if (RT_VALID_PTR(pThis->pRegionList))
4229 {
4230 VDRegionListFree(pThis->pRegionList);
4231 pThis->pRegionList = NULL;
4232 }
4233
4234 if (RT_VALID_PTR(pThis->pDisk))
4235 {
4236 VDDestroy(pThis->pDisk);
4237 pThis->pDisk = NULL;
4238 }
4239 drvvdFreeImages(pThis);
4240}
4241
4242/**
4243 * @copydoc FNPDMDRVPOWEROFF
4244 */
4245static DECLCALLBACK(void) drvvdPowerOff(PPDMDRVINS pDrvIns)
4246{
4247 PDMDRV_CHECK_VERSIONS_RETURN_VOID(pDrvIns);
4248 drvvdPowerOffOrDestructOrUnmount(pDrvIns);
4249}
4250
4251/**
4252 * @callback_method_impl{FNPDMDRVRESUME}
4253 *
4254 * VM resume notification that we use to undo what the temporary read-only image
4255 * mode set by drvvdSuspend.
4256 *
4257 * Also switch to runtime error mode if we're resuming after a state load
4258 * without having been powered on first.
4259 *
4260 * @todo The VMSetError vs VMSetRuntimeError mess must be fixed elsewhere,
4261 * we're making assumptions about Main behavior here!
4262 */
4263static DECLCALLBACK(void) drvvdResume(PPDMDRVINS pDrvIns)
4264{
4265 LogFlowFunc(("\n"));
4266 PVBOXDISK pThis = PDMINS_2_DATA(pDrvIns, PVBOXDISK);
4267
4268 drvvdSetWritable(pThis);
4269 pThis->fSuspending = false;
4270 pThis->fRedo = false;
4271
4272 if (pThis->pBlkCache)
4273 {
4274 int rc = PDMR3BlkCacheResume(pThis->pBlkCache);
4275 AssertRC(rc);
4276 }
4277
4278 if (pThis->pDrvMediaExPort)
4279 {
4280 /* Mark all requests waiting for I/O memory as active again so they get accounted for. */
4281 RTCritSectEnter(&pThis->CritSectIoReqsIoBufWait);
4282 PPDMMEDIAEXIOREQINT pIoReq, pIoReqNext;
4283 RTListForEachSafe(&pThis->LstIoReqIoBufWait, pIoReq, pIoReqNext, PDMMEDIAEXIOREQINT, NdLstWait)
4284 {
4285 pThis->pDrvMediaExPort->pfnIoReqStateChanged(pThis->pDrvMediaExPort, pIoReq, &pIoReq->abAlloc[0],
4286 PDMMEDIAEXIOREQSTATE_ACTIVE);
4287 ASMAtomicIncU32(&pThis->cIoReqsActive);
4288 LogFlowFunc(("Resumed I/O request %#p\n", pIoReq));
4289 }
4290 RTCritSectLeave(&pThis->CritSectIoReqsIoBufWait);
4291
4292 /* Kick of any request we have to redo. */
4293 RTCritSectEnter(&pThis->CritSectIoReqRedo);
4294 RTListForEachSafe(&pThis->LstIoReqRedo, pIoReq, pIoReqNext, PDMMEDIAEXIOREQINT, NdLstWait)
4295 {
4296 int rc = VINF_SUCCESS;
4297 bool fXchg = ASMAtomicCmpXchgU32((volatile uint32_t *)&pIoReq->enmState, VDIOREQSTATE_ACTIVE, VDIOREQSTATE_SUSPENDED);
4298
4299 RTListNodeRemove(&pIoReq->NdLstWait);
4300 ASMAtomicIncU32(&pThis->cIoReqsActive);
4301
4302 LogFlowFunc(("Resuming I/O request %#p fXchg=%RTbool\n", pIoReq, fXchg));
4303 if (fXchg)
4304 {
4305 pThis->pDrvMediaExPort->pfnIoReqStateChanged(pThis->pDrvMediaExPort, pIoReq, &pIoReq->abAlloc[0],
4306 PDMMEDIAEXIOREQSTATE_ACTIVE);
4307 LogFlowFunc(("Resumed I/O request %#p\n", pIoReq));
4308 if ( pIoReq->enmType == PDMMEDIAEXIOREQTYPE_READ
4309 || pIoReq->enmType == PDMMEDIAEXIOREQTYPE_WRITE)
4310 rc = drvvdMediaExIoReqReadWriteProcess(pThis, pIoReq, true /* fUpNotify */);
4311 else if (pIoReq->enmType == PDMMEDIAEXIOREQTYPE_FLUSH)
4312 {
4313 rc = drvvdMediaExIoReqFlushWrapper(pThis, pIoReq);
4314 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
4315 rc = VINF_PDM_MEDIAEX_IOREQ_IN_PROGRESS;
4316 else if (rc == VINF_VD_ASYNC_IO_FINISHED)
4317 rc = VINF_SUCCESS;
4318 }
4319 else if (pIoReq->enmType == PDMMEDIAEXIOREQTYPE_DISCARD)
4320 {
4321 rc = drvvdMediaExIoReqDiscardWrapper(pThis, pIoReq);
4322 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
4323 rc = VINF_PDM_MEDIAEX_IOREQ_IN_PROGRESS;
4324 else if (rc == VINF_VD_ASYNC_IO_FINISHED)
4325 rc = VINF_SUCCESS;
4326 }
4327 else
4328 AssertMsgFailed(("Invalid request type %u\n", pIoReq->enmType));
4329
4330 /* The read write process will call the completion callback on its own. */
4331 if ( rc != VINF_PDM_MEDIAEX_IOREQ_IN_PROGRESS
4332 && ( pIoReq->enmType == PDMMEDIAEXIOREQTYPE_DISCARD
4333 || pIoReq->enmType == PDMMEDIAEXIOREQTYPE_FLUSH))
4334 {
4335 Assert( ( pIoReq->enmType != PDMMEDIAEXIOREQTYPE_WRITE
4336 && pIoReq->enmType != PDMMEDIAEXIOREQTYPE_READ)
4337 || !pIoReq->ReadWrite.cbReqLeft
4338 || RT_FAILURE(rc));
4339 drvvdMediaExIoReqCompleteWorker(pThis, pIoReq, rc, true /* fUpNotify */);
4340 }
4341
4342 }
4343 else
4344 {
4345 /* Request was canceled inbetween, so don't care and notify the owner about the completed request. */
4346 Assert(pIoReq->enmState == VDIOREQSTATE_CANCELED);
4347 drvvdMediaExIoReqCompleteWorker(pThis, pIoReq, VERR_PDM_MEDIAEX_IOREQ_CANCELED, true /* fUpNotify */);
4348 }
4349 }
4350 Assert(RTListIsEmpty(&pThis->LstIoReqRedo));
4351 RTCritSectLeave(&pThis->CritSectIoReqRedo);
4352 }
4353
4354 /* Try to process any requests waiting for I/O memory now. */
4355 drvvdMediaExIoReqProcessWaiting(pThis);
4356 pThis->fErrorUseRuntime = true;
4357}
4358
4359/**
4360 * @callback_method_impl{FNPDMDRVSUSPEND}
4361 *
4362 * When the VM is being suspended, temporarily change to read-only image mode.
4363 *
4364 * This is important for several reasons:
4365 * -# It makes sure that there are no pending writes to the image. Most
4366 * backends implements this by closing and reopening the image in read-only
4367 * mode.
4368 * -# It allows Main to read the images during snapshotting without having
4369 * to account for concurrent writes.
4370 * -# This is essential for making teleportation targets sharing images work
4371 * right. Both with regards to caching and with regards to file sharing
4372 * locks (RTFILE_O_DENY_*). (See also drvvdLoadDone.)
4373 */
4374static DECLCALLBACK(void) drvvdSuspend(PPDMDRVINS pDrvIns)
4375{
4376 LogFlowFunc(("\n"));
4377 PVBOXDISK pThis = PDMINS_2_DATA(pDrvIns, PVBOXDISK);
4378
4379 if (pThis->pBlkCache)
4380 {
4381 int rc = PDMR3BlkCacheSuspend(pThis->pBlkCache);
4382 AssertRC(rc);
4383 }
4384
4385 drvvdSetReadonly(pThis);
4386}
4387
4388/**
4389 * @callback_method_impl{FNPDMDRVPOWERON}
4390 */
4391static DECLCALLBACK(void) drvvdPowerOn(PPDMDRVINS pDrvIns)
4392{
4393 LogFlowFunc(("\n"));
4394 PVBOXDISK pThis = PDMINS_2_DATA(pDrvIns, PVBOXDISK);
4395 drvvdSetWritable(pThis);
4396 pThis->fErrorUseRuntime = true;
4397}
4398
4399/**
4400 * @callback_method_impl{FNPDMDRVRESET}
4401 */
4402static DECLCALLBACK(void) drvvdReset(PPDMDRVINS pDrvIns)
4403{
4404 LogFlowFunc(("\n"));
4405 PVBOXDISK pThis = PDMINS_2_DATA(pDrvIns, PVBOXDISK);
4406
4407 if (pThis->pBlkCache)
4408 {
4409 int rc = PDMR3BlkCacheClear(pThis->pBlkCache);
4410 AssertRC(rc);
4411 }
4412
4413 if (pThis->fBootAccelEnabled)
4414 {
4415 pThis->fBootAccelActive = true;
4416 pThis->cbDataValid = 0;
4417 pThis->offDisk = 0;
4418 }
4419}
4420
4421/**
4422 * @callback_method_impl{FNPDMDRVDESTRUCT}
4423 */
4424static DECLCALLBACK(void) drvvdDestruct(PPDMDRVINS pDrvIns)
4425{
4426 PDMDRV_CHECK_VERSIONS_RETURN_VOID(pDrvIns);
4427 PVBOXDISK pThis = PDMINS_2_DATA(pDrvIns, PVBOXDISK);
4428 LogFlowFunc(("\n"));
4429
4430 /*
4431 * Make sure the block cache and disks are closed when this driver is
4432 * destroyed. This method will get called without calling the power off
4433 * callback first when we reconfigure the driver chain after a snapshot.
4434 */
4435 drvvdPowerOffOrDestructOrUnmount(pDrvIns);
4436 if (pThis->MergeLock != NIL_RTSEMRW)
4437 {
4438 int rc = RTSemRWDestroy(pThis->MergeLock);
4439 AssertRC(rc);
4440 pThis->MergeLock = NIL_RTSEMRW;
4441 }
4442 if (pThis->pbData)
4443 {
4444 RTMemFree(pThis->pbData);
4445 pThis->pbData = NULL;
4446 }
4447 if (pThis->pszBwGroup)
4448 {
4449 MMR3HeapFree(pThis->pszBwGroup);
4450 pThis->pszBwGroup = NULL;
4451 }
4452 if (pThis->hHbdMgr != NIL_HBDMGR)
4453 HBDMgrDestroy(pThis->hHbdMgr);
4454 if (pThis->hIoReqCache != NIL_RTMEMCACHE)
4455 RTMemCacheDestroy(pThis->hIoReqCache);
4456 if (pThis->hIoBufMgr != NIL_IOBUFMGR)
4457 IOBUFMgrDestroy(pThis->hIoBufMgr);
4458 if (RTCritSectIsInitialized(&pThis->CritSectIoReqsIoBufWait))
4459 RTCritSectDelete(&pThis->CritSectIoReqsIoBufWait);
4460 if (RTCritSectIsInitialized(&pThis->CritSectIoReqRedo))
4461 RTCritSectDelete(&pThis->CritSectIoReqRedo);
4462 for (unsigned i = 0; i < RT_ELEMENTS(pThis->aIoReqAllocBins); i++)
4463 if (pThis->aIoReqAllocBins[i].hMtxLstIoReqAlloc != NIL_RTSEMFASTMUTEX)
4464 RTSemFastMutexDestroy(pThis->aIoReqAllocBins[i].hMtxLstIoReqAlloc);
4465
4466 drvvdStatsDeregister(pThis);
4467}
4468
4469/**
4470 * @callback_method_impl{FNPDMDRVCONSTRUCT,
4471 * Construct a VBox disk media driver instance.}
4472 */
4473static DECLCALLBACK(int) drvvdConstruct(PPDMDRVINS pDrvIns, PCFGMNODE pCfg, uint32_t fFlags)
4474{
4475 RT_NOREF(fFlags);
4476 LogFlowFunc(("\n"));
4477 PDMDRV_CHECK_VERSIONS_RETURN(pDrvIns);
4478 PVBOXDISK pThis = PDMINS_2_DATA(pDrvIns, PVBOXDISK);
4479 int rc = VINF_SUCCESS;
4480 char *pszName = NULL; /* The path of the disk image file. */
4481 char *pszFormat = NULL; /* The format backed to use for this image. */
4482 char *pszCachePath = NULL; /* The path to the cache image. */
4483 char *pszCacheFormat = NULL; /* The format backend to use for the cache image. */
4484 bool fReadOnly = false; /* True if the media is read-only. */
4485 bool fMaybeReadOnly = false; /* True if the media may or may not be read-only. */
4486 bool fHonorZeroWrites = false; /* True if zero blocks should be written. */
4487
4488 /*
4489 * Init the static parts.
4490 */
4491 pDrvIns->IBase.pfnQueryInterface = drvvdQueryInterface;
4492 pThis->pDrvIns = pDrvIns;
4493 pThis->fTempReadOnly = false;
4494 pThis->pDisk = NULL;
4495 pThis->fAsyncIOSupported = false;
4496 pThis->fShareable = false;
4497 pThis->fMergePending = false;
4498 pThis->MergeCompleteMutex = NIL_RTSEMFASTMUTEX;
4499 pThis->MergeLock = NIL_RTSEMRW;
4500 pThis->uMergeSource = VD_LAST_IMAGE;
4501 pThis->uMergeTarget = VD_LAST_IMAGE;
4502 pThis->pCfgCrypto = NULL;
4503 pThis->pIfSecKey = NULL;
4504 pThis->hIoReqCache = NIL_RTMEMCACHE;
4505 pThis->hIoBufMgr = NIL_IOBUFMGR;
4506 pThis->pRegionList = NULL;
4507 pThis->fSuspending = false;
4508 pThis->fRedo = false;
4509
4510 for (unsigned i = 0; i < RT_ELEMENTS(pThis->aIoReqAllocBins); i++)
4511 pThis->aIoReqAllocBins[i].hMtxLstIoReqAlloc = NIL_RTSEMFASTMUTEX;
4512
4513 /* IMedia */
4514 pThis->IMedia.pfnRead = drvvdRead;
4515 pThis->IMedia.pfnReadPcBios = drvvdReadPcBios;
4516 pThis->IMedia.pfnWrite = drvvdWrite;
4517 pThis->IMedia.pfnFlush = drvvdFlush;
4518 pThis->IMedia.pfnMerge = drvvdMerge;
4519 pThis->IMedia.pfnSetSecKeyIf = drvvdSetSecKeyIf;
4520 pThis->IMedia.pfnGetSize = drvvdGetSize;
4521 pThis->IMedia.pfnGetSectorSize = drvvdGetSectorSize;
4522 pThis->IMedia.pfnIsReadOnly = drvvdIsReadOnly;
4523 pThis->IMedia.pfnIsNonRotational = drvvdIsNonRotational;
4524 pThis->IMedia.pfnBiosGetPCHSGeometry = drvvdBiosGetPCHSGeometry;
4525 pThis->IMedia.pfnBiosSetPCHSGeometry = drvvdBiosSetPCHSGeometry;
4526 pThis->IMedia.pfnBiosGetLCHSGeometry = drvvdBiosGetLCHSGeometry;
4527 pThis->IMedia.pfnBiosSetLCHSGeometry = drvvdBiosSetLCHSGeometry;
4528 pThis->IMedia.pfnBiosIsVisible = drvvdBiosIsVisible;
4529 pThis->IMedia.pfnGetType = drvvdGetType;
4530 pThis->IMedia.pfnGetUuid = drvvdGetUuid;
4531 pThis->IMedia.pfnDiscard = drvvdDiscard;
4532 pThis->IMedia.pfnSendCmd = NULL;
4533 pThis->IMedia.pfnGetRegionCount = drvvdGetRegionCount;
4534 pThis->IMedia.pfnQueryRegionProperties = drvvdQueryRegionProperties;
4535 pThis->IMedia.pfnQueryRegionPropertiesForLba = drvvdQueryRegionPropertiesForLba;
4536
4537 /* IMount */
4538 pThis->IMount.pfnUnmount = drvvdUnmount;
4539 pThis->IMount.pfnIsMounted = drvvdIsMounted;
4540 pThis->IMount.pfnLock = drvvdLock;
4541 pThis->IMount.pfnUnlock = drvvdUnlock;
4542 pThis->IMount.pfnIsLocked = drvvdIsLocked;
4543
4544 /* IMediaEx */
4545 pThis->IMediaEx.pfnQueryFeatures = drvvdQueryFeatures;
4546 pThis->IMediaEx.pfnNotifySuspend = drvvdNotifySuspend;
4547 pThis->IMediaEx.pfnIoReqAllocSizeSet = drvvdIoReqAllocSizeSet;
4548 pThis->IMediaEx.pfnIoReqAlloc = drvvdIoReqAlloc;
4549 pThis->IMediaEx.pfnIoReqFree = drvvdIoReqFree;
4550 pThis->IMediaEx.pfnIoReqQueryResidual = drvvdIoReqQueryResidual;
4551 pThis->IMediaEx.pfnIoReqQueryXferSize = drvvdIoReqQueryXferSize;
4552 pThis->IMediaEx.pfnIoReqCancelAll = drvvdIoReqCancelAll;
4553 pThis->IMediaEx.pfnIoReqCancel = drvvdIoReqCancel;
4554 pThis->IMediaEx.pfnIoReqRead = drvvdIoReqRead;
4555 pThis->IMediaEx.pfnIoReqWrite = drvvdIoReqWrite;
4556 pThis->IMediaEx.pfnIoReqFlush = drvvdIoReqFlush;
4557 pThis->IMediaEx.pfnIoReqDiscard = drvvdIoReqDiscard;
4558 pThis->IMediaEx.pfnIoReqSendScsiCmd = drvvdIoReqSendScsiCmd;
4559 pThis->IMediaEx.pfnIoReqGetActiveCount = drvvdIoReqGetActiveCount;
4560 pThis->IMediaEx.pfnIoReqGetSuspendedCount = drvvdIoReqGetSuspendedCount;
4561 pThis->IMediaEx.pfnIoReqQuerySuspendedStart = drvvdIoReqQuerySuspendedStart;
4562 pThis->IMediaEx.pfnIoReqQuerySuspendedNext = drvvdIoReqQuerySuspendedNext;
4563 pThis->IMediaEx.pfnIoReqSuspendedSave = drvvdIoReqSuspendedSave;
4564 pThis->IMediaEx.pfnIoReqSuspendedLoad = drvvdIoReqSuspendedLoad;
4565
4566 /* Initialize supported VD interfaces. */
4567 pThis->pVDIfsDisk = NULL;
4568
4569 pThis->VDIfError.pfnError = drvvdErrorCallback;
4570 pThis->VDIfError.pfnMessage = NULL;
4571 rc = VDInterfaceAdd(&pThis->VDIfError.Core, "DrvVD_VDIError", VDINTERFACETYPE_ERROR,
4572 pDrvIns, sizeof(VDINTERFACEERROR), &pThis->pVDIfsDisk);
4573 AssertRC(rc);
4574
4575 /* List of images is empty now. */
4576 pThis->pImages = NULL;
4577
4578 pThis->pDrvMediaPort = PDMIBASE_QUERY_INTERFACE(pDrvIns->pUpBase, PDMIMEDIAPORT);
4579 if (!pThis->pDrvMediaPort)
4580 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_MISSING_INTERFACE_ABOVE,
4581 N_("No media port interface above"));
4582
4583 pThis->pDrvMountNotify = PDMIBASE_QUERY_INTERFACE(pDrvIns->pUpBase, PDMIMOUNTNOTIFY);
4584
4585 /*
4586 * Try to attach the optional extended media interface port above and initialize associated
4587 * structures if available.
4588 */
4589 pThis->pDrvMediaExPort = PDMIBASE_QUERY_INTERFACE(pDrvIns->pUpBase, PDMIMEDIAEXPORT);
4590 if (pThis->pDrvMediaExPort)
4591 {
4592 for (unsigned i = 0; i < RT_ELEMENTS(pThis->aIoReqAllocBins); i++)
4593 {
4594 rc = RTSemFastMutexCreate(&pThis->aIoReqAllocBins[i].hMtxLstIoReqAlloc);
4595 if (RT_FAILURE(rc))
4596 break;
4597 RTListInit(&pThis->aIoReqAllocBins[i].LstIoReqAlloc);
4598 }
4599
4600 if (RT_SUCCESS(rc))
4601 rc = RTCritSectInit(&pThis->CritSectIoReqsIoBufWait);
4602
4603 if (RT_SUCCESS(rc))
4604 rc = RTCritSectInit(&pThis->CritSectIoReqRedo);
4605
4606 if (RT_FAILURE(rc))
4607 return PDMDRV_SET_ERROR(pDrvIns, rc, N_("Creating Mutex failed"));
4608
4609 RTListInit(&pThis->LstIoReqIoBufWait);
4610 RTListInit(&pThis->LstIoReqRedo);
4611 }
4612
4613 /* Before we access any VD API load all given plugins. */
4614 rc = drvvdLoadPlugins(pCfg);
4615 if (RT_FAILURE(rc))
4616 return PDMDRV_SET_ERROR(pDrvIns, rc, N_("Loading VD plugins failed"));
4617
4618 /*
4619 * Validate configuration and find all parent images.
4620 * It's sort of up side down from the image dependency tree.
4621 */
4622 bool fHostIP = false;
4623 bool fUseNewIo = false;
4624 bool fUseBlockCache = false;
4625 bool fDiscard = false;
4626 bool fInformAboutZeroBlocks = false;
4627 bool fSkipConsistencyChecks = false;
4628 bool fEmptyDrive = false;
4629 unsigned iLevel = 0;
4630 PCFGMNODE pCurNode = pCfg;
4631 uint32_t cbIoBufMax = 0;
4632
4633 for (;;)
4634 {
4635 bool fValid;
4636
4637 if (pCurNode == pCfg)
4638 {
4639 /* Toplevel configuration additionally contains the global image
4640 * open flags. Some might be converted to per-image flags later. */
4641 fValid = CFGMR3AreValuesValid(pCurNode,
4642 "Format\0Path\0"
4643 "ReadOnly\0MaybeReadOnly\0TempReadOnly\0Shareable\0HonorZeroWrites\0"
4644 "HostIPStack\0UseNewIo\0BootAcceleration\0BootAccelerationBuffer\0"
4645 "SetupMerge\0MergeSource\0MergeTarget\0BwGroup\0Type\0BlockCache\0"
4646 "CachePath\0CacheFormat\0Discard\0InformAboutZeroBlocks\0"
4647 "SkipConsistencyChecks\0"
4648 "Locked\0BIOSVisible\0Cylinders\0Heads\0Sectors\0Mountable\0"
4649 "EmptyDrive\0IoBufMax\0NonRotationalMedium\0"
4650#if defined(VBOX_PERIODIC_FLUSH) || defined(VBOX_IGNORE_FLUSH)
4651 "FlushInterval\0IgnoreFlush\0IgnoreFlushAsync\0"
4652#endif /* !(VBOX_PERIODIC_FLUSH || VBOX_IGNORE_FLUSH) */
4653 );
4654 }
4655 else
4656 {
4657 /* All other image configurations only contain image name and
4658 * the format information. */
4659 fValid = CFGMR3AreValuesValid(pCurNode, "Format\0Path\0"
4660 "MergeSource\0MergeTarget\0");
4661 }
4662 if (!fValid)
4663 {
4664 rc = PDMDrvHlpVMSetError(pDrvIns, VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES,
4665 RT_SRC_POS, N_("DrvVD: Configuration error: keys incorrect at level %d"), iLevel);
4666 break;
4667 }
4668
4669 if (pCurNode == pCfg)
4670 {
4671 rc = CFGMR3QueryBoolDef(pCurNode, "HostIPStack", &fHostIP, true);
4672 if (RT_FAILURE(rc))
4673 {
4674 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
4675 N_("DrvVD: Configuration error: Querying \"HostIPStack\" as boolean failed"));
4676 break;
4677 }
4678
4679 rc = CFGMR3QueryBoolDef(pCurNode, "HonorZeroWrites", &fHonorZeroWrites, false);
4680 if (RT_FAILURE(rc))
4681 {
4682 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
4683 N_("DrvVD: Configuration error: Querying \"HonorZeroWrites\" as boolean failed"));
4684 break;
4685 }
4686
4687 rc = CFGMR3QueryBoolDef(pCurNode, "ReadOnly", &fReadOnly, false);
4688 if (RT_FAILURE(rc))
4689 {
4690 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
4691 N_("DrvVD: Configuration error: Querying \"ReadOnly\" as boolean failed"));
4692 break;
4693 }
4694
4695 rc = CFGMR3QueryBoolDef(pCurNode, "MaybeReadOnly", &fMaybeReadOnly, false);
4696 if (RT_FAILURE(rc))
4697 {
4698 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
4699 N_("DrvVD: Configuration error: Querying \"MaybeReadOnly\" as boolean failed"));
4700 break;
4701 }
4702
4703 rc = CFGMR3QueryBoolDef(pCurNode, "TempReadOnly", &pThis->fTempReadOnly, false);
4704 if (RT_FAILURE(rc))
4705 {
4706 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
4707 N_("DrvVD: Configuration error: Querying \"TempReadOnly\" as boolean failed"));
4708 break;
4709 }
4710 if (fReadOnly && pThis->fTempReadOnly)
4711 {
4712 rc = PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_DRIVER_INVALID_PROPERTIES,
4713 N_("DrvVD: Configuration error: Both \"ReadOnly\" and \"TempReadOnly\" are set"));
4714 break;
4715 }
4716
4717 rc = CFGMR3QueryBoolDef(pCurNode, "Shareable", &pThis->fShareable, false);
4718 if (RT_FAILURE(rc))
4719 {
4720 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
4721 N_("DrvVD: Configuration error: Querying \"Shareable\" as boolean failed"));
4722 break;
4723 }
4724
4725 rc = CFGMR3QueryBoolDef(pCurNode, "UseNewIo", &fUseNewIo, false);
4726 if (RT_FAILURE(rc))
4727 {
4728 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
4729 N_("DrvVD: Configuration error: Querying \"UseNewIo\" as boolean failed"));
4730 break;
4731 }
4732 rc = CFGMR3QueryBoolDef(pCurNode, "SetupMerge", &pThis->fMergePending, false);
4733 if (RT_FAILURE(rc))
4734 {
4735 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
4736 N_("DrvVD: Configuration error: Querying \"SetupMerge\" as boolean failed"));
4737 break;
4738 }
4739 if (fReadOnly && pThis->fMergePending)
4740 {
4741 rc = PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_DRIVER_INVALID_PROPERTIES,
4742 N_("DrvVD: Configuration error: Both \"ReadOnly\" and \"MergePending\" are set"));
4743 break;
4744 }
4745 rc = CFGMR3QueryBoolDef(pCurNode, "BootAcceleration", &pThis->fBootAccelEnabled, false);
4746 if (RT_FAILURE(rc))
4747 {
4748 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
4749 N_("DrvVD: Configuration error: Querying \"BootAcceleration\" as boolean failed"));
4750 break;
4751 }
4752 rc = CFGMR3QueryU32Def(pCurNode, "BootAccelerationBuffer", (uint32_t *)&pThis->cbBootAccelBuffer, 16 * _1K);
4753 if (RT_FAILURE(rc))
4754 {
4755 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
4756 N_("DrvVD: Configuration error: Querying \"BootAccelerationBuffer\" as integer failed"));
4757 break;
4758 }
4759 rc = CFGMR3QueryBoolDef(pCurNode, "BlockCache", &fUseBlockCache, false);
4760 if (RT_FAILURE(rc))
4761 {
4762 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
4763 N_("DrvVD: Configuration error: Querying \"BlockCache\" as boolean failed"));
4764 break;
4765 }
4766 rc = CFGMR3QueryStringAlloc(pCurNode, "BwGroup", &pThis->pszBwGroup);
4767 if (RT_FAILURE(rc) && rc != VERR_CFGM_VALUE_NOT_FOUND)
4768 {
4769 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
4770 N_("DrvVD: Configuration error: Querying \"BwGroup\" as string failed"));
4771 break;
4772 }
4773 else
4774 rc = VINF_SUCCESS;
4775 rc = CFGMR3QueryBoolDef(pCurNode, "Discard", &fDiscard, false);
4776 if (RT_FAILURE(rc))
4777 {
4778 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
4779 N_("DrvVD: Configuration error: Querying \"Discard\" as boolean failed"));
4780 break;
4781 }
4782 if (fReadOnly && fDiscard)
4783 {
4784 rc = PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_DRIVER_INVALID_PROPERTIES,
4785 N_("DrvVD: Configuration error: Both \"ReadOnly\" and \"Discard\" are set"));
4786 break;
4787 }
4788 rc = CFGMR3QueryBoolDef(pCurNode, "InformAboutZeroBlocks", &fInformAboutZeroBlocks, false);
4789 if (RT_FAILURE(rc))
4790 {
4791 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
4792 N_("DrvVD: Configuration error: Querying \"InformAboutZeroBlocks\" as boolean failed"));
4793 break;
4794 }
4795 rc = CFGMR3QueryBoolDef(pCurNode, "SkipConsistencyChecks", &fSkipConsistencyChecks, true);
4796 if (RT_FAILURE(rc))
4797 {
4798 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
4799 N_("DrvVD: Configuration error: Querying \"SKipConsistencyChecks\" as boolean failed"));
4800 break;
4801 }
4802
4803 char *psz = NULL;
4804 rc = CFGMR3QueryStringAlloc(pCfg, "Type", &psz);
4805 if (RT_FAILURE(rc))
4806 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_BLOCK_NO_TYPE, N_("Failed to obtain the sub type"));
4807 pThis->enmType = drvvdGetMediaTypeFromString(psz);
4808 if (pThis->enmType == PDMMEDIATYPE_ERROR)
4809 {
4810 PDMDrvHlpVMSetError(pDrvIns, VERR_PDM_BLOCK_UNKNOWN_TYPE, RT_SRC_POS,
4811 N_("Unknown type \"%s\""), psz);
4812 MMR3HeapFree(psz);
4813 return VERR_PDM_BLOCK_UNKNOWN_TYPE;
4814 }
4815 MMR3HeapFree(psz); psz = NULL;
4816
4817 rc = CFGMR3QueryStringAlloc(pCurNode, "CachePath", &pszCachePath);
4818 if (RT_FAILURE(rc) && rc != VERR_CFGM_VALUE_NOT_FOUND)
4819 {
4820 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
4821 N_("DrvVD: Configuration error: Querying \"CachePath\" as string failed"));
4822 break;
4823 }
4824 else
4825 rc = VINF_SUCCESS;
4826
4827 if (pszCachePath)
4828 {
4829 rc = CFGMR3QueryStringAlloc(pCurNode, "CacheFormat", &pszCacheFormat);
4830 if (RT_FAILURE(rc))
4831 {
4832 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
4833 N_("DrvVD: Configuration error: Querying \"CacheFormat\" as string failed"));
4834 break;
4835 }
4836 }
4837
4838 /* Mountable */
4839 rc = CFGMR3QueryBoolDef(pCfg, "Mountable", &pThis->fMountable, false);
4840 if (RT_FAILURE(rc))
4841 return PDMDRV_SET_ERROR(pDrvIns, rc, N_("Failed to query \"Mountable\" from the config"));
4842
4843 /* Locked */
4844 rc = CFGMR3QueryBoolDef(pCfg, "Locked", &pThis->fLocked, false);
4845 if (RT_FAILURE(rc))
4846 return PDMDRV_SET_ERROR(pDrvIns, rc, N_("Failed to query \"Locked\" from the config"));
4847
4848 /* BIOS visible */
4849 rc = CFGMR3QueryBoolDef(pCfg, "BIOSVisible", &pThis->fBiosVisible, true);
4850 if (RT_FAILURE(rc))
4851 return PDMDRV_SET_ERROR(pDrvIns, rc, N_("Failed to query \"BIOSVisible\" from the config"));
4852
4853 /* Cylinders */
4854 rc = CFGMR3QueryU32Def(pCfg, "Cylinders", &pThis->LCHSGeometry.cCylinders, 0);
4855 if (RT_FAILURE(rc))
4856 return PDMDRV_SET_ERROR(pDrvIns, rc, N_("Failed to query \"Cylinders\" from the config"));
4857
4858 /* Heads */
4859 rc = CFGMR3QueryU32Def(pCfg, "Heads", &pThis->LCHSGeometry.cHeads, 0);
4860 if (RT_FAILURE(rc))
4861 return PDMDRV_SET_ERROR(pDrvIns, rc, N_("Failed to query \"Heads\" from the config"));
4862
4863 /* Sectors */
4864 rc = CFGMR3QueryU32Def(pCfg, "Sectors", &pThis->LCHSGeometry.cSectors, 0);
4865 if (RT_FAILURE(rc))
4866 return PDMDRV_SET_ERROR(pDrvIns, rc, N_("Failed to query \"Sectors\" from the config"));
4867
4868 /* Uuid */
4869 rc = CFGMR3QueryStringAlloc(pCfg, "Uuid", &psz);
4870 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
4871 RTUuidClear(&pThis->Uuid);
4872 else if (RT_SUCCESS(rc))
4873 {
4874 rc = RTUuidFromStr(&pThis->Uuid, psz);
4875 if (RT_FAILURE(rc))
4876 {
4877 PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("Uuid from string failed on \"%s\""), psz);
4878 MMR3HeapFree(psz);
4879 return rc;
4880 }
4881 MMR3HeapFree(psz); psz = NULL;
4882 }
4883 else
4884 return PDMDRV_SET_ERROR(pDrvIns, rc, N_("Failed to query \"Uuid\" from the config"));
4885
4886#ifdef VBOX_PERIODIC_FLUSH
4887 rc = CFGMR3QueryU32Def(pCfg, "FlushInterval", &pThis->cbFlushInterval, 0);
4888 if (RT_FAILURE(rc))
4889 return PDMDRV_SET_ERROR(pDrvIns, rc, N_("Failed to query \"FlushInterval\" from the config"));
4890#endif /* VBOX_PERIODIC_FLUSH */
4891
4892#ifdef VBOX_IGNORE_FLUSH
4893 rc = CFGMR3QueryBoolDef(pCfg, "IgnoreFlush", &pThis->fIgnoreFlush, true);
4894 if (RT_FAILURE(rc))
4895 return PDMDRV_SET_ERROR(pDrvIns, rc, N_("Failed to query \"IgnoreFlush\" from the config"));
4896
4897 if (pThis->fIgnoreFlush)
4898 LogRel(("DrvVD: Flushes will be ignored\n"));
4899 else
4900 LogRel(("DrvVD: Flushes will be passed to the disk\n"));
4901
4902 rc = CFGMR3QueryBoolDef(pCfg, "IgnoreFlushAsync", &pThis->fIgnoreFlushAsync, false);
4903 if (RT_FAILURE(rc))
4904 return PDMDRV_SET_ERROR(pDrvIns, rc, N_("Failed to query \"IgnoreFlushAsync\" from the config"));
4905
4906 if (pThis->fIgnoreFlushAsync)
4907 LogRel(("DrvVD: Async flushes will be ignored\n"));
4908 else
4909 LogRel(("DrvVD: Async flushes will be passed to the disk\n"));
4910#endif /* VBOX_IGNORE_FLUSH */
4911
4912 rc = CFGMR3QueryBoolDef(pCurNode, "EmptyDrive", &fEmptyDrive, false);
4913 if (RT_FAILURE(rc))
4914 {
4915 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
4916 N_("DrvVD: Configuration error: Querying \"EmptyDrive\" as boolean failed"));
4917 break;
4918 }
4919
4920 rc = CFGMR3QueryU32Def(pCfg, "IoBufMax", &cbIoBufMax, 5 * _1M);
4921 if (RT_FAILURE(rc))
4922 return PDMDRV_SET_ERROR(pDrvIns, rc, N_("Failed to query \"IoBufMax\" from the config"));
4923
4924 rc = CFGMR3QueryBoolDef(pCfg, "NonRotationalMedium", &pThis->fNonRotational, false);
4925 if (RT_FAILURE(rc))
4926 return PDMDRV_SET_ERROR(pDrvIns, rc,
4927 N_("DrvVD configuration error: Querying \"NonRotationalMedium\" as boolean failed"));
4928 }
4929
4930 PCFGMNODE pParent = CFGMR3GetChild(pCurNode, "Parent");
4931 if (!pParent)
4932 break;
4933 pCurNode = pParent;
4934 iLevel++;
4935 }
4936
4937 if (pThis->pDrvMediaExPort)
4938 rc = IOBUFMgrCreate(&pThis->hIoBufMgr, cbIoBufMax, pThis->pCfgCrypto ? IOBUFMGR_F_REQUIRE_NOT_PAGABLE : IOBUFMGR_F_DEFAULT);
4939
4940 if ( !fEmptyDrive
4941 && RT_SUCCESS(rc))
4942 {
4943 /*
4944 * Create the image container and the necessary interfaces.
4945 */
4946 if (RT_SUCCESS(rc))
4947 {
4948 /*
4949 * The image has a bandwidth group but the host cache is enabled.
4950 * Use the async I/O framework but tell it to enable the host cache.
4951 */
4952 if (!fUseNewIo && pThis->pszBwGroup)
4953 {
4954 pThis->fAsyncIoWithHostCache = true;
4955 fUseNewIo = true;
4956 }
4957
4958 /** @todo quick hack to work around problems in the async I/O
4959 * implementation (rw semaphore thread ownership problem)
4960 * while a merge is running. Remove once this is fixed. */
4961 if (pThis->fMergePending)
4962 fUseNewIo = false;
4963
4964 if (RT_SUCCESS(rc) && pThis->fMergePending)
4965 {
4966 rc = RTSemFastMutexCreate(&pThis->MergeCompleteMutex);
4967 if (RT_SUCCESS(rc))
4968 rc = RTSemRWCreate(&pThis->MergeLock);
4969 if (RT_SUCCESS(rc))
4970 {
4971 pThis->VDIfThreadSync.pfnStartRead = drvvdThreadStartRead;
4972 pThis->VDIfThreadSync.pfnFinishRead = drvvdThreadFinishRead;
4973 pThis->VDIfThreadSync.pfnStartWrite = drvvdThreadStartWrite;
4974 pThis->VDIfThreadSync.pfnFinishWrite = drvvdThreadFinishWrite;
4975
4976 rc = VDInterfaceAdd(&pThis->VDIfThreadSync.Core, "DrvVD_ThreadSync", VDINTERFACETYPE_THREADSYNC,
4977 pThis, sizeof(VDINTERFACETHREADSYNC), &pThis->pVDIfsDisk);
4978 }
4979 else
4980 {
4981 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
4982 N_("DrvVD: Failed to create semaphores for \"MergePending\""));
4983 }
4984 }
4985
4986 if (RT_SUCCESS(rc))
4987 {
4988 rc = VDCreate(pThis->pVDIfsDisk, drvvdGetVDFromMediaType(pThis->enmType), &pThis->pDisk);
4989 /* Error message is already set correctly. */
4990 }
4991 }
4992
4993 if (pThis->pDrvMediaExPort && fUseNewIo)
4994 pThis->fAsyncIOSupported = true;
4995
4996 uint64_t tsStart = RTTimeNanoTS();
4997
4998 unsigned iImageIdx = 0;
4999 while (pCurNode && RT_SUCCESS(rc))
5000 {
5001 /* Allocate per-image data. */
5002 PVBOXIMAGE pImage = drvvdNewImage(pThis);
5003 if (!pImage)
5004 {
5005 rc = VERR_NO_MEMORY;
5006 break;
5007 }
5008
5009 /*
5010 * Read the image configuration.
5011 */
5012 rc = CFGMR3QueryStringAlloc(pCurNode, "Path", &pszName);
5013 if (RT_FAILURE(rc))
5014 {
5015 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
5016 N_("DrvVD: Configuration error: Querying \"Path\" as string failed"));
5017 break;
5018 }
5019
5020 rc = CFGMR3QueryStringAlloc(pCurNode, "Format", &pszFormat);
5021 if (RT_FAILURE(rc))
5022 {
5023 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
5024 N_("DrvVD: Configuration error: Querying \"Format\" as string failed"));
5025 break;
5026 }
5027
5028 bool fMergeSource;
5029 rc = CFGMR3QueryBoolDef(pCurNode, "MergeSource", &fMergeSource, false);
5030 if (RT_FAILURE(rc))
5031 {
5032 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
5033 N_("DrvVD: Configuration error: Querying \"MergeSource\" as boolean failed"));
5034 break;
5035 }
5036 if (fMergeSource)
5037 {
5038 if (pThis->uMergeSource == VD_LAST_IMAGE)
5039 pThis->uMergeSource = iImageIdx;
5040 else
5041 {
5042 rc = PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_DRIVER_INVALID_PROPERTIES,
5043 N_("DrvVD: Configuration error: Multiple \"MergeSource\" occurrences"));
5044 break;
5045 }
5046 }
5047
5048 bool fMergeTarget;
5049 rc = CFGMR3QueryBoolDef(pCurNode, "MergeTarget", &fMergeTarget, false);
5050 if (RT_FAILURE(rc))
5051 {
5052 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
5053 N_("DrvVD: Configuration error: Querying \"MergeTarget\" as boolean failed"));
5054 break;
5055 }
5056 if (fMergeTarget)
5057 {
5058 if (pThis->uMergeTarget == VD_LAST_IMAGE)
5059 pThis->uMergeTarget = iImageIdx;
5060 else
5061 {
5062 rc = PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_DRIVER_INVALID_PROPERTIES,
5063 N_("DrvVD: Configuration error: Multiple \"MergeTarget\" occurrences"));
5064 break;
5065 }
5066 }
5067
5068 PCFGMNODE pCfgVDConfig = CFGMR3GetChild(pCurNode, "VDConfig");
5069 pImage->VDIfConfig.pfnAreKeysValid = drvvdCfgAreKeysValid;
5070 pImage->VDIfConfig.pfnQuerySize = drvvdCfgQuerySize;
5071 pImage->VDIfConfig.pfnQuery = drvvdCfgQuery;
5072 pImage->VDIfConfig.pfnQueryBytes = NULL;
5073 rc = VDInterfaceAdd(&pImage->VDIfConfig.Core, "DrvVD_Config", VDINTERFACETYPE_CONFIG,
5074 pCfgVDConfig, sizeof(VDINTERFACECONFIG), &pImage->pVDIfsImage);
5075 AssertRC(rc);
5076
5077 /* Check VDConfig for encryption config. */
5078 if (pCfgVDConfig)
5079 pThis->pCfgCrypto = CFGMR3GetChild(pCfgVDConfig, "CRYPT");
5080
5081 if (pThis->pCfgCrypto)
5082 {
5083 /* Setup VDConfig interface for disk encryption support. */
5084 pThis->VDIfCfg.pfnAreKeysValid = drvvdCfgAreKeysValid;
5085 pThis->VDIfCfg.pfnQuerySize = drvvdCfgQuerySize;
5086 pThis->VDIfCfg.pfnQuery = drvvdCfgQuery;
5087 pThis->VDIfCfg.pfnQueryBytes = NULL;
5088
5089 pThis->VDIfCrypto.pfnKeyRetain = drvvdCryptoKeyRetain;
5090 pThis->VDIfCrypto.pfnKeyRelease = drvvdCryptoKeyRelease;
5091 pThis->VDIfCrypto.pfnKeyStorePasswordRetain = drvvdCryptoKeyStorePasswordRetain;
5092 pThis->VDIfCrypto.pfnKeyStorePasswordRelease = drvvdCryptoKeyStorePasswordRelease;
5093 }
5094
5095 /* Unconditionally insert the TCPNET interface, don't bother to check
5096 * if an image really needs it. Will be ignored. Since the TCPNET
5097 * interface is per image we could make this more flexible in the
5098 * future if we want to. */
5099 /* Construct TCPNET callback table depending on the config. This is
5100 * done unconditionally, as uninterested backends will ignore it. */
5101 if (fHostIP)
5102 rc = VDIfTcpNetInstDefaultCreate(&pImage->hVdIfTcpNet, &pImage->pVDIfsImage);
5103 else
5104 {
5105#ifndef VBOX_WITH_INIP
5106 rc = PDMDrvHlpVMSetError(pDrvIns, VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES,
5107 RT_SRC_POS, N_("DrvVD: Configuration error: TCP over Internal Networking not compiled in"));
5108#else /* VBOX_WITH_INIP */
5109 pImage->VDIfTcpNet.pfnSocketCreate = drvvdINIPSocketCreate;
5110 pImage->VDIfTcpNet.pfnSocketDestroy = drvvdINIPSocketDestroy;
5111 pImage->VDIfTcpNet.pfnClientConnect = drvvdINIPClientConnect;
5112 pImage->VDIfTcpNet.pfnClientClose = drvvdINIPClientClose;
5113 pImage->VDIfTcpNet.pfnIsClientConnected = drvvdINIPIsClientConnected;
5114 pImage->VDIfTcpNet.pfnSelectOne = drvvdINIPSelectOne;
5115 pImage->VDIfTcpNet.pfnRead = drvvdINIPRead;
5116 pImage->VDIfTcpNet.pfnWrite = drvvdINIPWrite;
5117 pImage->VDIfTcpNet.pfnSgWrite = drvvdINIPSgWrite;
5118 pImage->VDIfTcpNet.pfnFlush = drvvdINIPFlush;
5119 pImage->VDIfTcpNet.pfnSetSendCoalescing = drvvdINIPSetSendCoalescing;
5120 pImage->VDIfTcpNet.pfnGetLocalAddress = drvvdINIPGetLocalAddress;
5121 pImage->VDIfTcpNet.pfnGetPeerAddress = drvvdINIPGetPeerAddress;
5122 pImage->VDIfTcpNet.pfnSelectOneEx = drvvdINIPSelectOneEx;
5123 pImage->VDIfTcpNet.pfnPoke = drvvdINIPPoke;
5124
5125 rc = VDInterfaceAdd(&pImage->VDIfTcpNet.Core, "DrvVD_TCPNET",
5126 VDINTERFACETYPE_TCPNET, NULL,
5127 sizeof(VDINTERFACETCPNET), &pImage->pVDIfsImage);
5128 AssertRC(rc);
5129#endif /* VBOX_WITH_INIP */
5130 }
5131
5132 /* Insert the custom I/O interface only if we're told to use new IO.
5133 * Since the I/O interface is per image we could make this more
5134 * flexible in the future if we want to. */
5135 if (fUseNewIo)
5136 {
5137#ifdef VBOX_WITH_PDM_ASYNC_COMPLETION
5138 pImage->VDIfIo.pfnOpen = drvvdAsyncIOOpen;
5139 pImage->VDIfIo.pfnClose = drvvdAsyncIOClose;
5140 pImage->VDIfIo.pfnGetSize = drvvdAsyncIOGetSize;
5141 pImage->VDIfIo.pfnSetSize = drvvdAsyncIOSetSize;
5142 pImage->VDIfIo.pfnSetAllocationSize = drvvdAsyncIOSetAllocationSize;
5143 pImage->VDIfIo.pfnReadSync = drvvdAsyncIOReadSync;
5144 pImage->VDIfIo.pfnWriteSync = drvvdAsyncIOWriteSync;
5145 pImage->VDIfIo.pfnFlushSync = drvvdAsyncIOFlushSync;
5146 pImage->VDIfIo.pfnReadAsync = drvvdAsyncIOReadAsync;
5147 pImage->VDIfIo.pfnWriteAsync = drvvdAsyncIOWriteAsync;
5148 pImage->VDIfIo.pfnFlushAsync = drvvdAsyncIOFlushAsync;
5149#else /* !VBOX_WITH_PDM_ASYNC_COMPLETION */
5150 rc = PDMDrvHlpVMSetError(pDrvIns, VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES,
5151 RT_SRC_POS, N_("DrvVD: Configuration error: Async Completion Framework not compiled in"));
5152#endif /* !VBOX_WITH_PDM_ASYNC_COMPLETION */
5153 if (RT_SUCCESS(rc))
5154 rc = VDInterfaceAdd(&pImage->VDIfIo.Core, "DrvVD_IO", VDINTERFACETYPE_IO,
5155 pThis, sizeof(VDINTERFACEIO), &pImage->pVDIfsImage);
5156 AssertRC(rc);
5157 }
5158
5159 /*
5160 * Open the image.
5161 */
5162 unsigned uOpenFlags;
5163 if (fReadOnly || pThis->fTempReadOnly || iLevel != 0)
5164 uOpenFlags = VD_OPEN_FLAGS_READONLY;
5165 else
5166 uOpenFlags = VD_OPEN_FLAGS_NORMAL;
5167 if (fHonorZeroWrites)
5168 uOpenFlags |= VD_OPEN_FLAGS_HONOR_ZEROES;
5169 if (pThis->fAsyncIOSupported)
5170 uOpenFlags |= VD_OPEN_FLAGS_ASYNC_IO;
5171 if (pThis->fShareable)
5172 uOpenFlags |= VD_OPEN_FLAGS_SHAREABLE;
5173 if (fDiscard && iLevel == 0)
5174 uOpenFlags |= VD_OPEN_FLAGS_DISCARD;
5175 if (fInformAboutZeroBlocks)
5176 uOpenFlags |= VD_OPEN_FLAGS_INFORM_ABOUT_ZERO_BLOCKS;
5177 if ( (uOpenFlags & VD_OPEN_FLAGS_READONLY)
5178 && fSkipConsistencyChecks)
5179 uOpenFlags |= VD_OPEN_FLAGS_SKIP_CONSISTENCY_CHECKS;
5180
5181 /* Try to open backend in async I/O mode first. */
5182 rc = VDOpen(pThis->pDisk, pszFormat, pszName, uOpenFlags, pImage->pVDIfsImage);
5183 if (rc == VERR_NOT_SUPPORTED)
5184 {
5185 pThis->fAsyncIOSupported = false;
5186 uOpenFlags &= ~VD_OPEN_FLAGS_ASYNC_IO;
5187 rc = VDOpen(pThis->pDisk, pszFormat, pszName, uOpenFlags, pImage->pVDIfsImage);
5188 }
5189
5190 if (rc == VERR_VD_DISCARD_NOT_SUPPORTED)
5191 {
5192 fDiscard = false;
5193 uOpenFlags &= ~VD_OPEN_FLAGS_DISCARD;
5194 rc = VDOpen(pThis->pDisk, pszFormat, pszName, uOpenFlags, pImage->pVDIfsImage);
5195 }
5196
5197 if (!fDiscard)
5198 {
5199 pThis->IMedia.pfnDiscard = NULL;
5200 pThis->IMediaEx.pfnIoReqDiscard = NULL;
5201 }
5202
5203 if (RT_SUCCESS(rc))
5204 {
5205 LogFunc(("%d - Opened '%s' in %s mode\n",
5206 iLevel, pszName,
5207 VDIsReadOnly(pThis->pDisk) ? "read-only" : "read-write"));
5208 if ( VDIsReadOnly(pThis->pDisk)
5209 && !fReadOnly
5210 && !fMaybeReadOnly
5211 && !pThis->fTempReadOnly
5212 && iLevel == 0)
5213 {
5214 rc = PDMDrvHlpVMSetError(pDrvIns, VERR_VD_IMAGE_READ_ONLY, RT_SRC_POS,
5215 N_("Failed to open image '%s' for writing due to wrong permissions"),
5216 pszName);
5217 break;
5218 }
5219 }
5220 else
5221 {
5222 rc = PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS,
5223 N_("Failed to open image '%s' in %s mode"), pszName,
5224 (uOpenFlags & VD_OPEN_FLAGS_READONLY) ? "read-only" : "read-write");
5225 break;
5226 }
5227
5228 MMR3HeapFree(pszName);
5229 pszName = NULL;
5230 MMR3HeapFree(pszFormat);
5231 pszFormat = NULL;
5232
5233 /* next */
5234 iLevel--;
5235 iImageIdx++;
5236 pCurNode = CFGMR3GetParent(pCurNode);
5237 }
5238
5239 LogRel(("VD: Opening the disk took %lld ns\n", RTTimeNanoTS() - tsStart));
5240
5241 /* Open the cache image if set. */
5242 if ( RT_SUCCESS(rc)
5243 && RT_VALID_PTR(pszCachePath))
5244 {
5245 /* Insert the custom I/O interface only if we're told to use new IO.
5246 * Since the I/O interface is per image we could make this more
5247 * flexible in the future if we want to. */
5248 if (fUseNewIo)
5249 {
5250#ifdef VBOX_WITH_PDM_ASYNC_COMPLETION
5251 pThis->VDIfIoCache.pfnOpen = drvvdAsyncIOOpen;
5252 pThis->VDIfIoCache.pfnClose = drvvdAsyncIOClose;
5253 pThis->VDIfIoCache.pfnGetSize = drvvdAsyncIOGetSize;
5254 pThis->VDIfIoCache.pfnSetSize = drvvdAsyncIOSetSize;
5255 pThis->VDIfIoCache.pfnReadSync = drvvdAsyncIOReadSync;
5256 pThis->VDIfIoCache.pfnWriteSync = drvvdAsyncIOWriteSync;
5257 pThis->VDIfIoCache.pfnFlushSync = drvvdAsyncIOFlushSync;
5258 pThis->VDIfIoCache.pfnReadAsync = drvvdAsyncIOReadAsync;
5259 pThis->VDIfIoCache.pfnWriteAsync = drvvdAsyncIOWriteAsync;
5260 pThis->VDIfIoCache.pfnFlushAsync = drvvdAsyncIOFlushAsync;
5261#else /* !VBOX_WITH_PDM_ASYNC_COMPLETION */
5262 rc = PDMDrvHlpVMSetError(pDrvIns, VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES,
5263 RT_SRC_POS, N_("DrvVD: Configuration error: Async Completion Framework not compiled in"));
5264#endif /* !VBOX_WITH_PDM_ASYNC_COMPLETION */
5265 if (RT_SUCCESS(rc))
5266 rc = VDInterfaceAdd(&pThis->VDIfIoCache.Core, "DrvVD_IO", VDINTERFACETYPE_IO,
5267 pThis, sizeof(VDINTERFACEIO), &pThis->pVDIfsCache);
5268 AssertRC(rc);
5269 }
5270
5271 rc = VDCacheOpen(pThis->pDisk, pszCacheFormat, pszCachePath, VD_OPEN_FLAGS_NORMAL, pThis->pVDIfsCache);
5272 if (RT_FAILURE(rc))
5273 rc = PDMDRV_SET_ERROR(pDrvIns, rc, N_("DrvVD: Could not open cache image"));
5274 }
5275
5276 if (RT_VALID_PTR(pszCachePath))
5277 MMR3HeapFree(pszCachePath);
5278 if (RT_VALID_PTR(pszCacheFormat))
5279 MMR3HeapFree(pszCacheFormat);
5280
5281 if ( RT_SUCCESS(rc)
5282 && pThis->fMergePending
5283 && ( pThis->uMergeSource == VD_LAST_IMAGE
5284 || pThis->uMergeTarget == VD_LAST_IMAGE))
5285 {
5286 rc = PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_DRIVER_INVALID_PROPERTIES,
5287 N_("DrvVD: Configuration error: Inconsistent image merge data"));
5288 }
5289
5290 /* Create the block cache if enabled. */
5291 if ( fUseBlockCache
5292 && !pThis->fShareable
5293 && !fDiscard
5294 && !pThis->pCfgCrypto /* Disk encryption disables the block cache for security reasons */
5295 && RT_SUCCESS(rc))
5296 {
5297 /*
5298 * We need a unique ID for the block cache (to identify the owner of data
5299 * blocks in a saved state). UUIDs are not really suitable because
5300 * there are image formats which don't support them. Furthermore it is
5301 * possible that a new diff image was attached after a saved state
5302 * which changes the UUID.
5303 * However the device "name + device instance + LUN" triple the disk is
5304 * attached to is always constant for saved states.
5305 */
5306 char *pszId = NULL;
5307 uint32_t iInstance, iLUN;
5308 const char *pcszController;
5309
5310 rc = pThis->pDrvMediaPort->pfnQueryDeviceLocation(pThis->pDrvMediaPort, &pcszController,
5311 &iInstance, &iLUN);
5312 if (RT_FAILURE(rc))
5313 rc = PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_DRIVER_INVALID_PROPERTIES,
5314 N_("DrvVD: Configuration error: Could not query device data"));
5315 else
5316 {
5317 int cbStr = RTStrAPrintf(&pszId, "%s-%d-%d", pcszController, iInstance, iLUN);
5318
5319 if (cbStr > 0)
5320 {
5321 rc = PDMDrvHlpBlkCacheRetain(pDrvIns, &pThis->pBlkCache,
5322 drvvdBlkCacheXferCompleteIoReq,
5323 drvvdBlkCacheXferEnqueue,
5324 drvvdBlkCacheXferEnqueueDiscard,
5325 pszId);
5326 if (rc == VERR_NOT_SUPPORTED)
5327 {
5328 LogRel(("VD: Block cache is not supported\n"));
5329 rc = VINF_SUCCESS;
5330 }
5331 else
5332 AssertRC(rc);
5333
5334 RTStrFree(pszId);
5335 }
5336 else
5337 rc = PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_DRIVER_INVALID_PROPERTIES,
5338 N_("DrvVD: Out of memory when creating block cache"));
5339 }
5340 }
5341
5342 if (RT_SUCCESS(rc))
5343 rc = drvvdSetupFilters(pThis, pCfg);
5344
5345 /*
5346 * Register a load-done callback so we can undo TempReadOnly config before
5347 * we get to drvvdResume. Automatically deregistered upon destruction.
5348 */
5349 if (RT_SUCCESS(rc))
5350 rc = PDMDrvHlpSSMRegisterEx(pDrvIns, 0 /* version */, 0 /* cbGuess */,
5351 NULL /*pfnLivePrep*/, NULL /*pfnLiveExec*/, NULL /*pfnLiveVote*/,
5352 NULL /*pfnSavePrep*/, NULL /*pfnSaveExec*/, NULL /*pfnSaveDone*/,
5353 NULL /*pfnDonePrep*/, NULL /*pfnLoadExec*/, drvvdLoadDone);
5354
5355 /* Setup the boot acceleration stuff if enabled. */
5356 if (RT_SUCCESS(rc) && pThis->fBootAccelEnabled)
5357 {
5358 pThis->cbDisk = VDGetSize(pThis->pDisk, VD_LAST_IMAGE);
5359 Assert(pThis->cbDisk > 0);
5360 pThis->pbData = (uint8_t *)RTMemAllocZ(pThis->cbBootAccelBuffer);
5361 if (pThis->pbData)
5362 {
5363 pThis->fBootAccelActive = true;
5364 pThis->offDisk = 0;
5365 pThis->cbDataValid = 0;
5366 LogRel(("VD: Boot acceleration enabled\n"));
5367 }
5368 else
5369 LogRel(("VD: Boot acceleration, out of memory, disabled\n"));
5370 }
5371
5372 if ( RTUuidIsNull(&pThis->Uuid)
5373 && pThis->enmType == PDMMEDIATYPE_HARD_DISK)
5374 VDGetUuid(pThis->pDisk, 0, &pThis->Uuid);
5375
5376 /*
5377 * Automatically upgrade the floppy drive if the specified one is too
5378 * small to represent the whole boot time image. (We cannot do this later
5379 * since the BIOS (and others) gets the info via CMOS.)
5380 *
5381 * This trick should make 2.88 images as well as the fake 15.6 and 63.5 MB
5382 * images despite the hardcoded default 1.44 drive.
5383 */
5384 if ( PDMMEDIATYPE_IS_FLOPPY(pThis->enmType)
5385 && pThis->pDisk)
5386 {
5387 uint64_t const cbFloppyImg = VDGetSize(pThis->pDisk, VD_LAST_IMAGE);
5388 PDMMEDIATYPE const enmCfgType = pThis->enmType;
5389 switch (enmCfgType)
5390 {
5391 default:
5392 AssertFailed();
5393 RT_FALL_THRU();
5394 case PDMMEDIATYPE_FLOPPY_360:
5395 if (cbFloppyImg > 40 * 2 * 9 * 512)
5396 pThis->enmType = PDMMEDIATYPE_FLOPPY_720;
5397 RT_FALL_THRU();
5398 case PDMMEDIATYPE_FLOPPY_720:
5399 if (cbFloppyImg > 80 * 2 * 14 * 512)
5400 pThis->enmType = PDMMEDIATYPE_FLOPPY_1_20;
5401 RT_FALL_THRU();
5402 case PDMMEDIATYPE_FLOPPY_1_20:
5403 if (cbFloppyImg > 80 * 2 * 20 * 512)
5404 pThis->enmType = PDMMEDIATYPE_FLOPPY_1_44;
5405 RT_FALL_THRU();
5406 case PDMMEDIATYPE_FLOPPY_1_44:
5407 if (cbFloppyImg > 80 * 2 * 24 * 512)
5408 pThis->enmType = PDMMEDIATYPE_FLOPPY_2_88;
5409 RT_FALL_THRU();
5410 case PDMMEDIATYPE_FLOPPY_2_88:
5411 if (cbFloppyImg > 80 * 2 * 48 * 512)
5412 pThis->enmType = PDMMEDIATYPE_FLOPPY_FAKE_15_6;
5413 RT_FALL_THRU();
5414 case PDMMEDIATYPE_FLOPPY_FAKE_15_6:
5415 if (cbFloppyImg > 255 * 2 * 63 * 512)
5416 pThis->enmType = PDMMEDIATYPE_FLOPPY_FAKE_63_5;
5417 RT_FALL_THRU();
5418 case PDMMEDIATYPE_FLOPPY_FAKE_63_5:
5419 if (cbFloppyImg > 255 * 2 * 255 * 512)
5420 LogRel(("Warning: Floppy image is larger that 63.5 MB! (%llu bytes)\n", cbFloppyImg));
5421 break;
5422 }
5423 if (pThis->enmType != enmCfgType)
5424 LogRel(("DrvVD: Automatically upgraded floppy drive from %s to %s to better support the %u byte image\n",
5425 drvvdGetTypeName(enmCfgType), drvvdGetTypeName(pThis->enmType), cbFloppyImg));
5426 }
5427 } /* !fEmptyDrive */
5428
5429 if (RT_SUCCESS(rc))
5430 drvvdStatsRegister(pThis);
5431
5432 if (RT_FAILURE(rc))
5433 {
5434 if (RT_VALID_PTR(pszName))
5435 MMR3HeapFree(pszName);
5436 if (RT_VALID_PTR(pszFormat))
5437 MMR3HeapFree(pszFormat);
5438 /* drvvdDestruct does the rest. */
5439 }
5440
5441 LogFlowFunc(("returns %Rrc\n", rc));
5442 return rc;
5443}
5444
5445/**
5446 * VBox disk container media driver registration record.
5447 */
5448const PDMDRVREG g_DrvVD =
5449{
5450 /* u32Version */
5451 PDM_DRVREG_VERSION,
5452 /* szName */
5453 "VD",
5454 /* szRCMod */
5455 "",
5456 /* szR0Mod */
5457 "",
5458 /* pszDescription */
5459 "Generic VBox disk media driver.",
5460 /* fFlags */
5461 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
5462 /* fClass. */
5463 PDM_DRVREG_CLASS_MEDIA,
5464 /* cMaxInstances */
5465 ~0U,
5466 /* cbInstance */
5467 sizeof(VBOXDISK),
5468 /* pfnConstruct */
5469 drvvdConstruct,
5470 /* pfnDestruct */
5471 drvvdDestruct,
5472 /* pfnRelocate */
5473 NULL,
5474 /* pfnIOCtl */
5475 NULL,
5476 /* pfnPowerOn */
5477 drvvdPowerOn,
5478 /* pfnReset */
5479 drvvdReset,
5480 /* pfnSuspend */
5481 drvvdSuspend,
5482 /* pfnResume */
5483 drvvdResume,
5484 /* pfnAttach */
5485 NULL,
5486 /* pfnDetach */
5487 NULL,
5488 /* pfnPowerOff */
5489 drvvdPowerOff,
5490 /* pfnSoftReset */
5491 NULL,
5492 /* u32EndVersion */
5493 PDM_DRVREG_VERSION
5494};
5495
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