VirtualBox

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

Last change on this file since 74441 was 74309, checked in by vboxsync, 6 years ago

Devices/Storage/DrvVD: Don't ignore the IgnoreFlushAsync option

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