VirtualBox

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

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

VMM,Main,++: Retired the unfinished FTM component.

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