VirtualBox

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

Last change on this file since 64008 was 64005, checked in by vboxsync, 9 years ago

DrvVD: Logging for discard requests in the error case too

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

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette