VirtualBox

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

Last change on this file since 71963 was 71775, checked in by vboxsync, 7 years ago

Devices/Storage: Properly account for requests currently waiting for I/O memory when suspending/resuming to avoid hangs upon suspend (devices would not complete suspending because aiting requests would be marked as active but could not complete)

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 218.3 KB
Line 
1/* $Id: DrvVD.cpp 71775 2018-04-09 14:54:57Z 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_OFFSETOF(VBOXDISK, IMedia)) )
99
100/** Saved state version of an I/O request .*/
101#define DRVVD_IOREQ_SAVED_STATE_VERSION UINT32_C(1)
102/** Maximum number of request errors in the release log before muting. */
103#define DRVVD_MAX_LOG_REL_ERRORS 100
104
105/** Forward declaration for the dis kcontainer. */
106typedef struct VBOXDISK *PVBOXDISK;
107
108/**
109 * VBox disk container, image information, private part.
110 */
111
112typedef struct VBOXIMAGE
113{
114 /** Pointer to next image. */
115 struct VBOXIMAGE *pNext;
116 /** Pointer to list of VD interfaces. Per-image. */
117 PVDINTERFACE pVDIfsImage;
118 /** Configuration information interface. */
119 VDINTERFACECONFIG VDIfConfig;
120 /** TCP network stack interface. */
121 VDINTERFACETCPNET VDIfTcpNet;
122 /** I/O interface. */
123 VDINTERFACEIO VDIfIo;
124} VBOXIMAGE, *PVBOXIMAGE;
125
126/**
127 * Storage backend data.
128 */
129typedef struct DRVVDSTORAGEBACKEND
130{
131 /** PDM async completion end point. */
132 PPDMASYNCCOMPLETIONENDPOINT pEndpoint;
133 /** The template. */
134 PPDMASYNCCOMPLETIONTEMPLATE pTemplate;
135 /** Event semaphore for synchronous operations. */
136 RTSEMEVENT EventSem;
137 /** Flag whether a synchronous operation is currently pending. */
138 volatile bool fSyncIoPending;
139 /** Return code of the last completed request. */
140 int rcReqLast;
141 /** Callback routine */
142 PFNVDCOMPLETED pfnCompleted;
143} DRVVDSTORAGEBACKEND, *PDRVVDSTORAGEBACKEND;
144
145/**
146 * VD I/O request state.
147 */
148typedef enum VDIOREQSTATE
149{
150 /** Invalid. */
151 VDIOREQSTATE_INVALID = 0,
152 /** The request is not in use and resides on the free list. */
153 VDIOREQSTATE_FREE,
154 /** The request was just allocated and is not active. */
155 VDIOREQSTATE_ALLOCATED,
156 /** The request was allocated and is in use. */
157 VDIOREQSTATE_ACTIVE,
158 /** The request was suspended and is not actively processed. */
159 VDIOREQSTATE_SUSPENDED,
160 /** The request is in the last step of completion and syncs memory. */
161 VDIOREQSTATE_COMPLETING,
162 /** The request completed. */
163 VDIOREQSTATE_COMPLETED,
164 /** The request was aborted but wasn't returned as complete from the storage
165 * layer below us. */
166 VDIOREQSTATE_CANCELED,
167 /** 32bit hack. */
168 VDIOREQSTATE_32BIT_HACK = 0x7fffffff
169} VDIOREQSTATE;
170
171/**
172 * VD I/O Request.
173 */
174typedef struct PDMMEDIAEXIOREQINT
175{
176 /** List node for the list of allocated requests. */
177 RTLISTNODE NdAllocatedList;
178 /** List for requests waiting for I/O memory or on the redo list. */
179 RTLISTNODE NdLstWait;
180 /** I/O request type. */
181 PDMMEDIAEXIOREQTYPE enmType;
182 /** Request state. */
183 volatile VDIOREQSTATE enmState;
184 /** I/O request ID. */
185 PDMMEDIAEXIOREQID uIoReqId;
186 /** Pointer to the disk container. */
187 PVBOXDISK pDisk;
188 /** Flags. */
189 uint32_t fFlags;
190 /** Timestamp when the request was submitted. */
191 uint64_t tsSubmit;
192 /** Type dependent data. */
193 union
194 {
195 /** Read/Write request sepcific data. */
196 struct
197 {
198 /** Start offset of the request. */
199 uint64_t offStart;
200 /** Size of the request. */
201 size_t cbReq;
202 /** Size left for this request. */
203 size_t cbReqLeft;
204 /** Size of the allocated I/O buffer. */
205 size_t cbIoBuf;
206 /** Pointer to the S/G buffer. */
207 PRTSGBUF pSgBuf;
208 /** Flag whether the pointer is a direct buffer or
209 * was allocated by us. */
210 bool fDirectBuf;
211 /** Buffer management data based on the fDirectBuf flag. */
212 union
213 {
214 /** Direct buffer. */
215 struct
216 {
217 /** Segment for the data buffer. */
218 RTSGSEG Seg;
219 /** S/G buffer structure. */
220 RTSGBUF SgBuf;
221 } Direct;
222 /** I/O buffer descriptor. */
223 IOBUFDESC IoBuf;
224 };
225 } ReadWrite;
226 /** Discard specific data. */
227 struct
228 {
229 /** Pointer to array of ranges to discard. */
230 PRTRANGE paRanges;
231 /** Number of ranges to discard. */
232 unsigned cRanges;
233 } Discard;
234 };
235 /** Allocator specific memory - variable size. */
236 uint8_t abAlloc[1];
237} PDMMEDIAEXIOREQINT;
238/** Pointer to a VD I/O request. */
239typedef PDMMEDIAEXIOREQINT *PPDMMEDIAEXIOREQINT;
240
241/**
242 * Structure for holding a list of allocated requests.
243 */
244typedef struct VDLSTIOREQALLOC
245{
246 /** Mutex protecting the table of allocated requests. */
247 RTSEMFASTMUTEX hMtxLstIoReqAlloc;
248 /** List anchor. */
249 RTLISTANCHOR LstIoReqAlloc;
250} VDLSTIOREQALLOC;
251typedef VDLSTIOREQALLOC *PVDLSTIOREQALLOC;
252
253/** Number of bins for allocated requests. */
254#define DRVVD_VDIOREQ_ALLOC_BINS 8
255
256/**
257 * VBox disk container media main structure, private part.
258 *
259 * @implements PDMIMEDIA
260 * @implements PDMIMEDIAEX
261 * @implements PDMIMOUNT
262 * @implements VDINTERFACEERROR
263 * @implements VDINTERFACETCPNET
264 * @implements VDINTERFACEASYNCIO
265 * @implements VDINTERFACECONFIG
266 */
267typedef struct VBOXDISK
268{
269 /** The VBox disk container. */
270 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
3267 *pcbReqIo = cbReqIo;
3268
3269 LogFlowFunc(("returns %Rrc *pcbReqIo=%zu\n", rc, *pcbReqIo));
3270 return rc;
3271}
3272
3273/**
3274 * Wrapper around the various ways to flush all data to the underlying medium (cache, async vs. sync).
3275 *
3276 * @returns VBox status code.
3277 * @param pThis VBox disk container instance data.
3278 * @param pIoReq I/O request to process.
3279 */
3280static int drvvdMediaExIoReqFlushWrapper(PVBOXDISK pThis, PPDMMEDIAEXIOREQINT pIoReq)
3281{
3282 int rc = VINF_SUCCESS;
3283
3284 LogFlowFunc(("pThis=%#p pIoReq=%#p\n", pThis, pIoReq));
3285
3286 if ( pThis->fAsyncIOSupported
3287 && !(pIoReq->fFlags & PDMIMEDIAEX_F_SYNC))
3288 {
3289 if (pThis->pBlkCache)
3290 {
3291 rc = PDMR3BlkCacheFlush(pThis->pBlkCache, pIoReq);
3292 if (rc == VINF_SUCCESS)
3293 rc = VINF_VD_ASYNC_IO_FINISHED;
3294 else if (rc == VINF_AIO_TASK_PENDING)
3295 rc = VERR_VD_ASYNC_IO_IN_PROGRESS;
3296 }
3297 else
3298 rc = VDAsyncFlush(pThis->pDisk, drvvdMediaExIoReqComplete, pThis, pIoReq);
3299 }
3300 else
3301 {
3302 rc = VDFlush(pThis->pDisk);
3303 if (RT_SUCCESS(rc))
3304 rc = VINF_VD_ASYNC_IO_FINISHED;
3305 }
3306
3307 LogFlowFunc(("returns %Rrc\n", rc));
3308 return rc;
3309}
3310
3311/**
3312 * Wrapper around the various ways to discard data blocks on the underlying medium (cache, async vs. sync).
3313 *
3314 * @returns VBox status code.
3315 * @param pThis VBox disk container instance data.
3316 * @param pIoReq I/O request to process.
3317 */
3318static int drvvdMediaExIoReqDiscardWrapper(PVBOXDISK pThis, PPDMMEDIAEXIOREQINT pIoReq)
3319{
3320 int rc = VINF_SUCCESS;
3321
3322 LogFlowFunc(("pThis=%#p pIoReq=%#p\n", pThis, pIoReq));
3323
3324 if ( pThis->fAsyncIOSupported
3325 && !(pIoReq->fFlags & PDMIMEDIAEX_F_SYNC))
3326 {
3327 if (pThis->pBlkCache)
3328 {
3329 rc = PDMR3BlkCacheDiscard(pThis->pBlkCache, pIoReq->Discard.paRanges, pIoReq->Discard.cRanges, pIoReq);
3330 if (rc == VINF_SUCCESS)
3331 rc = VINF_VD_ASYNC_IO_FINISHED;
3332 else if (rc == VINF_AIO_TASK_PENDING)
3333 rc = VERR_VD_ASYNC_IO_IN_PROGRESS;
3334 }
3335 else
3336 rc = VDAsyncDiscardRanges(pThis->pDisk, pIoReq->Discard.paRanges, pIoReq->Discard.cRanges,
3337 drvvdMediaExIoReqComplete, pThis, pIoReq);
3338 }
3339 else
3340 {
3341 rc = VDDiscardRanges(pThis->pDisk, pIoReq->Discard.paRanges, pIoReq->Discard.cRanges);
3342 if (RT_SUCCESS(rc))
3343 rc = VINF_VD_ASYNC_IO_FINISHED;
3344 }
3345
3346 LogFlowFunc(("returns %Rrc\n", rc));
3347 return rc;
3348}
3349
3350/**
3351 * Processes a read/write request.
3352 *
3353 * @returns VBox status code.
3354 * @param pThis VBox disk container instance data.
3355 * @param pIoReq I/O request to process.
3356 * @param fUpNotify Flag whether to notify the driver/device above us about the completion.
3357 */
3358static int drvvdMediaExIoReqReadWriteProcess(PVBOXDISK pThis, PPDMMEDIAEXIOREQINT pIoReq, bool fUpNotify)
3359{
3360 int rc = VINF_SUCCESS;
3361
3362 LogFlowFunc(("pThis=%#p pIoReq=%#p fUpNotify=%RTbool\n", pThis, pIoReq, fUpNotify));
3363
3364 Assert(pIoReq->enmType == PDMMEDIAEXIOREQTYPE_READ || pIoReq->enmType == PDMMEDIAEXIOREQTYPE_WRITE);
3365
3366 rc = drvvdKeyCheckPrereqs(pThis, false /* fSetError */);
3367
3368 while ( pIoReq->ReadWrite.cbReqLeft
3369 && rc == VINF_SUCCESS)
3370 {
3371 Assert(pIoReq->ReadWrite.cbIoBuf > 0);
3372
3373 size_t cbReqIo = RT_MIN(pIoReq->ReadWrite.cbReqLeft, pIoReq->ReadWrite.cbIoBuf);
3374
3375 if (pIoReq->enmType == PDMMEDIAEXIOREQTYPE_READ)
3376 rc = drvvdMediaExIoReqReadWrapper(pThis, pIoReq, cbReqIo, &cbReqIo);
3377 else
3378 {
3379 /* Sync memory buffer from the request initiator. */
3380 rc = drvvdMediaExIoReqBufSync(pThis, pIoReq, true /* fToIoBuf */);
3381 if (RT_SUCCESS(rc))
3382 rc = drvvdMediaExIoReqWriteWrapper(pThis, pIoReq, cbReqIo, &cbReqIo);
3383 }
3384
3385 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
3386 rc = VINF_PDM_MEDIAEX_IOREQ_IN_PROGRESS;
3387 else if (rc == VINF_VD_ASYNC_IO_FINISHED)
3388 {
3389 /*
3390 * Don't sync the buffer or update the I/O state for the last chunk as it is done
3391 * already in the completion worker called below.
3392 */
3393 if (cbReqIo < pIoReq->ReadWrite.cbReqLeft)
3394 {
3395 if (pIoReq->enmType == PDMMEDIAEXIOREQTYPE_READ)
3396 rc = drvvdMediaExIoReqBufSync(pThis, pIoReq, false /* fToIoBuf */);
3397 else
3398 rc = VINF_SUCCESS;
3399 pIoReq->ReadWrite.offStart += cbReqIo;
3400 pIoReq->ReadWrite.cbReqLeft -= cbReqIo;
3401 }
3402 else
3403 {
3404 rc = VINF_SUCCESS;
3405 break;
3406 }
3407 }
3408 }
3409
3410 if (rc != VINF_PDM_MEDIAEX_IOREQ_IN_PROGRESS)
3411 rc = drvvdMediaExIoReqCompleteWorker(pThis, pIoReq, rc, fUpNotify);
3412
3413 LogFlowFunc(("returns %Rrc\n", rc));
3414 return rc;
3415}
3416
3417
3418/**
3419 * Tries to process any requests waiting for available I/O memory.
3420 *
3421 * @returns nothing.
3422 * @param pThis VBox disk container instance data.
3423 */
3424static void drvvdMediaExIoReqProcessWaiting(PVBOXDISK pThis)
3425{
3426 uint32_t cIoReqsWaiting = ASMAtomicXchgU32(&pThis->cIoReqsWaiting, 0);
3427 if (cIoReqsWaiting > 0)
3428 {
3429 RTLISTANCHOR LstIoReqProcess;
3430 RTLISTANCHOR LstIoReqCanceled;
3431 RTListInit(&LstIoReqProcess);
3432 RTListInit(&LstIoReqCanceled);
3433
3434 /* Try to process as many requests as possible. */
3435 RTCritSectEnter(&pThis->CritSectIoReqsIoBufWait);
3436 PPDMMEDIAEXIOREQINT pIoReqCur, pIoReqNext;
3437
3438 RTListForEachSafe(&pThis->LstIoReqIoBufWait, pIoReqCur, pIoReqNext, PDMMEDIAEXIOREQINT, NdLstWait)
3439 {
3440 LogFlowFunc(("Found I/O request %#p on waiting list, trying to allocate buffer of size %zu bytes\n",
3441 pIoReqCur, pIoReqCur->ReadWrite.cbReq));
3442
3443 /* Allocate a suitable I/O buffer for this request. */
3444 int rc = IOBUFMgrAllocBuf(pThis->hIoBufMgr, &pIoReqCur->ReadWrite.IoBuf, pIoReqCur->ReadWrite.cbReq,
3445 &pIoReqCur->ReadWrite.cbIoBuf);
3446 if (rc == VINF_SUCCESS)
3447 {
3448 Assert(pIoReqCur->ReadWrite.cbIoBuf > 0);
3449
3450 cIoReqsWaiting--;
3451 RTListNodeRemove(&pIoReqCur->NdLstWait);
3452
3453 pIoReqCur->ReadWrite.fDirectBuf = false;
3454 pIoReqCur->ReadWrite.pSgBuf = &pIoReqCur->ReadWrite.IoBuf.SgBuf;
3455
3456 bool fXchg = ASMAtomicCmpXchgU32((volatile uint32_t *)&pIoReqCur->enmState,
3457 VDIOREQSTATE_ACTIVE, VDIOREQSTATE_ALLOCATED);
3458 if (RT_UNLIKELY(!fXchg))
3459 {
3460 /* Must have been canceled inbetween. */
3461 Assert(pIoReqCur->enmState == VDIOREQSTATE_CANCELED);
3462
3463 /* Free the buffer here already again to let other requests get a chance to allocate the memory. */
3464 IOBUFMgrFreeBuf(&pIoReqCur->ReadWrite.IoBuf);
3465 pIoReqCur->ReadWrite.cbIoBuf = 0;
3466 RTListAppend(&LstIoReqCanceled, &pIoReqCur->NdLstWait);
3467 }
3468 else
3469 {
3470 ASMAtomicIncU32(&pThis->cIoReqsActive);
3471 RTListAppend(&LstIoReqProcess, &pIoReqCur->NdLstWait);
3472 }
3473 }
3474 else
3475 {
3476 Assert(rc == VERR_NO_MEMORY);
3477 break;
3478 }
3479 }
3480 RTCritSectLeave(&pThis->CritSectIoReqsIoBufWait);
3481
3482 ASMAtomicAddU32(&pThis->cIoReqsWaiting, cIoReqsWaiting);
3483
3484 /* Process the requests we could allocate memory for and the ones which got canceled outside the lock now. */
3485 RTListForEachSafe(&LstIoReqCanceled, pIoReqCur, pIoReqNext, PDMMEDIAEXIOREQINT, NdLstWait)
3486 {
3487 RTListNodeRemove(&pIoReqCur->NdLstWait);
3488 drvvdMediaExIoReqCompleteWorker(pThis, pIoReqCur, VERR_PDM_MEDIAEX_IOREQ_CANCELED, true /* fUpNotify */);
3489 }
3490
3491 RTListForEachSafe(&LstIoReqProcess, pIoReqCur, pIoReqNext, PDMMEDIAEXIOREQINT, NdLstWait)
3492 {
3493 RTListNodeRemove(&pIoReqCur->NdLstWait);
3494 drvvdMediaExIoReqReadWriteProcess(pThis, pIoReqCur, true /* fUpNotify */);
3495 }
3496 }
3497}
3498
3499/**
3500 * Frees a I/O memory buffer allocated previously.
3501 *
3502 * @returns nothing.
3503 * @param pThis VBox disk container instance data.
3504 * @param pIoReq I/O request for which to free memory.
3505 */
3506DECLINLINE(void) drvvdMediaExIoReqBufFree(PVBOXDISK pThis, PPDMMEDIAEXIOREQINT pIoReq)
3507{
3508 LogFlowFunc(("pThis=%#p pIoReq=%#p{.cbIoBuf=%zu}\n", pThis, pIoReq, pIoReq->ReadWrite.cbIoBuf));
3509
3510 if ( ( pIoReq->enmType == PDMMEDIAEXIOREQTYPE_READ
3511 || pIoReq->enmType == PDMMEDIAEXIOREQTYPE_WRITE)
3512 && !pIoReq->ReadWrite.fDirectBuf
3513 && pIoReq->ReadWrite.cbIoBuf > 0)
3514 {
3515 IOBUFMgrFreeBuf(&pIoReq->ReadWrite.IoBuf);
3516
3517 if (!ASMAtomicReadBool(&pThis->fSuspending))
3518 drvvdMediaExIoReqProcessWaiting(pThis);
3519 }
3520
3521 LogFlowFunc(("returns\n"));
3522}
3523
3524
3525/**
3526 * Returns a string description of the given request state.
3527 *
3528 * @returns Pointer to the stringified state.
3529 * @param enmState The state.
3530 */
3531DECLINLINE(const char *) drvvdMediaExIoReqStateStringify(VDIOREQSTATE enmState)
3532{
3533#define STATE2STR(a_State) case VDIOREQSTATE_##a_State: return #a_State
3534 switch (enmState)
3535 {
3536 STATE2STR(INVALID);
3537 STATE2STR(FREE);
3538 STATE2STR(ALLOCATED);
3539 STATE2STR(ACTIVE);
3540 STATE2STR(SUSPENDED);
3541 STATE2STR(COMPLETING);
3542 STATE2STR(COMPLETED);
3543 STATE2STR(CANCELED);
3544 default:
3545 AssertMsgFailed(("Unknown state %u\n", enmState));
3546 return "UNKNOWN";
3547 }
3548#undef STATE2STR
3549}
3550
3551
3552/**
3553 * Returns a string description of the given request type.
3554 *
3555 * @returns Pointer to the stringified type.
3556 * @param enmType The request type.
3557 */
3558DECLINLINE(const char *) drvvdMediaExIoReqTypeStringify(PDMMEDIAEXIOREQTYPE enmType)
3559{
3560#define TYPE2STR(a_Type) case PDMMEDIAEXIOREQTYPE_##a_Type: return #a_Type
3561 switch (enmType)
3562 {
3563 TYPE2STR(INVALID);
3564 TYPE2STR(FLUSH);
3565 TYPE2STR(WRITE);
3566 TYPE2STR(READ);
3567 TYPE2STR(DISCARD);
3568 TYPE2STR(SCSI);
3569 default:
3570 AssertMsgFailed(("Unknown type %u\n", enmType));
3571 return "UNKNOWN";
3572 }
3573#undef TYPE2STR
3574}
3575
3576
3577/**
3578 * Dumps the interesting bits about the given I/O request to the release log.
3579 *
3580 * @returns nothing.
3581 * @param pThis VBox disk container instance data.
3582 * @param pIoReq The I/O request to dump.
3583 */
3584static void drvvdMediaExIoReqLogRel(PVBOXDISK pThis, PPDMMEDIAEXIOREQINT pIoReq)
3585{
3586 uint64_t offStart = 0;
3587 size_t cbReq = 0;
3588 size_t cbLeft = 0;
3589 size_t cbBufSize = 0;
3590 uint64_t tsActive = RTTimeMilliTS() - pIoReq->tsSubmit;
3591
3592 if ( pIoReq->enmType == PDMMEDIAEXIOREQTYPE_READ
3593 || pIoReq->enmType == PDMMEDIAEXIOREQTYPE_WRITE)
3594 {
3595 offStart = pIoReq->ReadWrite.offStart;
3596 cbReq = pIoReq->ReadWrite.cbReq;
3597 cbLeft = pIoReq->ReadWrite.cbReqLeft;
3598 cbBufSize = pIoReq->ReadWrite.cbIoBuf;
3599 }
3600
3601 LogRel(("VD#%u: Request{%#p}:\n"
3602 " Type=%s State=%s Id=%#llx SubmitTs=%llu {%llu} Flags=%#x\n"
3603 " Offset=%llu Size=%zu Left=%zu BufSize=%zu\n",
3604 pThis->pDrvIns->iInstance, pIoReq,
3605 drvvdMediaExIoReqTypeStringify(pIoReq->enmType),
3606 drvvdMediaExIoReqStateStringify(pIoReq->enmState),
3607 pIoReq->uIoReqId, pIoReq->tsSubmit, tsActive, pIoReq->fFlags,
3608 offStart, cbReq, cbLeft, cbBufSize));
3609}
3610
3611
3612/**
3613 * Returns whether the VM is in a running state.
3614 *
3615 * @returns Flag indicating whether the VM is currently in a running state.
3616 * @param pThis VBox disk container instance data.
3617 */
3618DECLINLINE(bool) drvvdMediaExIoReqIsVmRunning(PVBOXDISK pThis)
3619{
3620 VMSTATE enmVmState = PDMDrvHlpVMState(pThis->pDrvIns);
3621 if ( enmVmState == VMSTATE_RESUMING
3622 || enmVmState == VMSTATE_RUNNING
3623 || enmVmState == VMSTATE_RUNNING_LS
3624 || enmVmState == VMSTATE_RUNNING_FT
3625 || enmVmState == VMSTATE_RESETTING
3626 || enmVmState == VMSTATE_RESETTING_LS
3627 || enmVmState == VMSTATE_SOFT_RESETTING
3628 || enmVmState == VMSTATE_SOFT_RESETTING_LS
3629 || enmVmState == VMSTATE_SUSPENDING
3630 || enmVmState == VMSTATE_SUSPENDING_LS
3631 || enmVmState == VMSTATE_SUSPENDING_EXT_LS)
3632 return true;
3633
3634 return false;
3635}
3636
3637/**
3638 * @copydoc FNVDASYNCTRANSFERCOMPLETE
3639 */
3640static DECLCALLBACK(void) drvvdMediaExIoReqComplete(void *pvUser1, void *pvUser2, int rcReq)
3641{
3642 PVBOXDISK pThis = (PVBOXDISK)pvUser1;
3643 PPDMMEDIAEXIOREQINT pIoReq = (PPDMMEDIAEXIOREQINT)pvUser2;
3644
3645 drvvdMediaExIoReqCompleteWorker(pThis, pIoReq, rcReq, true /* fUpNotify */);
3646}
3647
3648/**
3649 * Tries to cancel the given I/O request returning the result.
3650 *
3651 * @returns Flag whether the request was successfully canceled or whether it
3652 * already complete inbetween.
3653 * @param pThis VBox disk container instance data.
3654 * @param pIoReq The I/O request to cancel.
3655 */
3656static bool drvvdMediaExIoReqCancel(PVBOXDISK pThis, PPDMMEDIAEXIOREQINT pIoReq)
3657{
3658 bool fXchg = false;
3659 VDIOREQSTATE enmStateOld = (VDIOREQSTATE)ASMAtomicReadU32((volatile uint32_t *)&pIoReq->enmState);
3660
3661 drvvdMediaExIoReqLogRel(pThis, pIoReq);
3662
3663 /*
3664 * We might have to try canceling the request multiple times if it transitioned from
3665 * ALLOCATED to ACTIVE or to SUSPENDED between reading the state and trying to change it.
3666 */
3667 while ( ( enmStateOld == VDIOREQSTATE_ALLOCATED
3668 || enmStateOld == VDIOREQSTATE_ACTIVE
3669 || enmStateOld == VDIOREQSTATE_SUSPENDED)
3670 && !fXchg)
3671 {
3672 fXchg = ASMAtomicCmpXchgU32((volatile uint32_t *)&pIoReq->enmState, VDIOREQSTATE_CANCELED, enmStateOld);
3673 if (fXchg)
3674 break;
3675
3676 enmStateOld = (VDIOREQSTATE)ASMAtomicReadU32((volatile uint32_t *)&pIoReq->enmState);
3677 }
3678
3679 if (fXchg)
3680 ASMAtomicDecU32(&pThis->cIoReqsActive);
3681
3682 return fXchg;
3683}
3684
3685/**
3686 * @interface_method_impl{PDMIMEDIAEX,pfnQueryFeatures}
3687 */
3688static DECLCALLBACK(int) drvvdQueryFeatures(PPDMIMEDIAEX pInterface, uint32_t *pfFeatures)
3689{
3690 PVBOXDISK pThis = RT_FROM_MEMBER(pInterface, VBOXDISK, IMediaEx);
3691
3692 AssertPtrReturn(pfFeatures, VERR_INVALID_POINTER);
3693
3694 uint32_t fFeatures = 0;
3695 if (pThis->fAsyncIOSupported)
3696 fFeatures |= PDMIMEDIAEX_FEATURE_F_ASYNC;
3697 if (pThis->IMedia.pfnDiscard)
3698 fFeatures |= PDMIMEDIAEX_FEATURE_F_DISCARD;
3699
3700 *pfFeatures = fFeatures;
3701
3702 return VINF_SUCCESS;
3703}
3704
3705
3706/**
3707 * @interface_method_impl{PDMIMEDIAEX,pfnNotifySuspend}
3708 */
3709static DECLCALLBACK(void) drvvdNotifySuspend(PPDMIMEDIAEX pInterface)
3710{
3711 PVBOXDISK pThis = RT_FROM_MEMBER(pInterface, VBOXDISK, IMediaEx);
3712
3713 ASMAtomicXchgBool(&pThis->fSuspending, true);
3714
3715 /* Mark all waiting requests as suspended so they don't get accounted for. */
3716 RTCritSectEnter(&pThis->CritSectIoReqsIoBufWait);
3717 PPDMMEDIAEXIOREQINT pIoReqCur, pIoReqNext;
3718 RTListForEachSafe(&pThis->LstIoReqIoBufWait, pIoReqCur, pIoReqNext, PDMMEDIAEXIOREQINT, NdLstWait)
3719 {
3720 pThis->pDrvMediaExPort->pfnIoReqStateChanged(pThis->pDrvMediaExPort, pIoReqCur, &pIoReqCur->abAlloc[0],
3721 PDMMEDIAEXIOREQSTATE_SUSPENDED);
3722 }
3723 RTCritSectLeave(&pThis->CritSectIoReqsIoBufWait);
3724}
3725
3726
3727/**
3728 * @interface_method_impl{PDMIMEDIAEX,pfnIoReqAllocSizeSet}
3729 */
3730static DECLCALLBACK(int) drvvdIoReqAllocSizeSet(PPDMIMEDIAEX pInterface, size_t cbIoReqAlloc)
3731{
3732 PVBOXDISK pThis = RT_FROM_MEMBER(pInterface, VBOXDISK, IMediaEx);
3733 if (RT_UNLIKELY(pThis->hIoReqCache != NIL_RTMEMCACHE))
3734 return VERR_INVALID_STATE;
3735
3736 return RTMemCacheCreate(&pThis->hIoReqCache, sizeof(PDMMEDIAEXIOREQINT) + cbIoReqAlloc, 0, UINT32_MAX,
3737 NULL, NULL, NULL, 0);
3738}
3739
3740/**
3741 * @interface_method_impl{PDMIMEDIAEX,pfnIoReqAlloc}
3742 */
3743static DECLCALLBACK(int) drvvdIoReqAlloc(PPDMIMEDIAEX pInterface, PPDMMEDIAEXIOREQ phIoReq, void **ppvIoReqAlloc,
3744 PDMMEDIAEXIOREQID uIoReqId, uint32_t fFlags)
3745{
3746 PVBOXDISK pThis = RT_FROM_MEMBER(pInterface, VBOXDISK, IMediaEx);
3747
3748 AssertReturn(!(fFlags & ~PDMIMEDIAEX_F_VALID), VERR_INVALID_PARAMETER);
3749
3750 PPDMMEDIAEXIOREQINT pIoReq = (PPDMMEDIAEXIOREQINT)RTMemCacheAlloc(pThis->hIoReqCache);
3751
3752 if (RT_UNLIKELY(!pIoReq))
3753 return VERR_NO_MEMORY;
3754
3755 pIoReq->uIoReqId = uIoReqId;
3756 pIoReq->fFlags = fFlags;
3757 pIoReq->pDisk = pThis;
3758 pIoReq->enmState = VDIOREQSTATE_ALLOCATED;
3759 pIoReq->enmType = PDMMEDIAEXIOREQTYPE_INVALID;
3760
3761 int rc = drvvdMediaExIoReqInsert(pThis, pIoReq);
3762 if (RT_SUCCESS(rc))
3763 {
3764 *phIoReq = pIoReq;
3765 *ppvIoReqAlloc = &pIoReq->abAlloc[0];
3766 }
3767 else
3768 RTMemCacheFree(pThis->hIoReqCache, pIoReq);
3769
3770 return rc;
3771}
3772
3773/**
3774 * @interface_method_impl{PDMIMEDIAEX,pfnIoReqFree}
3775 */
3776static DECLCALLBACK(int) drvvdIoReqFree(PPDMIMEDIAEX pInterface, PDMMEDIAEXIOREQ hIoReq)
3777{
3778 PVBOXDISK pThis = RT_FROM_MEMBER(pInterface, VBOXDISK, IMediaEx);
3779 PPDMMEDIAEXIOREQINT pIoReq = hIoReq;
3780
3781 if ( pIoReq->enmState != VDIOREQSTATE_COMPLETED
3782 && pIoReq->enmState != VDIOREQSTATE_ALLOCATED)
3783 return VERR_PDM_MEDIAEX_IOREQ_INVALID_STATE;
3784
3785 /* Remove from allocated list. */
3786 int rc = drvvdMediaExIoReqRemove(pThis, pIoReq);
3787 if (RT_FAILURE(rc))
3788 return rc;
3789
3790 /* Free any associated I/O memory. */
3791 drvvdMediaExIoReqBufFree(pThis, pIoReq);
3792
3793 /* For discard request discard the range array. */
3794 if ( pIoReq->enmType == PDMMEDIAEXIOREQTYPE_DISCARD
3795 && pIoReq->Discard.paRanges)
3796 {
3797 RTMemFree(pIoReq->Discard.paRanges);
3798 pIoReq->Discard.paRanges = NULL;
3799 }
3800
3801 pIoReq->enmState = VDIOREQSTATE_FREE;
3802 RTMemCacheFree(pThis->hIoReqCache, pIoReq);
3803 return VINF_SUCCESS;
3804}
3805
3806/**
3807 * @interface_method_impl{PDMIMEDIAEX,pfnIoReqQueryResidual}
3808 */
3809static DECLCALLBACK(int) drvvdIoReqQueryResidual(PPDMIMEDIAEX pInterface, PDMMEDIAEXIOREQ hIoReq, size_t *pcbResidual)
3810{
3811 RT_NOREF1(pInterface);
3812
3813 PPDMMEDIAEXIOREQINT pIoReq = hIoReq;
3814
3815 if (pIoReq->enmState != VDIOREQSTATE_COMPLETED)
3816 return VERR_PDM_MEDIAEX_IOREQ_INVALID_STATE;
3817
3818 if ( pIoReq->enmType != PDMMEDIAEXIOREQTYPE_READ
3819 && pIoReq->enmType != PDMMEDIAEXIOREQTYPE_WRITE
3820 && pIoReq->enmType != PDMMEDIAEXIOREQTYPE_FLUSH)
3821 return VERR_PDM_MEDIAEX_IOREQ_INVALID_STATE;
3822
3823 *pcbResidual = 0; /* No data left to transfer always. */
3824 return VINF_SUCCESS;
3825}
3826
3827/**
3828 * @interface_method_impl{PDMIMEDIAEX,pfnIoReqQueryXferSize}
3829 */
3830static DECLCALLBACK(int) drvvdIoReqQueryXferSize(PPDMIMEDIAEX pInterface, PDMMEDIAEXIOREQ hIoReq, size_t *pcbXfer)
3831{
3832 int rc = VINF_SUCCESS;
3833 RT_NOREF1(pInterface);
3834
3835 PPDMMEDIAEXIOREQINT pIoReq = hIoReq;
3836
3837 if (pIoReq->enmState != VDIOREQSTATE_COMPLETED)
3838 return VERR_PDM_MEDIAEX_IOREQ_INVALID_STATE;
3839
3840 if ( pIoReq->enmType == PDMMEDIAEXIOREQTYPE_READ
3841 || pIoReq->enmType == PDMMEDIAEXIOREQTYPE_WRITE)
3842 *pcbXfer = pIoReq->ReadWrite.cbReq;
3843 else if (pIoReq->enmType == PDMMEDIAEXIOREQTYPE_FLUSH)
3844 *pcbXfer = 0;
3845 else
3846 rc = VERR_PDM_MEDIAEX_IOREQ_INVALID_STATE;
3847
3848 return rc;
3849}
3850
3851/**
3852 * @interface_method_impl{PDMIMEDIAEX,pfnIoReqCancelAll}
3853 */
3854static DECLCALLBACK(int) drvvdIoReqCancelAll(PPDMIMEDIAEX pInterface)
3855{
3856 int rc = VINF_SUCCESS;
3857 PVBOXDISK pThis = RT_FROM_MEMBER(pInterface, VBOXDISK, IMediaEx);
3858
3859 LogRel(("VD#%u: Cancelling all active requests\n", pThis->pDrvIns->iInstance));
3860
3861 for (unsigned idxBin = 0; idxBin < RT_ELEMENTS(pThis->aIoReqAllocBins); idxBin++)
3862 {
3863 rc = RTSemFastMutexRequest(pThis->aIoReqAllocBins[idxBin].hMtxLstIoReqAlloc);
3864 if (RT_SUCCESS(rc))
3865 {
3866 /* Search for I/O request with ID. */
3867 PPDMMEDIAEXIOREQINT pIt;
3868
3869 RTListForEach(&pThis->aIoReqAllocBins[idxBin].LstIoReqAlloc, pIt, PDMMEDIAEXIOREQINT, NdAllocatedList)
3870 {
3871 drvvdMediaExIoReqCancel(pThis, pIt);
3872 }
3873 RTSemFastMutexRelease(pThis->aIoReqAllocBins[idxBin].hMtxLstIoReqAlloc);
3874 }
3875 }
3876
3877 return rc;
3878}
3879
3880/**
3881 * @interface_method_impl{PDMIMEDIAEX,pfnIoReqCancel}
3882 */
3883static DECLCALLBACK(int) drvvdIoReqCancel(PPDMIMEDIAEX pInterface, PDMMEDIAEXIOREQID uIoReqId)
3884{
3885 PVBOXDISK pThis = RT_FROM_MEMBER(pInterface, VBOXDISK, IMediaEx);
3886 unsigned idxBin = drvvdMediaExIoReqIdHash(uIoReqId);
3887
3888 LogRel(("VD#%u: Trying to cancel request %#llx\n", pThis->pDrvIns->iInstance, uIoReqId));
3889
3890 int rc = RTSemFastMutexRequest(pThis->aIoReqAllocBins[idxBin].hMtxLstIoReqAlloc);
3891 if (RT_SUCCESS(rc))
3892 {
3893 /* Search for I/O request with ID. */
3894 PPDMMEDIAEXIOREQINT pIt;
3895 rc = VERR_PDM_MEDIAEX_IOREQID_NOT_FOUND;
3896
3897 RTListForEach(&pThis->aIoReqAllocBins[idxBin].LstIoReqAlloc, pIt, PDMMEDIAEXIOREQINT, NdAllocatedList)
3898 {
3899 if (pIt->uIoReqId == uIoReqId)
3900 {
3901 if (drvvdMediaExIoReqCancel(pThis, pIt))
3902 rc = VINF_SUCCESS;
3903
3904 break;
3905 }
3906 }
3907 RTSemFastMutexRelease(pThis->aIoReqAllocBins[idxBin].hMtxLstIoReqAlloc);
3908 }
3909
3910 return rc;
3911}
3912
3913/**
3914 * @interface_method_impl{PDMIMEDIAEX,pfnIoReqRead}
3915 */
3916static DECLCALLBACK(int) drvvdIoReqRead(PPDMIMEDIAEX pInterface, PDMMEDIAEXIOREQ hIoReq, uint64_t off, size_t cbRead)
3917{
3918 PVBOXDISK pThis = RT_FROM_MEMBER(pInterface, VBOXDISK, IMediaEx);
3919 PPDMMEDIAEXIOREQINT pIoReq = hIoReq;
3920 VDIOREQSTATE enmState = (VDIOREQSTATE)ASMAtomicReadU32((volatile uint32_t *)&pIoReq->enmState);
3921
3922 if (RT_UNLIKELY(enmState == VDIOREQSTATE_CANCELED))
3923 return VERR_PDM_MEDIAEX_IOREQ_CANCELED;
3924
3925 if (RT_UNLIKELY(enmState != VDIOREQSTATE_ALLOCATED))
3926 return VERR_PDM_MEDIAEX_IOREQ_INVALID_STATE;
3927
3928 STAM_REL_COUNTER_INC(&pThis->StatReqsSubmitted);
3929 STAM_REL_COUNTER_INC(&pThis->StatReqsRead);
3930
3931 pIoReq->enmType = PDMMEDIAEXIOREQTYPE_READ;
3932 pIoReq->tsSubmit = RTTimeMilliTS();
3933 pIoReq->ReadWrite.offStart = off;
3934 pIoReq->ReadWrite.cbReq = cbRead;
3935 pIoReq->ReadWrite.cbReqLeft = cbRead;
3936 /* Allocate a suitable I/O buffer for this request. */
3937 int rc = drvvdMediaExIoReqBufAlloc(pThis, pIoReq, cbRead);
3938 if (rc == VINF_SUCCESS)
3939 {
3940 bool fXchg = ASMAtomicCmpXchgU32((volatile uint32_t *)&pIoReq->enmState, VDIOREQSTATE_ACTIVE, VDIOREQSTATE_ALLOCATED);
3941 if (RT_UNLIKELY(!fXchg))
3942 {
3943 /* Must have been canceled inbetween. */
3944 Assert(pIoReq->enmState == VDIOREQSTATE_CANCELED);
3945 return VERR_PDM_MEDIAEX_IOREQ_CANCELED;
3946 }
3947 ASMAtomicIncU32(&pThis->cIoReqsActive);
3948
3949 rc = drvvdMediaExIoReqReadWriteProcess(pThis, pIoReq, false /* fUpNotify */);
3950 }
3951
3952 return rc;
3953}
3954
3955/**
3956 * @interface_method_impl{PDMIMEDIAEX,pfnIoReqWrite}
3957 */
3958static DECLCALLBACK(int) drvvdIoReqWrite(PPDMIMEDIAEX pInterface, PDMMEDIAEXIOREQ hIoReq, uint64_t off, size_t cbWrite)
3959{
3960 PVBOXDISK pThis = RT_FROM_MEMBER(pInterface, VBOXDISK, IMediaEx);
3961 PPDMMEDIAEXIOREQINT pIoReq = hIoReq;
3962 VDIOREQSTATE enmState = (VDIOREQSTATE)ASMAtomicReadU32((volatile uint32_t *)&pIoReq->enmState);
3963
3964 if (RT_UNLIKELY(enmState == VDIOREQSTATE_CANCELED))
3965 return VERR_PDM_MEDIAEX_IOREQ_CANCELED;
3966
3967 if (RT_UNLIKELY(enmState != VDIOREQSTATE_ALLOCATED))
3968 return VERR_PDM_MEDIAEX_IOREQ_INVALID_STATE;
3969
3970 STAM_REL_COUNTER_INC(&pThis->StatReqsSubmitted);
3971 STAM_REL_COUNTER_INC(&pThis->StatReqsWrite);
3972
3973 pIoReq->enmType = PDMMEDIAEXIOREQTYPE_WRITE;
3974 pIoReq->tsSubmit = RTTimeMilliTS();
3975 pIoReq->ReadWrite.offStart = off;
3976 pIoReq->ReadWrite.cbReq = cbWrite;
3977 pIoReq->ReadWrite.cbReqLeft = cbWrite;
3978 /* Allocate a suitable I/O buffer for this request. */
3979 int rc = drvvdMediaExIoReqBufAlloc(pThis, pIoReq, cbWrite);
3980 if (rc == VINF_SUCCESS)
3981 {
3982 bool fXchg = ASMAtomicCmpXchgU32((volatile uint32_t *)&pIoReq->enmState, VDIOREQSTATE_ACTIVE, VDIOREQSTATE_ALLOCATED);
3983 if (RT_UNLIKELY(!fXchg))
3984 {
3985 /* Must have been canceled inbetween. */
3986 Assert(pIoReq->enmState == VDIOREQSTATE_CANCELED);
3987 return VERR_PDM_MEDIAEX_IOREQ_CANCELED;
3988 }
3989 ASMAtomicIncU32(&pThis->cIoReqsActive);
3990
3991 rc = drvvdMediaExIoReqReadWriteProcess(pThis, pIoReq, false /* fUpNotify */);
3992 }
3993
3994 return rc;
3995}
3996
3997/**
3998 * @interface_method_impl{PDMIMEDIAEX,pfnIoReqFlush}
3999 */
4000static DECLCALLBACK(int) drvvdIoReqFlush(PPDMIMEDIAEX pInterface, PDMMEDIAEXIOREQ hIoReq)
4001{
4002 PVBOXDISK pThis = RT_FROM_MEMBER(pInterface, VBOXDISK, IMediaEx);
4003 PPDMMEDIAEXIOREQINT pIoReq = hIoReq;
4004 VDIOREQSTATE enmState = (VDIOREQSTATE)ASMAtomicReadU32((volatile uint32_t *)&pIoReq->enmState);
4005
4006 if (RT_UNLIKELY(enmState == VDIOREQSTATE_CANCELED))
4007 return VERR_PDM_MEDIAEX_IOREQ_CANCELED;
4008
4009 if (RT_UNLIKELY(enmState != VDIOREQSTATE_ALLOCATED))
4010 return VERR_PDM_MEDIAEX_IOREQ_INVALID_STATE;
4011
4012 STAM_REL_COUNTER_INC(&pThis->StatReqsSubmitted);
4013 STAM_REL_COUNTER_INC(&pThis->StatReqsFlush);
4014
4015 pIoReq->enmType = PDMMEDIAEXIOREQTYPE_FLUSH;
4016 pIoReq->tsSubmit = RTTimeMilliTS();
4017 bool fXchg = ASMAtomicCmpXchgU32((volatile uint32_t *)&pIoReq->enmState, VDIOREQSTATE_ACTIVE, VDIOREQSTATE_ALLOCATED);
4018 if (RT_UNLIKELY(!fXchg))
4019 {
4020 /* Must have been canceled inbetween. */
4021 Assert(pIoReq->enmState == VDIOREQSTATE_CANCELED);
4022 return VERR_PDM_MEDIAEX_IOREQ_CANCELED;
4023 }
4024
4025 ASMAtomicIncU32(&pThis->cIoReqsActive);
4026 int rc = drvvdMediaExIoReqFlushWrapper(pThis, pIoReq);
4027 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
4028 rc = VINF_PDM_MEDIAEX_IOREQ_IN_PROGRESS;
4029 else if (rc == VINF_VD_ASYNC_IO_FINISHED)
4030 rc = VINF_SUCCESS;
4031
4032 if (rc != VINF_PDM_MEDIAEX_IOREQ_IN_PROGRESS)
4033 rc = drvvdMediaExIoReqCompleteWorker(pThis, pIoReq, rc, false /* fUpNotify */);
4034
4035 return rc;
4036}
4037
4038/**
4039 * @interface_method_impl{PDMIMEDIAEX,pfnIoReqDiscard}
4040 */
4041static DECLCALLBACK(int) drvvdIoReqDiscard(PPDMIMEDIAEX pInterface, PDMMEDIAEXIOREQ hIoReq, unsigned cRangesMax)
4042{
4043 PVBOXDISK pThis = RT_FROM_MEMBER(pInterface, VBOXDISK, IMediaEx);
4044 PPDMMEDIAEXIOREQINT pIoReq = hIoReq;
4045 VDIOREQSTATE enmState = (VDIOREQSTATE)ASMAtomicReadU32((volatile uint32_t *)&pIoReq->enmState);
4046
4047 if (RT_UNLIKELY(enmState == VDIOREQSTATE_CANCELED))
4048 return VERR_PDM_MEDIAEX_IOREQ_CANCELED;
4049
4050 if (RT_UNLIKELY(enmState != VDIOREQSTATE_ALLOCATED))
4051 return VERR_PDM_MEDIAEX_IOREQ_INVALID_STATE;
4052
4053 STAM_REL_COUNTER_INC(&pThis->StatReqsSubmitted);
4054 STAM_REL_COUNTER_INC(&pThis->StatReqsDiscard);
4055
4056 /* Copy the ranges over now, this can be optimized in the future. */
4057 pIoReq->Discard.paRanges = (PRTRANGE)RTMemAllocZ(cRangesMax * sizeof(RTRANGE));
4058 if (RT_UNLIKELY(!pIoReq->Discard.paRanges))
4059 return VERR_NO_MEMORY;
4060
4061 int rc = pThis->pDrvMediaExPort->pfnIoReqQueryDiscardRanges(pThis->pDrvMediaExPort, pIoReq, &pIoReq->abAlloc[0],
4062 0, cRangesMax, pIoReq->Discard.paRanges,
4063 &pIoReq->Discard.cRanges);
4064 if (RT_SUCCESS(rc))
4065 {
4066 pIoReq->enmType = PDMMEDIAEXIOREQTYPE_DISCARD;
4067 pIoReq->tsSubmit = RTTimeMilliTS();
4068 bool fXchg = ASMAtomicCmpXchgU32((volatile uint32_t *)&pIoReq->enmState, VDIOREQSTATE_ACTIVE, VDIOREQSTATE_ALLOCATED);
4069 if (RT_UNLIKELY(!fXchg))
4070 {
4071 /* Must have been canceled inbetween. */
4072 Assert(pIoReq->enmState == VDIOREQSTATE_CANCELED);
4073 return VERR_PDM_MEDIAEX_IOREQ_CANCELED;
4074 }
4075
4076 ASMAtomicIncU32(&pThis->cIoReqsActive);
4077 rc = drvvdMediaExIoReqDiscardWrapper(pThis, pIoReq);
4078 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
4079 rc = VINF_PDM_MEDIAEX_IOREQ_IN_PROGRESS;
4080 else if (rc == VINF_VD_ASYNC_IO_FINISHED)
4081 rc = VINF_SUCCESS;
4082
4083 if (rc != VINF_PDM_MEDIAEX_IOREQ_IN_PROGRESS)
4084 rc = drvvdMediaExIoReqCompleteWorker(pThis, pIoReq, rc, false /* fUpNotify */);
4085 }
4086
4087 return rc;
4088}
4089
4090/**
4091 * @interface_method_impl{PDMIMEDIAEX,pfnIoReqSendScsiCmd}
4092 */
4093static DECLCALLBACK(int) drvvdIoReqSendScsiCmd(PPDMIMEDIAEX pInterface, PDMMEDIAEXIOREQ hIoReq, uint32_t uLun,
4094 const uint8_t *pbCdb, size_t cbCdb, PDMMEDIAEXIOREQSCSITXDIR enmTxDir,
4095 size_t cbBuf, uint8_t *pabSense, size_t cbSense, uint8_t *pu8ScsiSts,
4096 uint32_t cTimeoutMillies)
4097{
4098 RT_NOREF10(pInterface, uLun, pbCdb, cbCdb, enmTxDir, cbBuf, pabSense, cbSense, pu8ScsiSts, cTimeoutMillies);
4099 PPDMMEDIAEXIOREQINT pIoReq = hIoReq;
4100 VDIOREQSTATE enmState = (VDIOREQSTATE)ASMAtomicReadU32((volatile uint32_t *)&pIoReq->enmState);
4101
4102 if (RT_UNLIKELY(enmState == VDIOREQSTATE_CANCELED))
4103 return VERR_PDM_MEDIAEX_IOREQ_CANCELED;
4104
4105 if (RT_UNLIKELY(enmState != VDIOREQSTATE_ALLOCATED))
4106 return VERR_PDM_MEDIAEX_IOREQ_INVALID_STATE;
4107
4108 return VERR_NOT_SUPPORTED;
4109}
4110
4111/**
4112 * @interface_method_impl{PDMIMEDIAEX,pfnIoReqGetActiveCount}
4113 */
4114static DECLCALLBACK(uint32_t) drvvdIoReqGetActiveCount(PPDMIMEDIAEX pInterface)
4115{
4116 PVBOXDISK pThis = RT_FROM_MEMBER(pInterface, VBOXDISK, IMediaEx);
4117 return ASMAtomicReadU32(&pThis->cIoReqsActive);
4118}
4119
4120/**
4121 * @interface_method_impl{PDMIMEDIAEX,pfnIoReqGetSuspendedCount}
4122 */
4123static DECLCALLBACK(uint32_t) drvvdIoReqGetSuspendedCount(PPDMIMEDIAEX pInterface)
4124{
4125 PVBOXDISK pThis = RT_FROM_MEMBER(pInterface, VBOXDISK, IMediaEx);
4126
4127 AssertReturn(!drvvdMediaExIoReqIsVmRunning(pThis), 0);
4128
4129 uint32_t cIoReqSuspended = 0;
4130 PPDMMEDIAEXIOREQINT pIoReq;
4131 RTCritSectEnter(&pThis->CritSectIoReqRedo);
4132 RTListForEach(&pThis->LstIoReqRedo, pIoReq, PDMMEDIAEXIOREQINT, NdLstWait)
4133 {
4134 cIoReqSuspended++;
4135 }
4136 RTCritSectLeave(&pThis->CritSectIoReqRedo);
4137
4138 return cIoReqSuspended + pThis->cIoReqsWaiting;
4139}
4140
4141/**
4142 * @interface_method_impl{PDMIMEDIAEX,pfnIoReqQuerySuspendedStart}
4143 */
4144static DECLCALLBACK(int) drvvdIoReqQuerySuspendedStart(PPDMIMEDIAEX pInterface, PPDMMEDIAEXIOREQ phIoReq,
4145 void **ppvIoReqAlloc)
4146{
4147 PVBOXDISK pThis = RT_FROM_MEMBER(pInterface, VBOXDISK, IMediaEx);
4148
4149 AssertReturn(!drvvdMediaExIoReqIsVmRunning(pThis), VERR_INVALID_STATE);
4150 AssertReturn(!( RTListIsEmpty(&pThis->LstIoReqRedo)
4151 && RTListIsEmpty(&pThis->LstIoReqIoBufWait)), VERR_NOT_FOUND);
4152
4153 PRTLISTANCHOR pLst;
4154 PRTCRITSECT pCritSect;
4155 if (!RTListIsEmpty(&pThis->LstIoReqRedo))
4156 {
4157 pLst = &pThis->LstIoReqRedo;
4158 pCritSect = &pThis->CritSectIoReqRedo;
4159 }
4160 else
4161 {
4162 pLst = &pThis->LstIoReqIoBufWait;
4163 pCritSect = &pThis->CritSectIoReqsIoBufWait;
4164 }
4165
4166 RTCritSectEnter(pCritSect);
4167 PPDMMEDIAEXIOREQINT pIoReq = RTListGetFirst(pLst, PDMMEDIAEXIOREQINT, NdLstWait);
4168 *phIoReq = pIoReq;
4169 *ppvIoReqAlloc = &pIoReq->abAlloc[0];
4170 RTCritSectLeave(pCritSect);
4171
4172 return VINF_SUCCESS;
4173}
4174
4175/**
4176 * @interface_method_impl{PDMIMEDIAEX,pfnIoReqQuerySuspendedNext}
4177 */
4178static DECLCALLBACK(int) drvvdIoReqQuerySuspendedNext(PPDMIMEDIAEX pInterface, PDMMEDIAEXIOREQ hIoReq,
4179 PPDMMEDIAEXIOREQ phIoReqNext, void **ppvIoReqAllocNext)
4180{
4181 PVBOXDISK pThis = RT_FROM_MEMBER(pInterface, VBOXDISK, IMediaEx);
4182 PPDMMEDIAEXIOREQINT pIoReq = hIoReq;
4183
4184 AssertReturn(!drvvdMediaExIoReqIsVmRunning(pThis), VERR_INVALID_STATE);
4185 AssertPtrReturn(pIoReq, VERR_INVALID_HANDLE);
4186 AssertReturn( ( pIoReq->enmState == VDIOREQSTATE_SUSPENDED
4187 && ( !RTListNodeIsLast(&pThis->LstIoReqRedo, &pIoReq->NdLstWait)
4188 || !RTListIsEmpty(&pThis->LstIoReqIoBufWait)))
4189 || ( pIoReq->enmState == VDIOREQSTATE_ALLOCATED
4190 && !RTListNodeIsLast(&pThis->LstIoReqIoBufWait, &pIoReq->NdLstWait)), VERR_NOT_FOUND);
4191
4192 PPDMMEDIAEXIOREQINT pIoReqNext;
4193 if (pIoReq->enmState == VDIOREQSTATE_SUSPENDED)
4194 {
4195 if (!RTListNodeIsLast(&pThis->LstIoReqRedo, &pIoReq->NdLstWait))
4196 {
4197 RTCritSectEnter(&pThis->CritSectIoReqRedo);
4198 pIoReqNext = RTListNodeGetNext(&pIoReq->NdLstWait, PDMMEDIAEXIOREQINT, NdLstWait);
4199 RTCritSectLeave(&pThis->CritSectIoReqRedo);
4200 }
4201 else
4202 {
4203 RTCritSectEnter(&pThis->CritSectIoReqsIoBufWait);
4204 pIoReqNext = RTListGetFirst(&pThis->LstIoReqIoBufWait, PDMMEDIAEXIOREQINT, NdLstWait);
4205 RTCritSectLeave(&pThis->CritSectIoReqsIoBufWait);
4206 }
4207 }
4208 else
4209 {
4210 RTCritSectEnter(&pThis->CritSectIoReqsIoBufWait);
4211 pIoReqNext = RTListNodeGetNext(&pIoReq->NdLstWait, PDMMEDIAEXIOREQINT, NdLstWait);
4212 RTCritSectLeave(&pThis->CritSectIoReqsIoBufWait);
4213 }
4214
4215 *phIoReqNext = pIoReqNext;
4216 *ppvIoReqAllocNext = &pIoReqNext->abAlloc[0];
4217
4218 return VINF_SUCCESS;
4219}
4220
4221/**
4222 * @interface_method_impl{PDMIMEDIAEX,pfnIoReqSuspendedSave}
4223 */
4224static DECLCALLBACK(int) drvvdIoReqSuspendedSave(PPDMIMEDIAEX pInterface, PSSMHANDLE pSSM, PDMMEDIAEXIOREQ hIoReq)
4225{
4226 PVBOXDISK pThis = RT_FROM_MEMBER(pInterface, VBOXDISK, IMediaEx);
4227 PPDMMEDIAEXIOREQINT pIoReq = hIoReq;
4228
4229 AssertReturn(!drvvdMediaExIoReqIsVmRunning(pThis), VERR_INVALID_STATE);
4230 AssertPtrReturn(pIoReq, VERR_INVALID_HANDLE);
4231 AssertReturn( pIoReq->enmState == VDIOREQSTATE_SUSPENDED
4232 || pIoReq->enmState == VDIOREQSTATE_ALLOCATED, VERR_INVALID_STATE);
4233
4234 SSMR3PutU32(pSSM, DRVVD_IOREQ_SAVED_STATE_VERSION);
4235 SSMR3PutU32(pSSM, (uint32_t)pIoReq->enmType);
4236 SSMR3PutU32(pSSM, pIoReq->uIoReqId);
4237 SSMR3PutU32(pSSM, pIoReq->fFlags);
4238 if ( pIoReq->enmType == PDMMEDIAEXIOREQTYPE_READ
4239 || pIoReq->enmType == PDMMEDIAEXIOREQTYPE_WRITE)
4240 {
4241 SSMR3PutU64(pSSM, pIoReq->ReadWrite.offStart);
4242 SSMR3PutU64(pSSM, pIoReq->ReadWrite.cbReq);
4243 SSMR3PutU64(pSSM, pIoReq->ReadWrite.cbReqLeft);
4244 }
4245 else if (pIoReq->enmType == PDMMEDIAEXIOREQTYPE_DISCARD)
4246 {
4247 SSMR3PutU32(pSSM, pIoReq->Discard.cRanges);
4248 for (unsigned i = 0; i < pIoReq->Discard.cRanges; i++)
4249 {
4250 SSMR3PutU64(pSSM, pIoReq->Discard.paRanges[i].offStart);
4251 SSMR3PutU64(pSSM, pIoReq->Discard.paRanges[i].cbRange);
4252 }
4253 }
4254
4255 return SSMR3PutU32(pSSM, UINT32_MAX); /* sanity/terminator */
4256}
4257
4258/**
4259 * @interface_method_impl{PDMIMEDIAEX,pfnIoReqSuspendedLoad}
4260 */
4261static DECLCALLBACK(int) drvvdIoReqSuspendedLoad(PPDMIMEDIAEX pInterface, PSSMHANDLE pSSM, PDMMEDIAEXIOREQ hIoReq)
4262{
4263 PVBOXDISK pThis = RT_FROM_MEMBER(pInterface, VBOXDISK, IMediaEx);
4264 PPDMMEDIAEXIOREQINT pIoReq = hIoReq;
4265
4266 AssertReturn(!drvvdMediaExIoReqIsVmRunning(pThis), VERR_INVALID_STATE);
4267 AssertPtrReturn(pIoReq, VERR_INVALID_HANDLE);
4268 AssertReturn(pIoReq->enmState == VDIOREQSTATE_ALLOCATED, VERR_INVALID_STATE);
4269
4270 uint32_t u32;
4271 uint64_t u64;
4272 int rc = VINF_SUCCESS;
4273 bool fPlaceOnRedoList = true;
4274
4275 SSMR3GetU32(pSSM, &u32);
4276 if (u32 <= DRVVD_IOREQ_SAVED_STATE_VERSION)
4277 {
4278 SSMR3GetU32(pSSM, &u32);
4279 AssertReturn( u32 == PDMMEDIAEXIOREQTYPE_WRITE
4280 || u32 == PDMMEDIAEXIOREQTYPE_READ
4281 || u32 == PDMMEDIAEXIOREQTYPE_DISCARD
4282 || u32 == PDMMEDIAEXIOREQTYPE_FLUSH,
4283 VERR_SSM_DATA_UNIT_FORMAT_CHANGED);
4284 pIoReq->enmType = (PDMMEDIAEXIOREQTYPE)u32;
4285
4286 SSMR3GetU32(pSSM, &u32);
4287 AssertReturn(u32 == pIoReq->uIoReqId, VERR_SSM_DATA_UNIT_FORMAT_CHANGED);
4288
4289 SSMR3GetU32(pSSM, &u32);
4290 AssertReturn(u32 == pIoReq->fFlags, VERR_SSM_DATA_UNIT_FORMAT_CHANGED);
4291
4292 if ( pIoReq->enmType == PDMMEDIAEXIOREQTYPE_READ
4293 || pIoReq->enmType == PDMMEDIAEXIOREQTYPE_WRITE)
4294 {
4295 SSMR3GetU64(pSSM, &pIoReq->ReadWrite.offStart);
4296 SSMR3GetU64(pSSM, &u64);
4297 pIoReq->ReadWrite.cbReq = (size_t)u64;
4298 SSMR3GetU64(pSSM, &u64);
4299 pIoReq->ReadWrite.cbReqLeft = (size_t)u64;
4300
4301 /*
4302 * Try to allocate enough I/O buffer, if this fails for some reason put it onto the
4303 * waiting list instead of the redo list.
4304 */
4305 pIoReq->ReadWrite.cbIoBuf = 0;
4306 rc = IOBUFMgrAllocBuf(pThis->hIoBufMgr, &pIoReq->ReadWrite.IoBuf, pIoReq->ReadWrite.cbReqLeft,
4307 &pIoReq->ReadWrite.cbIoBuf);
4308 if (rc == VERR_NO_MEMORY)
4309 {
4310 pIoReq->enmState = VDIOREQSTATE_ALLOCATED;
4311 ASMAtomicIncU32(&pThis->cIoReqsWaiting);
4312 RTListAppend(&pThis->LstIoReqIoBufWait, &pIoReq->NdLstWait);
4313 fPlaceOnRedoList = false;
4314 rc = VINF_SUCCESS;
4315 }
4316 else
4317 {
4318 pIoReq->ReadWrite.fDirectBuf = false;
4319 pIoReq->ReadWrite.pSgBuf = &pIoReq->ReadWrite.IoBuf.SgBuf;
4320 }
4321 }
4322 else if (pIoReq->enmType == PDMMEDIAEXIOREQTYPE_DISCARD)
4323 {
4324 rc = SSMR3GetU32(pSSM, &pIoReq->Discard.cRanges);
4325 if (RT_SUCCESS(rc))
4326 {
4327 pIoReq->Discard.paRanges = (PRTRANGE)RTMemAllocZ(pIoReq->Discard.cRanges * sizeof(RTRANGE));
4328 if (RT_LIKELY(pIoReq->Discard.paRanges))
4329 {
4330 for (unsigned i = 0; i < pIoReq->Discard.cRanges; i++)
4331 {
4332 SSMR3GetU64(pSSM, &pIoReq->Discard.paRanges[i].offStart);
4333 SSMR3GetU64(pSSM, &u64);
4334 pIoReq->Discard.paRanges[i].cbRange = (size_t)u64;
4335 }
4336 }
4337 else
4338 rc = VERR_NO_MEMORY;
4339 }
4340 }
4341
4342 if (RT_SUCCESS(rc))
4343 rc = SSMR3GetU32(pSSM, &u32); /* sanity/terminator */
4344 if (RT_SUCCESS(rc))
4345 AssertReturn(u32 == UINT32_MAX, VERR_SSM_DATA_UNIT_FORMAT_CHANGED);
4346 if ( RT_SUCCESS(rc)
4347 && fPlaceOnRedoList)
4348 {
4349 /* Mark as suspended */
4350 pIoReq->enmState = VDIOREQSTATE_SUSPENDED;
4351
4352 /* Link into suspended list so it gets kicked off again when we resume. */
4353 RTCritSectEnter(&pThis->CritSectIoReqRedo);
4354 RTListAppend(&pThis->LstIoReqRedo, &pIoReq->NdLstWait);
4355 RTCritSectLeave(&pThis->CritSectIoReqRedo);
4356 }
4357 }
4358
4359 return rc;
4360}
4361
4362/**
4363 * Loads all configured plugins.
4364 *
4365 * @returns VBox status code.
4366 * @param pCfg CFGM node holding plugin list.
4367 */
4368static int drvvdLoadPlugins(PCFGMNODE pCfg)
4369{
4370 PCFGMNODE pCfgPlugins = CFGMR3GetChild(pCfg, "Plugins");
4371
4372 if (pCfgPlugins)
4373 {
4374 PCFGMNODE pPluginCur = CFGMR3GetFirstChild(pCfgPlugins);
4375 while (pPluginCur)
4376 {
4377 int rc = VINF_SUCCESS;
4378 char *pszPluginFilename = NULL;
4379 rc = CFGMR3QueryStringAlloc(pPluginCur, "Path", &pszPluginFilename);
4380 if (RT_SUCCESS(rc))
4381 rc = VDPluginLoadFromFilename(pszPluginFilename);
4382
4383 if (RT_FAILURE(rc))
4384 LogRel(("VD: Failed to load plugin '%s' with %Rrc, continuing\n", pszPluginFilename, rc));
4385
4386 pPluginCur = CFGMR3GetNextChild(pPluginCur);
4387 }
4388 }
4389
4390 return VINF_SUCCESS;
4391}
4392
4393
4394/**
4395 * Sets up the disk filter chain.
4396 *
4397 * @returns VBox status code.
4398 * @param pThis The disk instance.
4399 * @param pCfg CFGM node holding the filter parameters.
4400 */
4401static int drvvdSetupFilters(PVBOXDISK pThis, PCFGMNODE pCfg)
4402{
4403 int rc = VINF_SUCCESS;
4404 PCFGMNODE pCfgFilter = CFGMR3GetChild(pCfg, "Filters");
4405
4406 if (pCfgFilter)
4407 {
4408 PCFGMNODE pCfgFilterConfig = CFGMR3GetChild(pCfgFilter, "VDConfig");
4409 char *pszFilterName = NULL;
4410 VDINTERFACECONFIG VDIfConfig;
4411 PVDINTERFACE pVDIfsFilter = NULL;
4412
4413 rc = CFGMR3QueryStringAlloc(pCfgFilter, "FilterName", &pszFilterName);
4414 if (RT_SUCCESS(rc))
4415 {
4416 VDIfConfig.pfnAreKeysValid = drvvdCfgAreKeysValid;
4417 VDIfConfig.pfnQuerySize = drvvdCfgQuerySize;
4418 VDIfConfig.pfnQuery = drvvdCfgQuery;
4419 VDIfConfig.pfnQueryBytes = drvvdCfgQueryBytes;
4420 rc = VDInterfaceAdd(&VDIfConfig.Core, "DrvVD_Config", VDINTERFACETYPE_CONFIG,
4421 pCfgFilterConfig, sizeof(VDINTERFACECONFIG), &pVDIfsFilter);
4422 AssertRC(rc);
4423
4424 rc = VDFilterAdd(pThis->pDisk, pszFilterName, VD_FILTER_FLAGS_DEFAULT, pVDIfsFilter);
4425
4426 MMR3HeapFree(pszFilterName);
4427 }
4428 }
4429
4430 return rc;
4431}
4432
4433
4434/**
4435 * Translates a PDMMEDIATYPE value into a string.
4436 *
4437 * @returns Read only string.
4438 * @param enmType The type value.
4439 */
4440static const char *drvvdGetTypeName(PDMMEDIATYPE enmType)
4441{
4442 switch (enmType)
4443 {
4444 case PDMMEDIATYPE_ERROR: return "ERROR";
4445 case PDMMEDIATYPE_FLOPPY_360: return "FLOPPY_360";
4446 case PDMMEDIATYPE_FLOPPY_720: return "FLOPPY_720";
4447 case PDMMEDIATYPE_FLOPPY_1_20: return "FLOPPY_1_20";
4448 case PDMMEDIATYPE_FLOPPY_1_44: return "FLOPPY_1_44";
4449 case PDMMEDIATYPE_FLOPPY_2_88: return "FLOPPY_2_88";
4450 case PDMMEDIATYPE_FLOPPY_FAKE_15_6: return "FLOPPY_FAKE_15_6";
4451 case PDMMEDIATYPE_FLOPPY_FAKE_63_5: return "FLOPPY_FAKE_63_5";
4452 case PDMMEDIATYPE_CDROM: return "CDROM";
4453 case PDMMEDIATYPE_DVD: return "DVD";
4454 case PDMMEDIATYPE_HARD_DISK: return "HARD_DISK";
4455 default: return "Unknown";
4456 }
4457}
4458
4459/**
4460 * Returns the appropriate PDMMEDIATYPE for t he given string.
4461 *
4462 * @returns PDMMEDIATYPE
4463 * @param pszType The string representation of the media type.
4464 */
4465static PDMMEDIATYPE drvvdGetMediaTypeFromString(const char *pszType)
4466{
4467 PDMMEDIATYPE enmType = PDMMEDIATYPE_ERROR;
4468
4469 if (!strcmp(pszType, "HardDisk"))
4470 enmType = PDMMEDIATYPE_HARD_DISK;
4471 else if (!strcmp(pszType, "DVD"))
4472 enmType = PDMMEDIATYPE_DVD;
4473 else if (!strcmp(pszType, "CDROM"))
4474 enmType = PDMMEDIATYPE_CDROM;
4475 else if (!strcmp(pszType, "Floppy 2.88"))
4476 enmType = PDMMEDIATYPE_FLOPPY_2_88;
4477 else if (!strcmp(pszType, "Floppy 1.44"))
4478 enmType = PDMMEDIATYPE_FLOPPY_1_44;
4479 else if (!strcmp(pszType, "Floppy 1.20"))
4480 enmType = PDMMEDIATYPE_FLOPPY_1_20;
4481 else if (!strcmp(pszType, "Floppy 720"))
4482 enmType = PDMMEDIATYPE_FLOPPY_720;
4483 else if (!strcmp(pszType, "Floppy 360"))
4484 enmType = PDMMEDIATYPE_FLOPPY_360;
4485 else if (!strcmp(pszType, "Floppy 15.6"))
4486 enmType = PDMMEDIATYPE_FLOPPY_FAKE_15_6;
4487 else if (!strcmp(pszType, "Floppy 63.5"))
4488 enmType = PDMMEDIATYPE_FLOPPY_FAKE_63_5;
4489
4490 return enmType;
4491}
4492
4493/**
4494 * Converts PDMMEDIATYPE to the appropriate VDTYPE.
4495 *
4496 * @returns The VDTYPE.
4497 * @param enmType The PDMMEDIATYPE to convert from.
4498 */
4499static VDTYPE drvvdGetVDFromMediaType(PDMMEDIATYPE enmType)
4500{
4501 if (PDMMEDIATYPE_IS_FLOPPY(enmType))
4502 return VDTYPE_FLOPPY;
4503 else if (enmType == PDMMEDIATYPE_DVD || enmType == PDMMEDIATYPE_CDROM)
4504 return VDTYPE_OPTICAL_DISC;
4505 else if (enmType == PDMMEDIATYPE_HARD_DISK)
4506 return VDTYPE_HDD;
4507
4508 AssertMsgFailed(("Invalid media type %d{%s} given!\n", enmType, drvvdGetTypeName(enmType)));
4509 return VDTYPE_HDD;
4510}
4511
4512/**
4513 * Registers statistics associated with the given media driver.
4514 *
4515 * @returns VBox status code.
4516 * @param pThis The media driver instance.
4517 */
4518static int drvvdStatsRegister(PVBOXDISK pThis)
4519{
4520 PPDMDRVINS pDrvIns = pThis->pDrvIns;
4521 uint32_t iInstance, iLUN;
4522 const char *pcszController;
4523
4524 int rc = pThis->pDrvMediaPort->pfnQueryDeviceLocation(pThis->pDrvMediaPort, &pcszController,
4525 &iInstance, &iLUN);
4526 if (RT_SUCCESS(rc))
4527 {
4528 char *pszCtrlUpper = RTStrDup(pcszController);
4529 if (pszCtrlUpper)
4530 {
4531 RTStrToUpper(pszCtrlUpper);
4532
4533 PDMDrvHlpSTAMRegisterF(pDrvIns, &pThis->StatQueryBufAttempts, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS,
4534 STAMUNIT_COUNT, "Number of attempts to query a direct buffer.",
4535 "/Devices/%s%u/Port%u/QueryBufAttempts", pszCtrlUpper, iInstance, iLUN);
4536 PDMDrvHlpSTAMRegisterF(pDrvIns, &pThis->StatQueryBufSuccess, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS,
4537 STAMUNIT_COUNT, "Number of succeeded attempts to query a direct buffer.",
4538 "/Devices/%s%u/Port%u/QueryBufSuccess", pszCtrlUpper, iInstance, iLUN);
4539
4540 PDMDrvHlpSTAMRegisterF(pDrvIns, &pThis->StatBytesRead, STAMTYPE_COUNTER, STAMVISIBILITY_USED, STAMUNIT_BYTES,
4541 "Amount of data read.", "/Devices/%s%u/Port%u/ReadBytes", pszCtrlUpper, iInstance, iLUN);
4542 PDMDrvHlpSTAMRegisterF(pDrvIns, &pThis->StatBytesWritten, STAMTYPE_COUNTER, STAMVISIBILITY_USED, STAMUNIT_BYTES,
4543 "Amount of data written.", "/Devices/%s%u/Port%u/WrittenBytes", pszCtrlUpper, iInstance, iLUN);
4544
4545 PDMDrvHlpSTAMRegisterF(pDrvIns, &pThis->StatReqsSubmitted, STAMTYPE_COUNTER, STAMVISIBILITY_USED, STAMUNIT_COUNT,
4546 "Number of I/O requests submitted.", "/Devices/%s%u/Port%u/ReqsSubmitted", pszCtrlUpper, iInstance, iLUN);
4547 PDMDrvHlpSTAMRegisterF(pDrvIns, &pThis->StatReqsFailed, STAMTYPE_COUNTER, STAMVISIBILITY_USED, STAMUNIT_COUNT,
4548 "Number of I/O requests failed.", "/Devices/%s%u/Port%u/ReqsFailed", pszCtrlUpper, iInstance, iLUN);
4549 PDMDrvHlpSTAMRegisterF(pDrvIns, &pThis->StatReqsSucceeded, STAMTYPE_COUNTER, STAMVISIBILITY_USED, STAMUNIT_COUNT,
4550 "Number of I/O requests succeeded.", "/Devices/%s%u/Port%u/ReqsSucceeded", pszCtrlUpper, iInstance, iLUN);
4551 PDMDrvHlpSTAMRegisterF(pDrvIns, &pThis->StatReqsFlush, STAMTYPE_COUNTER, STAMVISIBILITY_USED, STAMUNIT_COUNT,
4552 "Number of flush I/O requests submitted.", "/Devices/%s%u/Port%u/ReqsFlush", pszCtrlUpper, iInstance, iLUN);
4553 PDMDrvHlpSTAMRegisterF(pDrvIns, &pThis->StatReqsWrite, STAMTYPE_COUNTER, STAMVISIBILITY_USED, STAMUNIT_COUNT,
4554 "Number of write I/O requests submitted.", "/Devices/%s%u/Port%u/ReqsWrite", pszCtrlUpper, iInstance, iLUN);
4555 PDMDrvHlpSTAMRegisterF(pDrvIns, &pThis->StatReqsRead, STAMTYPE_COUNTER, STAMVISIBILITY_USED, STAMUNIT_COUNT,
4556 "Number of read I/O requests submitted.", "/Devices/%s%u/Port%u/ReqsRead", pszCtrlUpper, iInstance, iLUN);
4557 PDMDrvHlpSTAMRegisterF(pDrvIns, &pThis->StatReqsDiscard, STAMTYPE_COUNTER, STAMVISIBILITY_USED, STAMUNIT_COUNT,
4558 "Number of discard I/O requests submitted.", "/Devices/%s%u/Port%u/ReqsDiscard", pszCtrlUpper, iInstance, iLUN);
4559
4560 PDMDrvHlpSTAMRegisterF(pDrvIns, &pThis->StatReqsPerSec, STAMTYPE_COUNTER, STAMVISIBILITY_USED, STAMUNIT_OCCURENCES,
4561 "Number of processed I/O requests per second.", "/Devices/%s%u/Port%u/ReqsPerSec",
4562 pszCtrlUpper, iInstance, iLUN);
4563
4564 RTStrFree(pszCtrlUpper);
4565 }
4566 else
4567 rc = VERR_NO_STR_MEMORY;
4568 }
4569
4570 return rc;
4571}
4572
4573/**
4574 * Deregisters statistics associated with the given media driver.
4575 *
4576 * @returns nothing.
4577 * @param pThis The media driver instance.
4578 */
4579static void drvvdStatsDeregister(PVBOXDISK pThis)
4580{
4581 PPDMDRVINS pDrvIns = pThis->pDrvIns;
4582
4583 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->StatQueryBufAttempts);
4584 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->StatQueryBufSuccess);
4585
4586 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->StatBytesRead);
4587 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->StatBytesWritten);
4588 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->StatReqsSubmitted);
4589 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->StatReqsFailed);
4590 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->StatReqsSucceeded);
4591 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->StatReqsFlush);
4592 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->StatReqsWrite);
4593 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->StatReqsRead);
4594 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->StatReqsDiscard);
4595 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->StatReqsPerSec);
4596}
4597
4598
4599/*********************************************************************************************************************************
4600* Base interface methods *
4601*********************************************************************************************************************************/
4602
4603/**
4604 * @interface_method_impl{PDMIBASE,pfnQueryInterface}
4605 */
4606static DECLCALLBACK(void *) drvvdQueryInterface(PPDMIBASE pInterface, const char *pszIID)
4607{
4608 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
4609 PVBOXDISK pThis = PDMINS_2_DATA(pDrvIns, PVBOXDISK);
4610
4611 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pDrvIns->IBase);
4612 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIMEDIA, &pThis->IMedia);
4613 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIMOUNT, pThis->fMountable ? &pThis->IMount : NULL);
4614 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIMEDIAEX, pThis->pDrvMediaExPort ? &pThis->IMediaEx : NULL);
4615 return NULL;
4616}
4617
4618
4619/*********************************************************************************************************************************
4620* Saved state notification methods *
4621*********************************************************************************************************************************/
4622
4623/**
4624 * Load done callback for re-opening the image writable during teleportation.
4625 *
4626 * This is called both for successful and failed load runs, we only care about
4627 * successful ones.
4628 *
4629 * @returns VBox status code.
4630 * @param pDrvIns The driver instance.
4631 * @param pSSM The saved state handle.
4632 */
4633static DECLCALLBACK(int) drvvdLoadDone(PPDMDRVINS pDrvIns, PSSMHANDLE pSSM)
4634{
4635 PVBOXDISK pThis = PDMINS_2_DATA(pDrvIns, PVBOXDISK);
4636 Assert(!pThis->fErrorUseRuntime);
4637
4638 /* Drop out if we don't have any work to do or if it's a failed load. */
4639 if ( !pThis->fTempReadOnly
4640 || RT_FAILURE(SSMR3HandleGetStatus(pSSM)))
4641 return VINF_SUCCESS;
4642
4643 int rc = drvvdSetWritable(pThis);
4644 if (RT_FAILURE(rc)) /** @todo does the bugger set any errors? */
4645 return SSMR3SetLoadError(pSSM, rc, RT_SRC_POS,
4646 N_("Failed to write lock the images"));
4647 return VINF_SUCCESS;
4648}
4649
4650
4651/*********************************************************************************************************************************
4652* Driver methods *
4653*********************************************************************************************************************************/
4654
4655/**
4656 * Worker for the power off or destruct callback.
4657 *
4658 * @returns nothing.
4659 * @param pDrvIns The driver instance.
4660 */
4661static void drvvdPowerOffOrDestructOrUnmount(PPDMDRVINS pDrvIns)
4662{
4663 PVBOXDISK pThis = PDMINS_2_DATA(pDrvIns, PVBOXDISK);
4664 LogFlowFunc(("\n"));
4665
4666 RTSEMFASTMUTEX mutex;
4667 ASMAtomicXchgHandle(&pThis->MergeCompleteMutex, NIL_RTSEMFASTMUTEX, &mutex);
4668 if (mutex != NIL_RTSEMFASTMUTEX)
4669 {
4670 /* Request the semaphore to wait until a potentially running merge
4671 * operation has been finished. */
4672 int rc = RTSemFastMutexRequest(mutex);
4673 AssertRC(rc);
4674 pThis->fMergePending = false;
4675 rc = RTSemFastMutexRelease(mutex);
4676 AssertRC(rc);
4677 rc = RTSemFastMutexDestroy(mutex);
4678 AssertRC(rc);
4679 }
4680
4681 if (RT_VALID_PTR(pThis->pBlkCache))
4682 {
4683 PDMR3BlkCacheRelease(pThis->pBlkCache);
4684 pThis->pBlkCache = NULL;
4685 }
4686
4687 if (RT_VALID_PTR(pThis->pRegionList))
4688 {
4689 VDRegionListFree(pThis->pRegionList);
4690 pThis->pRegionList = NULL;
4691 }
4692
4693 if (RT_VALID_PTR(pThis->pDisk))
4694 {
4695 VDDestroy(pThis->pDisk);
4696 pThis->pDisk = NULL;
4697 }
4698 drvvdFreeImages(pThis);
4699}
4700
4701/**
4702 * @copydoc FNPDMDRVPOWEROFF
4703 */
4704static DECLCALLBACK(void) drvvdPowerOff(PPDMDRVINS pDrvIns)
4705{
4706 PDMDRV_CHECK_VERSIONS_RETURN_VOID(pDrvIns);
4707 drvvdPowerOffOrDestructOrUnmount(pDrvIns);
4708}
4709
4710/**
4711 * @callback_method_impl{FNPDMDRVRESUME}
4712 *
4713 * VM resume notification that we use to undo what the temporary read-only image
4714 * mode set by drvvdSuspend.
4715 *
4716 * Also switch to runtime error mode if we're resuming after a state load
4717 * without having been powered on first.
4718 *
4719 * @todo The VMSetError vs VMSetRuntimeError mess must be fixed elsewhere,
4720 * we're making assumptions about Main behavior here!
4721 */
4722static DECLCALLBACK(void) drvvdResume(PPDMDRVINS pDrvIns)
4723{
4724 LogFlowFunc(("\n"));
4725 PVBOXDISK pThis = PDMINS_2_DATA(pDrvIns, PVBOXDISK);
4726
4727 drvvdSetWritable(pThis);
4728 pThis->fSuspending = false;
4729
4730 if (pThis->pBlkCache)
4731 {
4732 int rc = PDMR3BlkCacheResume(pThis->pBlkCache);
4733 AssertRC(rc);
4734 }
4735
4736 if (pThis->pDrvMediaExPort)
4737 {
4738 /* Mark all requests waiting for I/O memory as active again so they get accounted for. */
4739 RTCritSectEnter(&pThis->CritSectIoReqsIoBufWait);
4740 PPDMMEDIAEXIOREQINT pIoReq, pIoReqNext;
4741 RTListForEachSafe(&pThis->LstIoReqIoBufWait, pIoReq, pIoReqNext, PDMMEDIAEXIOREQINT, NdLstWait)
4742 {
4743 pThis->pDrvMediaExPort->pfnIoReqStateChanged(pThis->pDrvMediaExPort, pIoReq, &pIoReq->abAlloc[0],
4744 PDMMEDIAEXIOREQSTATE_ACTIVE);
4745 ASMAtomicIncU32(&pThis->cIoReqsActive);
4746 }
4747 RTCritSectLeave(&pThis->CritSectIoReqsIoBufWait);
4748
4749 /* Kick of any request we have to redo. */
4750 RTCritSectEnter(&pThis->CritSectIoReqRedo);
4751 RTListForEachSafe(&pThis->LstIoReqRedo, pIoReq, pIoReqNext, PDMMEDIAEXIOREQINT, NdLstWait)
4752 {
4753 int rc = VINF_SUCCESS;
4754 bool fXchg = ASMAtomicCmpXchgU32((volatile uint32_t *)&pIoReq->enmState, VDIOREQSTATE_ACTIVE, VDIOREQSTATE_SUSPENDED);
4755
4756 RTListNodeRemove(&pIoReq->NdLstWait);
4757 ASMAtomicIncU32(&pThis->cIoReqsActive);
4758
4759 if (fXchg)
4760 {
4761 pThis->pDrvMediaExPort->pfnIoReqStateChanged(pThis->pDrvMediaExPort, pIoReq, &pIoReq->abAlloc[0],
4762 PDMMEDIAEXIOREQSTATE_ACTIVE);
4763 if ( pIoReq->enmType == PDMMEDIAEXIOREQTYPE_READ
4764 || pIoReq->enmType == PDMMEDIAEXIOREQTYPE_WRITE)
4765 rc = drvvdMediaExIoReqReadWriteProcess(pThis, pIoReq, true /* fUpNotify */);
4766 else if (pIoReq->enmType == PDMMEDIAEXIOREQTYPE_FLUSH)
4767 {
4768 rc = drvvdMediaExIoReqFlushWrapper(pThis, pIoReq);
4769 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
4770 rc = VINF_PDM_MEDIAEX_IOREQ_IN_PROGRESS;
4771 else if (rc == VINF_VD_ASYNC_IO_FINISHED)
4772 rc = VINF_SUCCESS;
4773 }
4774 else if (pIoReq->enmType == PDMMEDIAEXIOREQTYPE_DISCARD)
4775 {
4776 rc = drvvdMediaExIoReqDiscardWrapper(pThis, pIoReq);
4777 if (rc == VERR_VD_ASYNC_IO_IN_PROGRESS)
4778 rc = VINF_PDM_MEDIAEX_IOREQ_IN_PROGRESS;
4779 else if (rc == VINF_VD_ASYNC_IO_FINISHED)
4780 rc = VINF_SUCCESS;
4781 }
4782 else
4783 AssertMsgFailed(("Invalid request type %u\n", pIoReq->enmType));
4784
4785 /* The read write process will call the completion callback on its own. */
4786 if ( rc != VINF_PDM_MEDIAEX_IOREQ_IN_PROGRESS
4787 && ( pIoReq->enmType == PDMMEDIAEXIOREQTYPE_DISCARD
4788 || pIoReq->enmType == PDMMEDIAEXIOREQTYPE_FLUSH))
4789 {
4790 Assert( ( pIoReq->enmType != PDMMEDIAEXIOREQTYPE_WRITE
4791 && pIoReq->enmType != PDMMEDIAEXIOREQTYPE_READ)
4792 || !pIoReq->ReadWrite.cbReqLeft
4793 || RT_FAILURE(rc));
4794 drvvdMediaExIoReqCompleteWorker(pThis, pIoReq, rc, true /* fUpNotify */);
4795 }
4796
4797 }
4798 else
4799 {
4800 /* Request was canceled inbetween, so don't care and notify the owner about the completed request. */
4801 Assert(pIoReq->enmState == VDIOREQSTATE_CANCELED);
4802 drvvdMediaExIoReqCompleteWorker(pThis, pIoReq, VERR_PDM_MEDIAEX_IOREQ_CANCELED, true /* fUpNotify */);
4803 }
4804 }
4805 Assert(RTListIsEmpty(&pThis->LstIoReqRedo));
4806 RTCritSectLeave(&pThis->CritSectIoReqRedo);
4807 }
4808
4809 /* Try to process any requests waiting for I/O memory now. */
4810 drvvdMediaExIoReqProcessWaiting(pThis);
4811 pThis->fErrorUseRuntime = true;
4812}
4813
4814/**
4815 * @callback_method_impl{FNPDMDRVSUSPEND}
4816 *
4817 * When the VM is being suspended, temporarily change to read-only image mode.
4818 *
4819 * This is important for several reasons:
4820 * -# It makes sure that there are no pending writes to the image. Most
4821 * backends implements this by closing and reopening the image in read-only
4822 * mode.
4823 * -# It allows Main to read the images during snapshotting without having
4824 * to account for concurrent writes.
4825 * -# This is essential for making teleportation targets sharing images work
4826 * right. Both with regards to caching and with regards to file sharing
4827 * locks (RTFILE_O_DENY_*). (See also drvvdLoadDone.)
4828 */
4829static DECLCALLBACK(void) drvvdSuspend(PPDMDRVINS pDrvIns)
4830{
4831 LogFlowFunc(("\n"));
4832 PVBOXDISK pThis = PDMINS_2_DATA(pDrvIns, PVBOXDISK);
4833
4834 if (pThis->pBlkCache)
4835 {
4836 int rc = PDMR3BlkCacheSuspend(pThis->pBlkCache);
4837 AssertRC(rc);
4838 }
4839
4840 drvvdSetReadonly(pThis);
4841}
4842
4843/**
4844 * @callback_method_impl{FNPDMDRVPOWERON}
4845 */
4846static DECLCALLBACK(void) drvvdPowerOn(PPDMDRVINS pDrvIns)
4847{
4848 LogFlowFunc(("\n"));
4849 PVBOXDISK pThis = PDMINS_2_DATA(pDrvIns, PVBOXDISK);
4850 drvvdSetWritable(pThis);
4851 pThis->fErrorUseRuntime = true;
4852}
4853
4854/**
4855 * @callback_method_impl{FNPDMDRVRESET}
4856 */
4857static DECLCALLBACK(void) drvvdReset(PPDMDRVINS pDrvIns)
4858{
4859 LogFlowFunc(("\n"));
4860 PVBOXDISK pThis = PDMINS_2_DATA(pDrvIns, PVBOXDISK);
4861
4862 if (pThis->pBlkCache)
4863 {
4864 int rc = PDMR3BlkCacheClear(pThis->pBlkCache);
4865 AssertRC(rc);
4866 }
4867
4868 if (pThis->fBootAccelEnabled)
4869 {
4870 pThis->fBootAccelActive = true;
4871 pThis->cbDataValid = 0;
4872 pThis->offDisk = 0;
4873 }
4874}
4875
4876/**
4877 * @callback_method_impl{FNPDMDRVDESTRUCT}
4878 */
4879static DECLCALLBACK(void) drvvdDestruct(PPDMDRVINS pDrvIns)
4880{
4881 PDMDRV_CHECK_VERSIONS_RETURN_VOID(pDrvIns);
4882 PVBOXDISK pThis = PDMINS_2_DATA(pDrvIns, PVBOXDISK);
4883 LogFlowFunc(("\n"));
4884
4885 /*
4886 * Make sure the block cache and disks are closed when this driver is
4887 * destroyed. This method will get called without calling the power off
4888 * callback first when we reconfigure the driver chain after a snapshot.
4889 */
4890 drvvdPowerOffOrDestructOrUnmount(pDrvIns);
4891 if (pThis->MergeLock != NIL_RTSEMRW)
4892 {
4893 int rc = RTSemRWDestroy(pThis->MergeLock);
4894 AssertRC(rc);
4895 pThis->MergeLock = NIL_RTSEMRW;
4896 }
4897 if (pThis->pbData)
4898 {
4899 RTMemFree(pThis->pbData);
4900 pThis->pbData = NULL;
4901 }
4902 if (pThis->pszBwGroup)
4903 {
4904 MMR3HeapFree(pThis->pszBwGroup);
4905 pThis->pszBwGroup = NULL;
4906 }
4907 if (pThis->hHbdMgr != NIL_HBDMGR)
4908 HBDMgrDestroy(pThis->hHbdMgr);
4909 if (pThis->hIoReqCache != NIL_RTMEMCACHE)
4910 RTMemCacheDestroy(pThis->hIoReqCache);
4911 if (pThis->hIoBufMgr != NIL_IOBUFMGR)
4912 IOBUFMgrDestroy(pThis->hIoBufMgr);
4913 if (RTCritSectIsInitialized(&pThis->CritSectIoReqsIoBufWait))
4914 RTCritSectDelete(&pThis->CritSectIoReqsIoBufWait);
4915 if (RTCritSectIsInitialized(&pThis->CritSectIoReqRedo))
4916 RTCritSectDelete(&pThis->CritSectIoReqRedo);
4917 for (unsigned i = 0; i < RT_ELEMENTS(pThis->aIoReqAllocBins); i++)
4918 if (pThis->aIoReqAllocBins[i].hMtxLstIoReqAlloc != NIL_RTSEMFASTMUTEX)
4919 RTSemFastMutexDestroy(pThis->aIoReqAllocBins[i].hMtxLstIoReqAlloc);
4920
4921 drvvdStatsDeregister(pThis);
4922}
4923
4924/**
4925 * @callback_method_impl{FNPDMDRVCONSTRUCT,
4926 * Construct a VBox disk media driver instance.}
4927 */
4928static DECLCALLBACK(int) drvvdConstruct(PPDMDRVINS pDrvIns, PCFGMNODE pCfg, uint32_t fFlags)
4929{
4930 RT_NOREF(fFlags);
4931 LogFlowFunc(("\n"));
4932 PDMDRV_CHECK_VERSIONS_RETURN(pDrvIns);
4933 PVBOXDISK pThis = PDMINS_2_DATA(pDrvIns, PVBOXDISK);
4934 int rc = VINF_SUCCESS;
4935 char *pszName = NULL; /* The path of the disk image file. */
4936 char *pszFormat = NULL; /* The format backed to use for this image. */
4937 char *pszCachePath = NULL; /* The path to the cache image. */
4938 char *pszCacheFormat = NULL; /* The format backend to use for the cache image. */
4939 bool fReadOnly = false; /* True if the media is read-only. */
4940 bool fMaybeReadOnly = false; /* True if the media may or may not be read-only. */
4941 bool fHonorZeroWrites = false; /* True if zero blocks should be written. */
4942
4943 /*
4944 * Init the static parts.
4945 */
4946 pDrvIns->IBase.pfnQueryInterface = drvvdQueryInterface;
4947 pThis->pDrvIns = pDrvIns;
4948 pThis->fTempReadOnly = false;
4949 pThis->pDisk = NULL;
4950 pThis->fAsyncIOSupported = false;
4951 pThis->fShareable = false;
4952 pThis->fMergePending = false;
4953 pThis->MergeCompleteMutex = NIL_RTSEMFASTMUTEX;
4954 pThis->MergeLock = NIL_RTSEMRW;
4955 pThis->uMergeSource = VD_LAST_IMAGE;
4956 pThis->uMergeTarget = VD_LAST_IMAGE;
4957 pThis->pCfgCrypto = NULL;
4958 pThis->pIfSecKey = NULL;
4959 pThis->hIoReqCache = NIL_RTMEMCACHE;
4960 pThis->hIoBufMgr = NIL_IOBUFMGR;
4961 pThis->pRegionList = NULL;
4962 pThis->fSuspending = false;
4963
4964 for (unsigned i = 0; i < RT_ELEMENTS(pThis->aIoReqAllocBins); i++)
4965 pThis->aIoReqAllocBins[i].hMtxLstIoReqAlloc = NIL_RTSEMFASTMUTEX;
4966
4967 /* IMedia */
4968 pThis->IMedia.pfnRead = drvvdRead;
4969 pThis->IMedia.pfnReadPcBios = drvvdReadPcBios;
4970 pThis->IMedia.pfnWrite = drvvdWrite;
4971 pThis->IMedia.pfnFlush = drvvdFlush;
4972 pThis->IMedia.pfnMerge = drvvdMerge;
4973 pThis->IMedia.pfnSetSecKeyIf = drvvdSetSecKeyIf;
4974 pThis->IMedia.pfnGetSize = drvvdGetSize;
4975 pThis->IMedia.pfnGetSectorSize = drvvdGetSectorSize;
4976 pThis->IMedia.pfnIsReadOnly = drvvdIsReadOnly;
4977 pThis->IMedia.pfnIsNonRotational = drvvdIsNonRotational;
4978 pThis->IMedia.pfnBiosGetPCHSGeometry = drvvdBiosGetPCHSGeometry;
4979 pThis->IMedia.pfnBiosSetPCHSGeometry = drvvdBiosSetPCHSGeometry;
4980 pThis->IMedia.pfnBiosGetLCHSGeometry = drvvdBiosGetLCHSGeometry;
4981 pThis->IMedia.pfnBiosSetLCHSGeometry = drvvdBiosSetLCHSGeometry;
4982 pThis->IMedia.pfnBiosIsVisible = drvvdBiosIsVisible;
4983 pThis->IMedia.pfnGetType = drvvdGetType;
4984 pThis->IMedia.pfnGetUuid = drvvdGetUuid;
4985 pThis->IMedia.pfnDiscard = drvvdDiscard;
4986 pThis->IMedia.pfnSendCmd = NULL;
4987 pThis->IMedia.pfnGetRegionCount = drvvdGetRegionCount;
4988 pThis->IMedia.pfnQueryRegionProperties = drvvdQueryRegionProperties;
4989 pThis->IMedia.pfnQueryRegionPropertiesForLba = drvvdQueryRegionPropertiesForLba;
4990
4991 /* IMount */
4992 pThis->IMount.pfnUnmount = drvvdUnmount;
4993 pThis->IMount.pfnIsMounted = drvvdIsMounted;
4994 pThis->IMount.pfnLock = drvvdLock;
4995 pThis->IMount.pfnUnlock = drvvdUnlock;
4996 pThis->IMount.pfnIsLocked = drvvdIsLocked;
4997
4998 /* IMediaEx */
4999 pThis->IMediaEx.pfnQueryFeatures = drvvdQueryFeatures;
5000 pThis->IMediaEx.pfnNotifySuspend = drvvdNotifySuspend;
5001 pThis->IMediaEx.pfnIoReqAllocSizeSet = drvvdIoReqAllocSizeSet;
5002 pThis->IMediaEx.pfnIoReqAlloc = drvvdIoReqAlloc;
5003 pThis->IMediaEx.pfnIoReqFree = drvvdIoReqFree;
5004 pThis->IMediaEx.pfnIoReqQueryResidual = drvvdIoReqQueryResidual;
5005 pThis->IMediaEx.pfnIoReqQueryXferSize = drvvdIoReqQueryXferSize;
5006 pThis->IMediaEx.pfnIoReqCancelAll = drvvdIoReqCancelAll;
5007 pThis->IMediaEx.pfnIoReqCancel = drvvdIoReqCancel;
5008 pThis->IMediaEx.pfnIoReqRead = drvvdIoReqRead;
5009 pThis->IMediaEx.pfnIoReqWrite = drvvdIoReqWrite;
5010 pThis->IMediaEx.pfnIoReqFlush = drvvdIoReqFlush;
5011 pThis->IMediaEx.pfnIoReqDiscard = drvvdIoReqDiscard;
5012 pThis->IMediaEx.pfnIoReqSendScsiCmd = drvvdIoReqSendScsiCmd;
5013 pThis->IMediaEx.pfnIoReqGetActiveCount = drvvdIoReqGetActiveCount;
5014 pThis->IMediaEx.pfnIoReqGetSuspendedCount = drvvdIoReqGetSuspendedCount;
5015 pThis->IMediaEx.pfnIoReqQuerySuspendedStart = drvvdIoReqQuerySuspendedStart;
5016 pThis->IMediaEx.pfnIoReqQuerySuspendedNext = drvvdIoReqQuerySuspendedNext;
5017 pThis->IMediaEx.pfnIoReqSuspendedSave = drvvdIoReqSuspendedSave;
5018 pThis->IMediaEx.pfnIoReqSuspendedLoad = drvvdIoReqSuspendedLoad;
5019
5020 /* Initialize supported VD interfaces. */
5021 pThis->pVDIfsDisk = NULL;
5022
5023 pThis->VDIfError.pfnError = drvvdErrorCallback;
5024 pThis->VDIfError.pfnMessage = NULL;
5025 rc = VDInterfaceAdd(&pThis->VDIfError.Core, "DrvVD_VDIError", VDINTERFACETYPE_ERROR,
5026 pDrvIns, sizeof(VDINTERFACEERROR), &pThis->pVDIfsDisk);
5027 AssertRC(rc);
5028
5029 /* List of images is empty now. */
5030 pThis->pImages = NULL;
5031
5032 pThis->pDrvMediaPort = PDMIBASE_QUERY_INTERFACE(pDrvIns->pUpBase, PDMIMEDIAPORT);
5033 if (!pThis->pDrvMediaPort)
5034 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_MISSING_INTERFACE_ABOVE,
5035 N_("No media port interface above"));
5036
5037 pThis->pDrvMountNotify = PDMIBASE_QUERY_INTERFACE(pDrvIns->pUpBase, PDMIMOUNTNOTIFY);
5038
5039 /*
5040 * Try to attach the optional extended media interface port above and initialize associated
5041 * structures if available.
5042 */
5043 pThis->pDrvMediaExPort = PDMIBASE_QUERY_INTERFACE(pDrvIns->pUpBase, PDMIMEDIAEXPORT);
5044 if (pThis->pDrvMediaExPort)
5045 {
5046 for (unsigned i = 0; i < RT_ELEMENTS(pThis->aIoReqAllocBins); i++)
5047 {
5048 rc = RTSemFastMutexCreate(&pThis->aIoReqAllocBins[i].hMtxLstIoReqAlloc);
5049 if (RT_FAILURE(rc))
5050 break;
5051 RTListInit(&pThis->aIoReqAllocBins[i].LstIoReqAlloc);
5052 }
5053
5054 if (RT_SUCCESS(rc))
5055 rc = RTCritSectInit(&pThis->CritSectIoReqsIoBufWait);
5056
5057 if (RT_SUCCESS(rc))
5058 rc = RTCritSectInit(&pThis->CritSectIoReqRedo);
5059
5060 if (RT_FAILURE(rc))
5061 return PDMDRV_SET_ERROR(pDrvIns, rc, N_("Creating Mutex failed"));
5062
5063 RTListInit(&pThis->LstIoReqIoBufWait);
5064 RTListInit(&pThis->LstIoReqRedo);
5065 }
5066
5067 /* Before we access any VD API load all given plugins. */
5068 rc = drvvdLoadPlugins(pCfg);
5069 if (RT_FAILURE(rc))
5070 return PDMDRV_SET_ERROR(pDrvIns, rc, N_("Loading VD plugins failed"));
5071
5072 /*
5073 * Validate configuration and find all parent images.
5074 * It's sort of up side down from the image dependency tree.
5075 */
5076 bool fHostIP = false;
5077 bool fUseNewIo = false;
5078 bool fUseBlockCache = false;
5079 bool fDiscard = false;
5080 bool fInformAboutZeroBlocks = false;
5081 bool fSkipConsistencyChecks = false;
5082 bool fEmptyDrive = false;
5083 unsigned iLevel = 0;
5084 PCFGMNODE pCurNode = pCfg;
5085 uint32_t cbIoBufMax = 0;
5086
5087 for (;;)
5088 {
5089 bool fValid;
5090
5091 if (pCurNode == pCfg)
5092 {
5093 /* Toplevel configuration additionally contains the global image
5094 * open flags. Some might be converted to per-image flags later. */
5095 fValid = CFGMR3AreValuesValid(pCurNode,
5096 "Format\0Path\0"
5097 "ReadOnly\0MaybeReadOnly\0TempReadOnly\0Shareable\0HonorZeroWrites\0"
5098 "HostIPStack\0UseNewIo\0BootAcceleration\0BootAccelerationBuffer\0"
5099 "SetupMerge\0MergeSource\0MergeTarget\0BwGroup\0Type\0BlockCache\0"
5100 "CachePath\0CacheFormat\0Discard\0InformAboutZeroBlocks\0"
5101 "SkipConsistencyChecks\0"
5102 "Locked\0BIOSVisible\0Cylinders\0Heads\0Sectors\0Mountable\0"
5103 "EmptyDrive\0IoBufMax\0NonRotationalMedium\0"
5104#if defined(VBOX_PERIODIC_FLUSH) || defined(VBOX_IGNORE_FLUSH)
5105 "FlushInterval\0IgnoreFlush\0IgnoreFlushAsync\0"
5106#endif /* !(VBOX_PERIODIC_FLUSH || VBOX_IGNORE_FLUSH) */
5107 );
5108 }
5109 else
5110 {
5111 /* All other image configurations only contain image name and
5112 * the format information. */
5113 fValid = CFGMR3AreValuesValid(pCurNode, "Format\0Path\0"
5114 "MergeSource\0MergeTarget\0");
5115 }
5116 if (!fValid)
5117 {
5118 rc = PDMDrvHlpVMSetError(pDrvIns, VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES,
5119 RT_SRC_POS, N_("DrvVD: Configuration error: keys incorrect at level %d"), iLevel);
5120 break;
5121 }
5122
5123 if (pCurNode == pCfg)
5124 {
5125 rc = CFGMR3QueryBoolDef(pCurNode, "HostIPStack", &fHostIP, true);
5126 if (RT_FAILURE(rc))
5127 {
5128 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
5129 N_("DrvVD: Configuration error: Querying \"HostIPStack\" as boolean failed"));
5130 break;
5131 }
5132
5133 rc = CFGMR3QueryBoolDef(pCurNode, "HonorZeroWrites", &fHonorZeroWrites, false);
5134 if (RT_FAILURE(rc))
5135 {
5136 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
5137 N_("DrvVD: Configuration error: Querying \"HonorZeroWrites\" as boolean failed"));
5138 break;
5139 }
5140
5141 rc = CFGMR3QueryBoolDef(pCurNode, "ReadOnly", &fReadOnly, false);
5142 if (RT_FAILURE(rc))
5143 {
5144 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
5145 N_("DrvVD: Configuration error: Querying \"ReadOnly\" as boolean failed"));
5146 break;
5147 }
5148
5149 rc = CFGMR3QueryBoolDef(pCurNode, "MaybeReadOnly", &fMaybeReadOnly, false);
5150 if (RT_FAILURE(rc))
5151 {
5152 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
5153 N_("DrvVD: Configuration error: Querying \"MaybeReadOnly\" as boolean failed"));
5154 break;
5155 }
5156
5157 rc = CFGMR3QueryBoolDef(pCurNode, "TempReadOnly", &pThis->fTempReadOnly, false);
5158 if (RT_FAILURE(rc))
5159 {
5160 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
5161 N_("DrvVD: Configuration error: Querying \"TempReadOnly\" as boolean failed"));
5162 break;
5163 }
5164 if (fReadOnly && pThis->fTempReadOnly)
5165 {
5166 rc = PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_DRIVER_INVALID_PROPERTIES,
5167 N_("DrvVD: Configuration error: Both \"ReadOnly\" and \"TempReadOnly\" are set"));
5168 break;
5169 }
5170
5171 rc = CFGMR3QueryBoolDef(pCurNode, "Shareable", &pThis->fShareable, false);
5172 if (RT_FAILURE(rc))
5173 {
5174 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
5175 N_("DrvVD: Configuration error: Querying \"Shareable\" as boolean failed"));
5176 break;
5177 }
5178
5179 rc = CFGMR3QueryBoolDef(pCurNode, "UseNewIo", &fUseNewIo, false);
5180 if (RT_FAILURE(rc))
5181 {
5182 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
5183 N_("DrvVD: Configuration error: Querying \"UseNewIo\" as boolean failed"));
5184 break;
5185 }
5186 rc = CFGMR3QueryBoolDef(pCurNode, "SetupMerge", &pThis->fMergePending, false);
5187 if (RT_FAILURE(rc))
5188 {
5189 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
5190 N_("DrvVD: Configuration error: Querying \"SetupMerge\" as boolean failed"));
5191 break;
5192 }
5193 if (fReadOnly && pThis->fMergePending)
5194 {
5195 rc = PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_DRIVER_INVALID_PROPERTIES,
5196 N_("DrvVD: Configuration error: Both \"ReadOnly\" and \"MergePending\" are set"));
5197 break;
5198 }
5199 rc = CFGMR3QueryBoolDef(pCurNode, "BootAcceleration", &pThis->fBootAccelEnabled, false);
5200 if (RT_FAILURE(rc))
5201 {
5202 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
5203 N_("DrvVD: Configuration error: Querying \"BootAcceleration\" as boolean failed"));
5204 break;
5205 }
5206 rc = CFGMR3QueryU32Def(pCurNode, "BootAccelerationBuffer", (uint32_t *)&pThis->cbBootAccelBuffer, 16 * _1K);
5207 if (RT_FAILURE(rc))
5208 {
5209 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
5210 N_("DrvVD: Configuration error: Querying \"BootAccelerationBuffer\" as integer failed"));
5211 break;
5212 }
5213 rc = CFGMR3QueryBoolDef(pCurNode, "BlockCache", &fUseBlockCache, false);
5214 if (RT_FAILURE(rc))
5215 {
5216 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
5217 N_("DrvVD: Configuration error: Querying \"BlockCache\" as boolean failed"));
5218 break;
5219 }
5220 rc = CFGMR3QueryStringAlloc(pCurNode, "BwGroup", &pThis->pszBwGroup);
5221 if (RT_FAILURE(rc) && rc != VERR_CFGM_VALUE_NOT_FOUND)
5222 {
5223 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
5224 N_("DrvVD: Configuration error: Querying \"BwGroup\" as string failed"));
5225 break;
5226 }
5227 else
5228 rc = VINF_SUCCESS;
5229 rc = CFGMR3QueryBoolDef(pCurNode, "Discard", &fDiscard, false);
5230 if (RT_FAILURE(rc))
5231 {
5232 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
5233 N_("DrvVD: Configuration error: Querying \"Discard\" as boolean failed"));
5234 break;
5235 }
5236 if (fReadOnly && fDiscard)
5237 {
5238 rc = PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_DRIVER_INVALID_PROPERTIES,
5239 N_("DrvVD: Configuration error: Both \"ReadOnly\" and \"Discard\" are set"));
5240 break;
5241 }
5242 rc = CFGMR3QueryBoolDef(pCurNode, "InformAboutZeroBlocks", &fInformAboutZeroBlocks, false);
5243 if (RT_FAILURE(rc))
5244 {
5245 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
5246 N_("DrvVD: Configuration error: Querying \"InformAboutZeroBlocks\" as boolean failed"));
5247 break;
5248 }
5249 rc = CFGMR3QueryBoolDef(pCurNode, "SkipConsistencyChecks", &fSkipConsistencyChecks, true);
5250 if (RT_FAILURE(rc))
5251 {
5252 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
5253 N_("DrvVD: Configuration error: Querying \"SKipConsistencyChecks\" as boolean failed"));
5254 break;
5255 }
5256
5257 char *psz = NULL;
5258 rc = CFGMR3QueryStringAlloc(pCfg, "Type", &psz);
5259 if (RT_FAILURE(rc))
5260 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_BLOCK_NO_TYPE, N_("Failed to obtain the sub type"));
5261 pThis->enmType = drvvdGetMediaTypeFromString(psz);
5262 if (pThis->enmType == PDMMEDIATYPE_ERROR)
5263 {
5264 PDMDrvHlpVMSetError(pDrvIns, VERR_PDM_BLOCK_UNKNOWN_TYPE, RT_SRC_POS,
5265 N_("Unknown type \"%s\""), psz);
5266 MMR3HeapFree(psz);
5267 return VERR_PDM_BLOCK_UNKNOWN_TYPE;
5268 }
5269 MMR3HeapFree(psz); psz = NULL;
5270
5271 rc = CFGMR3QueryStringAlloc(pCurNode, "CachePath", &pszCachePath);
5272 if (RT_FAILURE(rc) && rc != VERR_CFGM_VALUE_NOT_FOUND)
5273 {
5274 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
5275 N_("DrvVD: Configuration error: Querying \"CachePath\" as string failed"));
5276 break;
5277 }
5278 else
5279 rc = VINF_SUCCESS;
5280
5281 if (pszCachePath)
5282 {
5283 rc = CFGMR3QueryStringAlloc(pCurNode, "CacheFormat", &pszCacheFormat);
5284 if (RT_FAILURE(rc))
5285 {
5286 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
5287 N_("DrvVD: Configuration error: Querying \"CacheFormat\" as string failed"));
5288 break;
5289 }
5290 }
5291
5292 /* Mountable */
5293 rc = CFGMR3QueryBoolDef(pCfg, "Mountable", &pThis->fMountable, false);
5294 if (RT_FAILURE(rc))
5295 return PDMDRV_SET_ERROR(pDrvIns, rc, N_("Failed to query \"Mountable\" from the config"));
5296
5297 /* Locked */
5298 rc = CFGMR3QueryBoolDef(pCfg, "Locked", &pThis->fLocked, false);
5299 if (RT_FAILURE(rc))
5300 return PDMDRV_SET_ERROR(pDrvIns, rc, N_("Failed to query \"Locked\" from the config"));
5301
5302 /* BIOS visible */
5303 rc = CFGMR3QueryBoolDef(pCfg, "BIOSVisible", &pThis->fBiosVisible, true);
5304 if (RT_FAILURE(rc))
5305 return PDMDRV_SET_ERROR(pDrvIns, rc, N_("Failed to query \"BIOSVisible\" from the config"));
5306
5307 /* Cylinders */
5308 rc = CFGMR3QueryU32Def(pCfg, "Cylinders", &pThis->LCHSGeometry.cCylinders, 0);
5309 if (RT_FAILURE(rc))
5310 return PDMDRV_SET_ERROR(pDrvIns, rc, N_("Failed to query \"Cylinders\" from the config"));
5311
5312 /* Heads */
5313 rc = CFGMR3QueryU32Def(pCfg, "Heads", &pThis->LCHSGeometry.cHeads, 0);
5314 if (RT_FAILURE(rc))
5315 return PDMDRV_SET_ERROR(pDrvIns, rc, N_("Failed to query \"Heads\" from the config"));
5316
5317 /* Sectors */
5318 rc = CFGMR3QueryU32Def(pCfg, "Sectors", &pThis->LCHSGeometry.cSectors, 0);
5319 if (RT_FAILURE(rc))
5320 return PDMDRV_SET_ERROR(pDrvIns, rc, N_("Failed to query \"Sectors\" from the config"));
5321
5322 /* Uuid */
5323 rc = CFGMR3QueryStringAlloc(pCfg, "Uuid", &psz);
5324 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
5325 RTUuidClear(&pThis->Uuid);
5326 else if (RT_SUCCESS(rc))
5327 {
5328 rc = RTUuidFromStr(&pThis->Uuid, psz);
5329 if (RT_FAILURE(rc))
5330 {
5331 PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("Uuid from string failed on \"%s\""), psz);
5332 MMR3HeapFree(psz);
5333 return rc;
5334 }
5335 MMR3HeapFree(psz); psz = NULL;
5336 }
5337 else
5338 return PDMDRV_SET_ERROR(pDrvIns, rc, N_("Failed to query \"Uuid\" from the config"));
5339
5340#ifdef VBOX_PERIODIC_FLUSH
5341 rc = CFGMR3QueryU32Def(pCfg, "FlushInterval", &pThis->cbFlushInterval, 0);
5342 if (RT_FAILURE(rc))
5343 return PDMDRV_SET_ERROR(pDrvIns, rc, N_("Failed to query \"FlushInterval\" from the config"));
5344#endif /* VBOX_PERIODIC_FLUSH */
5345
5346#ifdef VBOX_IGNORE_FLUSH
5347 rc = CFGMR3QueryBoolDef(pCfg, "IgnoreFlush", &pThis->fIgnoreFlush, true);
5348 if (RT_FAILURE(rc))
5349 return PDMDRV_SET_ERROR(pDrvIns, rc, N_("Failed to query \"IgnoreFlush\" from the config"));
5350
5351 if (pThis->fIgnoreFlush)
5352 LogRel(("DrvVD: Flushes will be ignored\n"));
5353 else
5354 LogRel(("DrvVD: Flushes will be passed to the disk\n"));
5355
5356 rc = CFGMR3QueryBoolDef(pCfg, "IgnoreFlushAsync", &pThis->fIgnoreFlushAsync, false);
5357 if (RT_FAILURE(rc))
5358 return PDMDRV_SET_ERROR(pDrvIns, rc, N_("Failed to query \"IgnoreFlushAsync\" from the config"));
5359
5360 if (pThis->fIgnoreFlushAsync)
5361 LogRel(("DrvVD: Async flushes will be ignored\n"));
5362 else
5363 LogRel(("DrvVD: Async flushes will be passed to the disk\n"));
5364#endif /* VBOX_IGNORE_FLUSH */
5365
5366 rc = CFGMR3QueryBoolDef(pCurNode, "EmptyDrive", &fEmptyDrive, false);
5367 if (RT_FAILURE(rc))
5368 {
5369 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
5370 N_("DrvVD: Configuration error: Querying \"EmptyDrive\" as boolean failed"));
5371 break;
5372 }
5373
5374 rc = CFGMR3QueryU32Def(pCfg, "IoBufMax", &cbIoBufMax, 5 * _1M);
5375 if (RT_FAILURE(rc))
5376 return PDMDRV_SET_ERROR(pDrvIns, rc, N_("Failed to query \"IoBufMax\" from the config"));
5377
5378 rc = CFGMR3QueryBoolDef(pCfg, "NonRotationalMedium", &pThis->fNonRotational, false);
5379 if (RT_FAILURE(rc))
5380 return PDMDRV_SET_ERROR(pDrvIns, rc,
5381 N_("DrvVD configuration error: Querying \"NonRotationalMedium\" as boolean failed"));
5382 }
5383
5384 PCFGMNODE pParent = CFGMR3GetChild(pCurNode, "Parent");
5385 if (!pParent)
5386 break;
5387 pCurNode = pParent;
5388 iLevel++;
5389 }
5390
5391 if (pThis->pDrvMediaExPort)
5392 rc = IOBUFMgrCreate(&pThis->hIoBufMgr, cbIoBufMax, pThis->pCfgCrypto ? IOBUFMGR_F_REQUIRE_NOT_PAGABLE : IOBUFMGR_F_DEFAULT);
5393
5394 if ( !fEmptyDrive
5395 && RT_SUCCESS(rc))
5396 {
5397 /*
5398 * Create the image container and the necessary interfaces.
5399 */
5400 if (RT_SUCCESS(rc))
5401 {
5402 /*
5403 * The image has a bandwidth group but the host cache is enabled.
5404 * Use the async I/O framework but tell it to enable the host cache.
5405 */
5406 if (!fUseNewIo && pThis->pszBwGroup)
5407 {
5408 pThis->fAsyncIoWithHostCache = true;
5409 fUseNewIo = true;
5410 }
5411
5412 /** @todo quick hack to work around problems in the async I/O
5413 * implementation (rw semaphore thread ownership problem)
5414 * while a merge is running. Remove once this is fixed. */
5415 if (pThis->fMergePending)
5416 fUseNewIo = false;
5417
5418 if (RT_SUCCESS(rc) && pThis->fMergePending)
5419 {
5420 rc = RTSemFastMutexCreate(&pThis->MergeCompleteMutex);
5421 if (RT_SUCCESS(rc))
5422 rc = RTSemRWCreate(&pThis->MergeLock);
5423 if (RT_SUCCESS(rc))
5424 {
5425 pThis->VDIfThreadSync.pfnStartRead = drvvdThreadStartRead;
5426 pThis->VDIfThreadSync.pfnFinishRead = drvvdThreadFinishRead;
5427 pThis->VDIfThreadSync.pfnStartWrite = drvvdThreadStartWrite;
5428 pThis->VDIfThreadSync.pfnFinishWrite = drvvdThreadFinishWrite;
5429
5430 rc = VDInterfaceAdd(&pThis->VDIfThreadSync.Core, "DrvVD_ThreadSync", VDINTERFACETYPE_THREADSYNC,
5431 pThis, sizeof(VDINTERFACETHREADSYNC), &pThis->pVDIfsDisk);
5432 }
5433 else
5434 {
5435 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
5436 N_("DrvVD: Failed to create semaphores for \"MergePending\""));
5437 }
5438 }
5439
5440 if (RT_SUCCESS(rc))
5441 {
5442 rc = VDCreate(pThis->pVDIfsDisk, drvvdGetVDFromMediaType(pThis->enmType), &pThis->pDisk);
5443 /* Error message is already set correctly. */
5444 }
5445 }
5446
5447 if (pThis->pDrvMediaExPort && fUseNewIo)
5448 pThis->fAsyncIOSupported = true;
5449
5450 uint64_t tsStart = RTTimeNanoTS();
5451
5452 unsigned iImageIdx = 0;
5453 while (pCurNode && RT_SUCCESS(rc))
5454 {
5455 /* Allocate per-image data. */
5456 PVBOXIMAGE pImage = drvvdNewImage(pThis);
5457 if (!pImage)
5458 {
5459 rc = VERR_NO_MEMORY;
5460 break;
5461 }
5462
5463 /*
5464 * Read the image configuration.
5465 */
5466 rc = CFGMR3QueryStringAlloc(pCurNode, "Path", &pszName);
5467 if (RT_FAILURE(rc))
5468 {
5469 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
5470 N_("DrvVD: Configuration error: Querying \"Path\" as string failed"));
5471 break;
5472 }
5473
5474 rc = CFGMR3QueryStringAlloc(pCurNode, "Format", &pszFormat);
5475 if (RT_FAILURE(rc))
5476 {
5477 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
5478 N_("DrvVD: Configuration error: Querying \"Format\" as string failed"));
5479 break;
5480 }
5481
5482 bool fMergeSource;
5483 rc = CFGMR3QueryBoolDef(pCurNode, "MergeSource", &fMergeSource, false);
5484 if (RT_FAILURE(rc))
5485 {
5486 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
5487 N_("DrvVD: Configuration error: Querying \"MergeSource\" as boolean failed"));
5488 break;
5489 }
5490 if (fMergeSource)
5491 {
5492 if (pThis->uMergeSource == VD_LAST_IMAGE)
5493 pThis->uMergeSource = iImageIdx;
5494 else
5495 {
5496 rc = PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_DRIVER_INVALID_PROPERTIES,
5497 N_("DrvVD: Configuration error: Multiple \"MergeSource\" occurrences"));
5498 break;
5499 }
5500 }
5501
5502 bool fMergeTarget;
5503 rc = CFGMR3QueryBoolDef(pCurNode, "MergeTarget", &fMergeTarget, false);
5504 if (RT_FAILURE(rc))
5505 {
5506 rc = PDMDRV_SET_ERROR(pDrvIns, rc,
5507 N_("DrvVD: Configuration error: Querying \"MergeTarget\" as boolean failed"));
5508 break;
5509 }
5510 if (fMergeTarget)
5511 {
5512 if (pThis->uMergeTarget == VD_LAST_IMAGE)
5513 pThis->uMergeTarget = iImageIdx;
5514 else
5515 {
5516 rc = PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_DRIVER_INVALID_PROPERTIES,
5517 N_("DrvVD: Configuration error: Multiple \"MergeTarget\" occurrences"));
5518 break;
5519 }
5520 }
5521
5522 PCFGMNODE pCfgVDConfig = CFGMR3GetChild(pCurNode, "VDConfig");
5523 pImage->VDIfConfig.pfnAreKeysValid = drvvdCfgAreKeysValid;
5524 pImage->VDIfConfig.pfnQuerySize = drvvdCfgQuerySize;
5525 pImage->VDIfConfig.pfnQuery = drvvdCfgQuery;
5526 pImage->VDIfConfig.pfnQueryBytes = NULL;
5527 rc = VDInterfaceAdd(&pImage->VDIfConfig.Core, "DrvVD_Config", VDINTERFACETYPE_CONFIG,
5528 pCfgVDConfig, sizeof(VDINTERFACECONFIG), &pImage->pVDIfsImage);
5529 AssertRC(rc);
5530
5531 /* Check VDConfig for encryption config. */
5532 if (pCfgVDConfig)
5533 pThis->pCfgCrypto = CFGMR3GetChild(pCfgVDConfig, "CRYPT");
5534
5535 if (pThis->pCfgCrypto)
5536 {
5537 /* Setup VDConfig interface for disk encryption support. */
5538 pThis->VDIfCfg.pfnAreKeysValid = drvvdCfgAreKeysValid;
5539 pThis->VDIfCfg.pfnQuerySize = drvvdCfgQuerySize;
5540 pThis->VDIfCfg.pfnQuery = drvvdCfgQuery;
5541 pThis->VDIfCfg.pfnQueryBytes = NULL;
5542
5543 pThis->VDIfCrypto.pfnKeyRetain = drvvdCryptoKeyRetain;
5544 pThis->VDIfCrypto.pfnKeyRelease = drvvdCryptoKeyRelease;
5545 pThis->VDIfCrypto.pfnKeyStorePasswordRetain = drvvdCryptoKeyStorePasswordRetain;
5546 pThis->VDIfCrypto.pfnKeyStorePasswordRelease = drvvdCryptoKeyStorePasswordRelease;
5547 }
5548
5549 /* Unconditionally insert the TCPNET interface, don't bother to check
5550 * if an image really needs it. Will be ignored. Since the TCPNET
5551 * interface is per image we could make this more flexible in the
5552 * future if we want to. */
5553 /* Construct TCPNET callback table depending on the config. This is
5554 * done unconditionally, as uninterested backends will ignore it. */
5555 if (fHostIP)
5556 {
5557 pImage->VDIfTcpNet.pfnSocketCreate = drvvdTcpSocketCreate;
5558 pImage->VDIfTcpNet.pfnSocketDestroy = drvvdTcpSocketDestroy;
5559 pImage->VDIfTcpNet.pfnClientConnect = drvvdTcpClientConnect;
5560 pImage->VDIfTcpNet.pfnIsClientConnected = drvvdTcpIsClientConnected;
5561 pImage->VDIfTcpNet.pfnClientClose = drvvdTcpClientClose;
5562 pImage->VDIfTcpNet.pfnSelectOne = drvvdTcpSelectOne;
5563 pImage->VDIfTcpNet.pfnRead = drvvdTcpRead;
5564 pImage->VDIfTcpNet.pfnWrite = drvvdTcpWrite;
5565 pImage->VDIfTcpNet.pfnSgWrite = drvvdTcpSgWrite;
5566 pImage->VDIfTcpNet.pfnReadNB = drvvdTcpReadNB;
5567 pImage->VDIfTcpNet.pfnWriteNB = drvvdTcpWriteNB;
5568 pImage->VDIfTcpNet.pfnSgWriteNB = drvvdTcpSgWriteNB;
5569 pImage->VDIfTcpNet.pfnFlush = drvvdTcpFlush;
5570 pImage->VDIfTcpNet.pfnSetSendCoalescing = drvvdTcpSetSendCoalescing;
5571 pImage->VDIfTcpNet.pfnGetLocalAddress = drvvdTcpGetLocalAddress;
5572 pImage->VDIfTcpNet.pfnGetPeerAddress = drvvdTcpGetPeerAddress;
5573
5574 /*
5575 * There is a 15ms delay between receiving the data and marking the socket
5576 * as readable on Windows XP which hurts async I/O performance of
5577 * TCP backends badly. Provide a different select method without
5578 * using poll on XP.
5579 * This is only used on XP because it is not as efficient as the one using poll
5580 * and all other Windows versions are working fine.
5581 */
5582 char szOS[64];
5583 memset(szOS, 0, sizeof(szOS));
5584 rc = RTSystemQueryOSInfo(RTSYSOSINFO_PRODUCT, &szOS[0], sizeof(szOS));
5585
5586 if (RT_SUCCESS(rc) && !strncmp(szOS, "Windows XP", 10))
5587 {
5588 LogRel(("VD: Detected Windows XP, disabled poll based waiting for TCP\n"));
5589 pImage->VDIfTcpNet.pfnSelectOneEx = drvvdTcpSelectOneExNoPoll;
5590 }
5591 else
5592 pImage->VDIfTcpNet.pfnSelectOneEx = drvvdTcpSelectOneExPoll;
5593
5594 pImage->VDIfTcpNet.pfnPoke = drvvdTcpPoke;
5595 }
5596 else
5597 {
5598#ifndef VBOX_WITH_INIP
5599 rc = PDMDrvHlpVMSetError(pDrvIns, VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES,
5600 RT_SRC_POS, N_("DrvVD: Configuration error: TCP over Internal Networking not compiled in"));
5601#else /* VBOX_WITH_INIP */
5602 pImage->VDIfTcpNet.pfnSocketCreate = drvvdINIPSocketCreate;
5603 pImage->VDIfTcpNet.pfnSocketDestroy = drvvdINIPSocketDestroy;
5604 pImage->VDIfTcpNet.pfnClientConnect = drvvdINIPClientConnect;
5605 pImage->VDIfTcpNet.pfnClientClose = drvvdINIPClientClose;
5606 pImage->VDIfTcpNet.pfnIsClientConnected = drvvdINIPIsClientConnected;
5607 pImage->VDIfTcpNet.pfnSelectOne = drvvdINIPSelectOne;
5608 pImage->VDIfTcpNet.pfnRead = drvvdINIPRead;
5609 pImage->VDIfTcpNet.pfnWrite = drvvdINIPWrite;
5610 pImage->VDIfTcpNet.pfnSgWrite = drvvdINIPSgWrite;
5611 pImage->VDIfTcpNet.pfnFlush = drvvdINIPFlush;
5612 pImage->VDIfTcpNet.pfnSetSendCoalescing = drvvdINIPSetSendCoalescing;
5613 pImage->VDIfTcpNet.pfnGetLocalAddress = drvvdINIPGetLocalAddress;
5614 pImage->VDIfTcpNet.pfnGetPeerAddress = drvvdINIPGetPeerAddress;
5615 pImage->VDIfTcpNet.pfnSelectOneEx = drvvdINIPSelectOneEx;
5616 pImage->VDIfTcpNet.pfnPoke = drvvdINIPPoke;
5617#endif /* VBOX_WITH_INIP */
5618 }
5619 rc = VDInterfaceAdd(&pImage->VDIfTcpNet.Core, "DrvVD_TCPNET",
5620 VDINTERFACETYPE_TCPNET, NULL,
5621 sizeof(VDINTERFACETCPNET), &pImage->pVDIfsImage);
5622 AssertRC(rc);
5623
5624 /* Insert the custom I/O interface only if we're told to use new IO.
5625 * Since the I/O interface is per image we could make this more
5626 * flexible in the future if we want to. */
5627 if (fUseNewIo)
5628 {
5629#ifdef VBOX_WITH_PDM_ASYNC_COMPLETION
5630 pImage->VDIfIo.pfnOpen = drvvdAsyncIOOpen;
5631 pImage->VDIfIo.pfnClose = drvvdAsyncIOClose;
5632 pImage->VDIfIo.pfnGetSize = drvvdAsyncIOGetSize;
5633 pImage->VDIfIo.pfnSetSize = drvvdAsyncIOSetSize;
5634 pImage->VDIfIo.pfnSetAllocationSize = drvvdAsyncIOSetAllocationSize;
5635 pImage->VDIfIo.pfnReadSync = drvvdAsyncIOReadSync;
5636 pImage->VDIfIo.pfnWriteSync = drvvdAsyncIOWriteSync;
5637 pImage->VDIfIo.pfnFlushSync = drvvdAsyncIOFlushSync;
5638 pImage->VDIfIo.pfnReadAsync = drvvdAsyncIOReadAsync;
5639 pImage->VDIfIo.pfnWriteAsync = drvvdAsyncIOWriteAsync;
5640 pImage->VDIfIo.pfnFlushAsync = drvvdAsyncIOFlushAsync;
5641#else /* !VBOX_WITH_PDM_ASYNC_COMPLETION */
5642 rc = PDMDrvHlpVMSetError(pDrvIns, VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES,
5643 RT_SRC_POS, N_("DrvVD: Configuration error: Async Completion Framework not compiled in"));
5644#endif /* !VBOX_WITH_PDM_ASYNC_COMPLETION */
5645 if (RT_SUCCESS(rc))
5646 rc = VDInterfaceAdd(&pImage->VDIfIo.Core, "DrvVD_IO", VDINTERFACETYPE_IO,
5647 pThis, sizeof(VDINTERFACEIO), &pImage->pVDIfsImage);
5648 AssertRC(rc);
5649 }
5650
5651 /*
5652 * Open the image.
5653 */
5654 unsigned uOpenFlags;
5655 if (fReadOnly || pThis->fTempReadOnly || iLevel != 0)
5656 uOpenFlags = VD_OPEN_FLAGS_READONLY;
5657 else
5658 uOpenFlags = VD_OPEN_FLAGS_NORMAL;
5659 if (fHonorZeroWrites)
5660 uOpenFlags |= VD_OPEN_FLAGS_HONOR_ZEROES;
5661 if (pThis->fAsyncIOSupported)
5662 uOpenFlags |= VD_OPEN_FLAGS_ASYNC_IO;
5663 if (pThis->fShareable)
5664 uOpenFlags |= VD_OPEN_FLAGS_SHAREABLE;
5665 if (fDiscard && iLevel == 0)
5666 uOpenFlags |= VD_OPEN_FLAGS_DISCARD;
5667 if (fInformAboutZeroBlocks)
5668 uOpenFlags |= VD_OPEN_FLAGS_INFORM_ABOUT_ZERO_BLOCKS;
5669 if ( (uOpenFlags & VD_OPEN_FLAGS_READONLY)
5670 && fSkipConsistencyChecks)
5671 uOpenFlags |= VD_OPEN_FLAGS_SKIP_CONSISTENCY_CHECKS;
5672
5673 /* Try to open backend in async I/O mode first. */
5674 rc = VDOpen(pThis->pDisk, pszFormat, pszName, uOpenFlags, pImage->pVDIfsImage);
5675 if (rc == VERR_NOT_SUPPORTED)
5676 {
5677 pThis->fAsyncIOSupported = false;
5678 uOpenFlags &= ~VD_OPEN_FLAGS_ASYNC_IO;
5679 rc = VDOpen(pThis->pDisk, pszFormat, pszName, uOpenFlags, pImage->pVDIfsImage);
5680 }
5681
5682 if (rc == VERR_VD_DISCARD_NOT_SUPPORTED)
5683 {
5684 fDiscard = false;
5685 uOpenFlags &= ~VD_OPEN_FLAGS_DISCARD;
5686 rc = VDOpen(pThis->pDisk, pszFormat, pszName, uOpenFlags, pImage->pVDIfsImage);
5687 }
5688
5689 if (!fDiscard)
5690 {
5691 pThis->IMedia.pfnDiscard = NULL;
5692 pThis->IMediaEx.pfnIoReqDiscard = NULL;
5693 }
5694
5695 if (RT_SUCCESS(rc))
5696 {
5697 LogFunc(("%d - Opened '%s' in %s mode\n",
5698 iLevel, pszName,
5699 VDIsReadOnly(pThis->pDisk) ? "read-only" : "read-write"));
5700 if ( VDIsReadOnly(pThis->pDisk)
5701 && !fReadOnly
5702 && !fMaybeReadOnly
5703 && !pThis->fTempReadOnly
5704 && iLevel == 0)
5705 {
5706 rc = PDMDrvHlpVMSetError(pDrvIns, VERR_VD_IMAGE_READ_ONLY, RT_SRC_POS,
5707 N_("Failed to open image '%s' for writing due to wrong permissions"),
5708 pszName);
5709 break;
5710 }
5711 }
5712 else
5713 {
5714 rc = PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS,
5715 N_("Failed to open image '%s' in %s mode"), pszName,
5716 (uOpenFlags & VD_OPEN_FLAGS_READONLY) ? "read-only" : "read-write");
5717 break;
5718 }
5719
5720 MMR3HeapFree(pszName);
5721 pszName = NULL;
5722 MMR3HeapFree(pszFormat);
5723 pszFormat = NULL;
5724
5725 /* next */
5726 iLevel--;
5727 iImageIdx++;
5728 pCurNode = CFGMR3GetParent(pCurNode);
5729 }
5730
5731 LogRel(("VD: Opening the disk took %lld ns\n", RTTimeNanoTS() - tsStart));
5732
5733 /* Open the cache image if set. */
5734 if ( RT_SUCCESS(rc)
5735 && RT_VALID_PTR(pszCachePath))
5736 {
5737 /* Insert the custom I/O interface only if we're told to use new IO.
5738 * Since the I/O interface is per image we could make this more
5739 * flexible in the future if we want to. */
5740 if (fUseNewIo)
5741 {
5742#ifdef VBOX_WITH_PDM_ASYNC_COMPLETION
5743 pThis->VDIfIoCache.pfnOpen = drvvdAsyncIOOpen;
5744 pThis->VDIfIoCache.pfnClose = drvvdAsyncIOClose;
5745 pThis->VDIfIoCache.pfnGetSize = drvvdAsyncIOGetSize;
5746 pThis->VDIfIoCache.pfnSetSize = drvvdAsyncIOSetSize;
5747 pThis->VDIfIoCache.pfnReadSync = drvvdAsyncIOReadSync;
5748 pThis->VDIfIoCache.pfnWriteSync = drvvdAsyncIOWriteSync;
5749 pThis->VDIfIoCache.pfnFlushSync = drvvdAsyncIOFlushSync;
5750 pThis->VDIfIoCache.pfnReadAsync = drvvdAsyncIOReadAsync;
5751 pThis->VDIfIoCache.pfnWriteAsync = drvvdAsyncIOWriteAsync;
5752 pThis->VDIfIoCache.pfnFlushAsync = drvvdAsyncIOFlushAsync;
5753#else /* !VBOX_WITH_PDM_ASYNC_COMPLETION */
5754 rc = PDMDrvHlpVMSetError(pDrvIns, VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES,
5755 RT_SRC_POS, N_("DrvVD: Configuration error: Async Completion Framework not compiled in"));
5756#endif /* !VBOX_WITH_PDM_ASYNC_COMPLETION */
5757 if (RT_SUCCESS(rc))
5758 rc = VDInterfaceAdd(&pThis->VDIfIoCache.Core, "DrvVD_IO", VDINTERFACETYPE_IO,
5759 pThis, sizeof(VDINTERFACEIO), &pThis->pVDIfsCache);
5760 AssertRC(rc);
5761 }
5762
5763 rc = VDCacheOpen(pThis->pDisk, pszCacheFormat, pszCachePath, VD_OPEN_FLAGS_NORMAL, pThis->pVDIfsCache);
5764 if (RT_FAILURE(rc))
5765 rc = PDMDRV_SET_ERROR(pDrvIns, rc, N_("DrvVD: Could not open cache image"));
5766 }
5767
5768 if (RT_VALID_PTR(pszCachePath))
5769 MMR3HeapFree(pszCachePath);
5770 if (RT_VALID_PTR(pszCacheFormat))
5771 MMR3HeapFree(pszCacheFormat);
5772
5773 if ( RT_SUCCESS(rc)
5774 && pThis->fMergePending
5775 && ( pThis->uMergeSource == VD_LAST_IMAGE
5776 || pThis->uMergeTarget == VD_LAST_IMAGE))
5777 {
5778 rc = PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_DRIVER_INVALID_PROPERTIES,
5779 N_("DrvVD: Configuration error: Inconsistent image merge data"));
5780 }
5781
5782 /* Create the block cache if enabled. */
5783 if ( fUseBlockCache
5784 && !pThis->fShareable
5785 && !fDiscard
5786 && !pThis->pCfgCrypto /* Disk encryption disables the block cache for security reasons */
5787 && RT_SUCCESS(rc))
5788 {
5789 /*
5790 * We need a unique ID for the block cache (to identify the owner of data
5791 * blocks in a saved state). UUIDs are not really suitable because
5792 * there are image formats which don't support them. Furthermore it is
5793 * possible that a new diff image was attached after a saved state
5794 * which changes the UUID.
5795 * However the device "name + device instance + LUN" triple the disk is
5796 * attached to is always constant for saved states.
5797 */
5798 char *pszId = NULL;
5799 uint32_t iInstance, iLUN;
5800 const char *pcszController;
5801
5802 rc = pThis->pDrvMediaPort->pfnQueryDeviceLocation(pThis->pDrvMediaPort, &pcszController,
5803 &iInstance, &iLUN);
5804 if (RT_FAILURE(rc))
5805 rc = PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_DRIVER_INVALID_PROPERTIES,
5806 N_("DrvVD: Configuration error: Could not query device data"));
5807 else
5808 {
5809 int cbStr = RTStrAPrintf(&pszId, "%s-%d-%d", pcszController, iInstance, iLUN);
5810
5811 if (cbStr > 0)
5812 {
5813 rc = PDMDrvHlpBlkCacheRetain(pDrvIns, &pThis->pBlkCache,
5814 drvvdBlkCacheXferCompleteIoReq,
5815 drvvdBlkCacheXferEnqueue,
5816 drvvdBlkCacheXferEnqueueDiscard,
5817 pszId);
5818 if (rc == VERR_NOT_SUPPORTED)
5819 {
5820 LogRel(("VD: Block cache is not supported\n"));
5821 rc = VINF_SUCCESS;
5822 }
5823 else
5824 AssertRC(rc);
5825
5826 RTStrFree(pszId);
5827 }
5828 else
5829 rc = PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_DRIVER_INVALID_PROPERTIES,
5830 N_("DrvVD: Out of memory when creating block cache"));
5831 }
5832 }
5833
5834 if (RT_SUCCESS(rc))
5835 rc = drvvdSetupFilters(pThis, pCfg);
5836
5837 /*
5838 * Register a load-done callback so we can undo TempReadOnly config before
5839 * we get to drvvdResume. Automatically deregistered upon destruction.
5840 */
5841 if (RT_SUCCESS(rc))
5842 rc = PDMDrvHlpSSMRegisterEx(pDrvIns, 0 /* version */, 0 /* cbGuess */,
5843 NULL /*pfnLivePrep*/, NULL /*pfnLiveExec*/, NULL /*pfnLiveVote*/,
5844 NULL /*pfnSavePrep*/, NULL /*pfnSaveExec*/, NULL /*pfnSaveDone*/,
5845 NULL /*pfnDonePrep*/, NULL /*pfnLoadExec*/, drvvdLoadDone);
5846
5847 /* Setup the boot acceleration stuff if enabled. */
5848 if (RT_SUCCESS(rc) && pThis->fBootAccelEnabled)
5849 {
5850 pThis->cbDisk = VDGetSize(pThis->pDisk, VD_LAST_IMAGE);
5851 Assert(pThis->cbDisk > 0);
5852 pThis->pbData = (uint8_t *)RTMemAllocZ(pThis->cbBootAccelBuffer);
5853 if (pThis->pbData)
5854 {
5855 pThis->fBootAccelActive = true;
5856 pThis->offDisk = 0;
5857 pThis->cbDataValid = 0;
5858 LogRel(("VD: Boot acceleration enabled\n"));
5859 }
5860 else
5861 LogRel(("VD: Boot acceleration, out of memory, disabled\n"));
5862 }
5863
5864 if ( RTUuidIsNull(&pThis->Uuid)
5865 && pThis->enmType == PDMMEDIATYPE_HARD_DISK)
5866 VDGetUuid(pThis->pDisk, 0, &pThis->Uuid);
5867
5868 /*
5869 * Automatically upgrade the floppy drive if the specified one is too
5870 * small to represent the whole boot time image. (We cannot do this later
5871 * since the BIOS (and others) gets the info via CMOS.)
5872 *
5873 * This trick should make 2.88 images as well as the fake 15.6 and 63.5 MB
5874 * images despite the hardcoded default 1.44 drive.
5875 */
5876 if ( PDMMEDIATYPE_IS_FLOPPY(pThis->enmType)
5877 && pThis->pDisk)
5878 {
5879 uint64_t const cbFloppyImg = VDGetSize(pThis->pDisk, VD_LAST_IMAGE);
5880 PDMMEDIATYPE const enmCfgType = pThis->enmType;
5881 switch (enmCfgType)
5882 {
5883 default:
5884 AssertFailed();
5885 RT_FALL_THRU();
5886 case PDMMEDIATYPE_FLOPPY_360:
5887 if (cbFloppyImg > 40 * 2 * 9 * 512)
5888 pThis->enmType = PDMMEDIATYPE_FLOPPY_720;
5889 RT_FALL_THRU();
5890 case PDMMEDIATYPE_FLOPPY_720:
5891 if (cbFloppyImg > 80 * 2 * 14 * 512)
5892 pThis->enmType = PDMMEDIATYPE_FLOPPY_1_20;
5893 RT_FALL_THRU();
5894 case PDMMEDIATYPE_FLOPPY_1_20:
5895 if (cbFloppyImg > 80 * 2 * 20 * 512)
5896 pThis->enmType = PDMMEDIATYPE_FLOPPY_1_44;
5897 RT_FALL_THRU();
5898 case PDMMEDIATYPE_FLOPPY_1_44:
5899 if (cbFloppyImg > 80 * 2 * 24 * 512)
5900 pThis->enmType = PDMMEDIATYPE_FLOPPY_2_88;
5901 RT_FALL_THRU();
5902 case PDMMEDIATYPE_FLOPPY_2_88:
5903 if (cbFloppyImg > 80 * 2 * 48 * 512)
5904 pThis->enmType = PDMMEDIATYPE_FLOPPY_FAKE_15_6;
5905 RT_FALL_THRU();
5906 case PDMMEDIATYPE_FLOPPY_FAKE_15_6:
5907 if (cbFloppyImg > 255 * 2 * 63 * 512)
5908 pThis->enmType = PDMMEDIATYPE_FLOPPY_FAKE_63_5;
5909 RT_FALL_THRU();
5910 case PDMMEDIATYPE_FLOPPY_FAKE_63_5:
5911 if (cbFloppyImg > 255 * 2 * 255 * 512)
5912 LogRel(("Warning: Floppy image is larger that 63.5 MB! (%llu bytes)\n", cbFloppyImg));
5913 break;
5914 }
5915 if (pThis->enmType != enmCfgType)
5916 LogRel(("DrvVD: Automatically upgraded floppy drive from %s to %s to better support the %u byte image\n",
5917 drvvdGetTypeName(enmCfgType), drvvdGetTypeName(pThis->enmType), cbFloppyImg));
5918 }
5919 } /* !fEmptyDrive */
5920
5921 if (RT_SUCCESS(rc))
5922 drvvdStatsRegister(pThis);
5923
5924 if (RT_FAILURE(rc))
5925 {
5926 if (RT_VALID_PTR(pszName))
5927 MMR3HeapFree(pszName);
5928 if (RT_VALID_PTR(pszFormat))
5929 MMR3HeapFree(pszFormat);
5930 /* drvvdDestruct does the rest. */
5931 }
5932
5933 LogFlowFunc(("returns %Rrc\n", rc));
5934 return rc;
5935}
5936
5937/**
5938 * VBox disk container media driver registration record.
5939 */
5940const PDMDRVREG g_DrvVD =
5941{
5942 /* u32Version */
5943 PDM_DRVREG_VERSION,
5944 /* szName */
5945 "VD",
5946 /* szRCMod */
5947 "",
5948 /* szR0Mod */
5949 "",
5950 /* pszDescription */
5951 "Generic VBox disk media driver.",
5952 /* fFlags */
5953 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
5954 /* fClass. */
5955 PDM_DRVREG_CLASS_MEDIA,
5956 /* cMaxInstances */
5957 ~0U,
5958 /* cbInstance */
5959 sizeof(VBOXDISK),
5960 /* pfnConstruct */
5961 drvvdConstruct,
5962 /* pfnDestruct */
5963 drvvdDestruct,
5964 /* pfnRelocate */
5965 NULL,
5966 /* pfnIOCtl */
5967 NULL,
5968 /* pfnPowerOn */
5969 drvvdPowerOn,
5970 /* pfnReset */
5971 drvvdReset,
5972 /* pfnSuspend */
5973 drvvdSuspend,
5974 /* pfnResume */
5975 drvvdResume,
5976 /* pfnAttach */
5977 NULL,
5978 /* pfnDetach */
5979 NULL,
5980 /* pfnPowerOff */
5981 drvvdPowerOff,
5982 /* pfnSoftReset */
5983 NULL,
5984 /* u32EndVersion */
5985 PDM_DRVREG_VERSION
5986};
5987
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