VirtualBox

source: vbox/trunk/src/VBox/Devices/Storage/DrvHostBase.cpp@ 36797

Last change on this file since 36797 was 36797, checked in by vboxsync, 14 years ago

FreeBSD: Warnings

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 76.1 KB
Line 
1/* $Id: DrvHostBase.cpp 36797 2011-04-21 15:46:31Z vboxsync $ */
2/** @file
3 * DrvHostBase - Host base drive access driver.
4 */
5
6/*
7 * Copyright (C) 2006-2007 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_HOST_BASE
23#ifdef RT_OS_DARWIN
24# include <mach/mach.h>
25# include <Carbon/Carbon.h>
26# include <IOKit/IOKitLib.h>
27# include <IOKit/storage/IOStorageDeviceCharacteristics.h>
28# include <IOKit/scsi/SCSITaskLib.h>
29# include <IOKit/scsi/SCSICommandOperationCodes.h>
30# include <IOKit/IOBSD.h>
31# include <DiskArbitration/DiskArbitration.h>
32# include <mach/mach_error.h>
33# include <VBox/scsi.h>
34
35#elif defined(RT_OS_L4)
36 /* Nothing special requires... yeah, right. */
37
38#elif defined(RT_OS_LINUX)
39# include <sys/ioctl.h>
40# include <sys/fcntl.h>
41# include <errno.h>
42
43#elif defined(RT_OS_SOLARIS)
44# include <fcntl.h>
45# include <errno.h>
46# include <stropts.h>
47# include <malloc.h>
48# include <sys/dkio.h>
49extern "C" char *getfullblkname(char *);
50
51#elif defined(RT_OS_WINDOWS)
52# define WIN32_NO_STATUS
53# include <Windows.h>
54# include <dbt.h>
55# undef WIN32_NO_STATUS
56# include <ntstatus.h>
57
58/* from ntdef.h */
59typedef LONG NTSTATUS;
60
61/* from ntddk.h */
62typedef struct _IO_STATUS_BLOCK {
63 union {
64 NTSTATUS Status;
65 PVOID Pointer;
66 };
67 ULONG_PTR Information;
68} IO_STATUS_BLOCK, *PIO_STATUS_BLOCK;
69
70
71/* from ntinternals.com */
72typedef enum _FS_INFORMATION_CLASS {
73 FileFsVolumeInformation=1,
74 FileFsLabelInformation,
75 FileFsSizeInformation,
76 FileFsDeviceInformation,
77 FileFsAttributeInformation,
78 FileFsControlInformation,
79 FileFsFullSizeInformation,
80 FileFsObjectIdInformation,
81 FileFsMaximumInformation
82} FS_INFORMATION_CLASS, *PFS_INFORMATION_CLASS;
83
84typedef struct _FILE_FS_SIZE_INFORMATION {
85 LARGE_INTEGER TotalAllocationUnits;
86 LARGE_INTEGER AvailableAllocationUnits;
87 ULONG SectorsPerAllocationUnit;
88 ULONG BytesPerSector;
89} FILE_FS_SIZE_INFORMATION, *PFILE_FS_SIZE_INFORMATION;
90
91extern "C"
92NTSTATUS __stdcall NtQueryVolumeInformationFile(
93 /*IN*/ HANDLE FileHandle,
94 /*OUT*/ PIO_STATUS_BLOCK IoStatusBlock,
95 /*OUT*/ PVOID FileSystemInformation,
96 /*IN*/ ULONG Length,
97 /*IN*/ FS_INFORMATION_CLASS FileSystemInformationClass );
98
99#elif defined(RT_OS_FREEBSD)
100# include <sys/cdefs.h>
101# include <sys/param.h>
102# include <errno.h>
103# include <stdio.h>
104# include <cam/cam.h>
105# include <cam/cam_ccb.h>
106# include <cam/scsi/scsi_message.h>
107# include <cam/scsi/scsi_pass.h>
108# include <VBox/scsi.h>
109# include <iprt/log.h>
110#else
111# error "Unsupported Platform."
112#endif
113
114#include <VBox/vmm/pdmdrv.h>
115#include <iprt/assert.h>
116#include <iprt/file.h>
117#include <iprt/path.h>
118#include <iprt/string.h>
119#include <iprt/thread.h>
120#include <iprt/semaphore.h>
121#include <iprt/uuid.h>
122#include <iprt/asm.h>
123#include <iprt/critsect.h>
124#include <iprt/ctype.h>
125
126#include "DrvHostBase.h"
127
128
129
130
131/* -=-=-=-=- IBlock -=-=-=-=- */
132
133/** @copydoc PDMIBLOCK::pfnRead */
134static DECLCALLBACK(int) drvHostBaseRead(PPDMIBLOCK pInterface, uint64_t off, void *pvBuf, size_t cbRead)
135{
136 PDRVHOSTBASE pThis = PDMIBLOCK_2_DRVHOSTBASE(pInterface);
137 LogFlow(("%s-%d: drvHostBaseRead: off=%#llx pvBuf=%p cbRead=%#x (%s)\n",
138 pThis->pDrvIns->pReg->szName, pThis->pDrvIns->iInstance, off, pvBuf, cbRead, pThis->pszDevice));
139 RTCritSectEnter(&pThis->CritSect);
140
141 /*
142 * Check the state.
143 */
144 int rc;
145#ifdef RT_OS_DARWIN
146 if ( pThis->fMediaPresent
147 && pThis->ppScsiTaskDI
148 && pThis->cbBlock)
149#elif RT_OS_FREEBSD
150 if ( pThis->fMediaPresent
151 && pThis->cbBlock)
152#else
153 if (pThis->fMediaPresent)
154#endif
155 {
156#if defined(RT_OS_DARWIN) || defined(RT_OS_FREEBSD)
157 /*
158 * Issue a READ(12) request.
159 */
160 do
161 {
162 const uint32_t LBA = off / pThis->cbBlock;
163 AssertReturn(!(off % pThis->cbBlock), VERR_INVALID_PARAMETER);
164 uint32_t cbRead32 = cbRead > SCSI_MAX_BUFFER_SIZE
165 ? SCSI_MAX_BUFFER_SIZE
166 : (uint32_t)cbRead;
167 const uint32_t cBlocks = cbRead32 / pThis->cbBlock;
168 AssertReturn(!(cbRead % pThis->cbBlock), VERR_INVALID_PARAMETER);
169 uint8_t abCmd[16] =
170 {
171 SCSI_READ_12, 0,
172 RT_BYTE4(LBA), RT_BYTE3(LBA), RT_BYTE2(LBA), RT_BYTE1(LBA),
173 RT_BYTE4(cBlocks), RT_BYTE3(cBlocks), RT_BYTE2(cBlocks), RT_BYTE1(cBlocks),
174 0, 0, 0, 0, 0
175 };
176 rc = DRVHostBaseScsiCmd(pThis, abCmd, 12, PDMBLOCKTXDIR_FROM_DEVICE, pvBuf, &cbRead32, NULL, 0, 0);
177
178 off += cbRead32;
179 cbRead -= cbRead32;
180 pvBuf = (uint8_t *)pvBuf + cbRead32;
181 } while ((cbRead > 0) && RT_SUCCESS(rc));
182
183#else
184 /*
185 * Seek and read.
186 */
187 rc = RTFileSeek(pThis->FileDevice, off, RTFILE_SEEK_BEGIN, NULL);
188 if (RT_SUCCESS(rc))
189 {
190 rc = RTFileRead(pThis->FileDevice, pvBuf, cbRead, NULL);
191 if (RT_SUCCESS(rc))
192 {
193 Log2(("%s-%d: drvHostBaseRead: off=%#llx cbRead=%#x\n"
194 "%16.*Rhxd\n",
195 pThis->pDrvIns->pReg->szName, pThis->pDrvIns->iInstance, off, cbRead, cbRead, pvBuf));
196 }
197 else
198 Log(("%s-%d: drvHostBaseRead: RTFileRead(%d, %p, %#x) -> %Rrc (off=%#llx '%s')\n",
199 pThis->pDrvIns->pReg->szName, pThis->pDrvIns->iInstance, pThis->FileDevice,
200 pvBuf, cbRead, rc, off, pThis->pszDevice));
201 }
202 else
203 Log(("%s-%d: drvHostBaseRead: RTFileSeek(%d,%#llx,) -> %Rrc\n", pThis->pDrvIns->pReg->szName,
204 pThis->pDrvIns->iInstance, pThis->FileDevice, off, rc));
205#endif
206 }
207 else
208 rc = VERR_MEDIA_NOT_PRESENT;
209
210 RTCritSectLeave(&pThis->CritSect);
211 LogFlow(("%s-%d: drvHostBaseRead: returns %Rrc\n", pThis->pDrvIns->pReg->szName, pThis->pDrvIns->iInstance, rc));
212 return rc;
213}
214
215
216/** @copydoc PDMIBLOCK::pfnWrite */
217static DECLCALLBACK(int) drvHostBaseWrite(PPDMIBLOCK pInterface, uint64_t off, const void *pvBuf, size_t cbWrite)
218{
219 PDRVHOSTBASE pThis = PDMIBLOCK_2_DRVHOSTBASE(pInterface);
220 LogFlow(("%s-%d: drvHostBaseWrite: off=%#llx pvBuf=%p cbWrite=%#x (%s)\n",
221 pThis->pDrvIns->pReg->szName, pThis->pDrvIns->iInstance, off, pvBuf, cbWrite, pThis->pszDevice));
222 Log2(("%s-%d: drvHostBaseWrite: off=%#llx cbWrite=%#x\n"
223 "%16.*Rhxd\n",
224 pThis->pDrvIns->pReg->szName, pThis->pDrvIns->iInstance, off, cbWrite, cbWrite, pvBuf));
225 RTCritSectEnter(&pThis->CritSect);
226
227 /*
228 * Check the state.
229 */
230 int rc;
231 if (!pThis->fReadOnly)
232 {
233 if (pThis->fMediaPresent)
234 {
235#if defined(RT_OS_DARWIN) || defined(RT_OS_FREEBSD)
236 /** @todo write support... */
237 rc = VERR_WRITE_PROTECT;
238
239#else
240 /*
241 * Seek and write.
242 */
243 rc = RTFileSeek(pThis->FileDevice, off, RTFILE_SEEK_BEGIN, NULL);
244 if (RT_SUCCESS(rc))
245 {
246 rc = RTFileWrite(pThis->FileDevice, pvBuf, cbWrite, NULL);
247 if (RT_FAILURE(rc))
248 Log(("%s-%d: drvHostBaseWrite: RTFileWrite(%d, %p, %#x) -> %Rrc (off=%#llx '%s')\n",
249 pThis->pDrvIns->pReg->szName, pThis->pDrvIns->iInstance, pThis->FileDevice,
250 pvBuf, cbWrite, rc, off, pThis->pszDevice));
251 }
252 else
253 Log(("%s-%d: drvHostBaseWrite: RTFileSeek(%d,%#llx,) -> %Rrc\n",
254 pThis->pDrvIns->pReg->szName, pThis->pDrvIns->iInstance, pThis->FileDevice, off, rc));
255#endif
256 }
257 else
258 rc = VERR_MEDIA_NOT_PRESENT;
259 }
260 else
261 rc = VERR_WRITE_PROTECT;
262
263 RTCritSectLeave(&pThis->CritSect);
264 LogFlow(("%s-%d: drvHostBaseWrite: returns %Rrc\n", pThis->pDrvIns->pReg->szName, pThis->pDrvIns->iInstance, rc));
265 return rc;
266}
267
268
269/** @copydoc PDMIBLOCK::pfnFlush */
270static DECLCALLBACK(int) drvHostBaseFlush(PPDMIBLOCK pInterface)
271{
272 int rc;
273 PDRVHOSTBASE pThis = PDMIBLOCK_2_DRVHOSTBASE(pInterface);
274 LogFlow(("%s-%d: drvHostBaseFlush: (%s)\n",
275 pThis->pDrvIns->pReg->szName, pThis->pDrvIns->iInstance, pThis->pszDevice));
276 RTCritSectEnter(&pThis->CritSect);
277
278 if (pThis->fMediaPresent)
279 {
280#if defined(RT_OS_DARWIN) || defined(RT_OS_FREEBSD)
281 rc = VINF_SUCCESS;
282 /** @todo scsi device buffer flush... */
283#else
284 rc = RTFileFlush(pThis->FileDevice);
285#endif
286 }
287 else
288 rc = VERR_MEDIA_NOT_PRESENT;
289
290 RTCritSectLeave(&pThis->CritSect);
291 LogFlow(("%s-%d: drvHostBaseFlush: returns %Rrc\n", pThis->pDrvIns->pReg->szName, pThis->pDrvIns->iInstance, rc));
292 return rc;
293}
294
295
296/** @copydoc PDMIBLOCK::pfnIsReadOnly */
297static DECLCALLBACK(bool) drvHostBaseIsReadOnly(PPDMIBLOCK pInterface)
298{
299 PDRVHOSTBASE pThis = PDMIBLOCK_2_DRVHOSTBASE(pInterface);
300 return pThis->fReadOnly;
301}
302
303
304/** @copydoc PDMIBLOCK::pfnGetSize */
305static DECLCALLBACK(uint64_t) drvHostBaseGetSize(PPDMIBLOCK pInterface)
306{
307 PDRVHOSTBASE pThis = PDMIBLOCK_2_DRVHOSTBASE(pInterface);
308 RTCritSectEnter(&pThis->CritSect);
309
310 uint64_t cb = 0;
311 if (pThis->fMediaPresent)
312 cb = pThis->cbSize;
313
314 RTCritSectLeave(&pThis->CritSect);
315 LogFlow(("%s-%d: drvHostBaseGetSize: returns %llu\n", pThis->pDrvIns->pReg->szName, pThis->pDrvIns->iInstance, cb));
316 return cb;
317}
318
319
320/** @copydoc PDMIBLOCK::pfnGetType */
321static DECLCALLBACK(PDMBLOCKTYPE) drvHostBaseGetType(PPDMIBLOCK pInterface)
322{
323 PDRVHOSTBASE pThis = PDMIBLOCK_2_DRVHOSTBASE(pInterface);
324 LogFlow(("%s-%d: drvHostBaseGetType: returns %d\n", pThis->pDrvIns->pReg->szName, pThis->pDrvIns->iInstance, pThis->enmType));
325 return pThis->enmType;
326}
327
328
329/** @copydoc PDMIBLOCK::pfnGetUuid */
330static DECLCALLBACK(int) drvHostBaseGetUuid(PPDMIBLOCK pInterface, PRTUUID pUuid)
331{
332 PDRVHOSTBASE pThis = PDMIBLOCK_2_DRVHOSTBASE(pInterface);
333
334 *pUuid = pThis->Uuid;
335
336 LogFlow(("%s-%d: drvHostBaseGetUuid: returns VINF_SUCCESS *pUuid=%RTuuid\n", pThis->pDrvIns->pReg->szName, pThis->pDrvIns->iInstance, pUuid));
337 return VINF_SUCCESS;
338}
339
340
341/* -=-=-=-=- IBlockBios -=-=-=-=- */
342
343/** Makes a PDRVHOSTBASE out of a PPDMIBLOCKBIOS. */
344#define PDMIBLOCKBIOS_2_DRVHOSTBASE(pInterface) ( (PDRVHOSTBASE((uintptr_t)pInterface - RT_OFFSETOF(DRVHOSTBASE, IBlockBios))) )
345
346
347/** @copydoc PDMIBLOCKBIOS::pfnGetPCHSGeometry */
348static DECLCALLBACK(int) drvHostBaseGetPCHSGeometry(PPDMIBLOCKBIOS pInterface, PPDMMEDIAGEOMETRY pPCHSGeometry)
349{
350 PDRVHOSTBASE pThis = PDMIBLOCKBIOS_2_DRVHOSTBASE(pInterface);
351 RTCritSectEnter(&pThis->CritSect);
352
353 int rc = VINF_SUCCESS;
354 if (pThis->fMediaPresent)
355 {
356 if ( pThis->PCHSGeometry.cCylinders > 0
357 && pThis->PCHSGeometry.cHeads > 0
358 && pThis->PCHSGeometry.cSectors > 0)
359 {
360 *pPCHSGeometry = pThis->PCHSGeometry;
361 }
362 else
363 rc = VERR_PDM_GEOMETRY_NOT_SET;
364 }
365 else
366 rc = VERR_PDM_MEDIA_NOT_MOUNTED;
367
368 RTCritSectLeave(&pThis->CritSect);
369 LogFlow(("%s-%d: %s: returns %Rrc CHS={%d,%d,%d}\n",
370 pThis->pDrvIns->pReg->szName, pThis->pDrvIns->iInstance, __FUNCTION__, rc, pThis->PCHSGeometry.cCylinders, pThis->PCHSGeometry.cHeads, pThis->PCHSGeometry.cSectors));
371 return rc;
372}
373
374
375/** @copydoc PDMIBLOCKBIOS::pfnSetPCHSGeometry */
376static DECLCALLBACK(int) drvHostBaseSetPCHSGeometry(PPDMIBLOCKBIOS pInterface, PCPDMMEDIAGEOMETRY pPCHSGeometry)
377{
378 PDRVHOSTBASE pThis = PDMIBLOCKBIOS_2_DRVHOSTBASE(pInterface);
379 LogFlow(("%s-%d: %s: cCylinders=%d cHeads=%d cSectors=%d\n",
380 pThis->pDrvIns->pReg->szName, pThis->pDrvIns->iInstance, __FUNCTION__, pPCHSGeometry->cCylinders, pPCHSGeometry->cHeads, pPCHSGeometry->cSectors));
381 RTCritSectEnter(&pThis->CritSect);
382
383 int rc = VINF_SUCCESS;
384 if (pThis->fMediaPresent)
385 {
386 pThis->PCHSGeometry = *pPCHSGeometry;
387 }
388 else
389 {
390 AssertMsgFailed(("Invalid state! Not mounted!\n"));
391 rc = VERR_PDM_MEDIA_NOT_MOUNTED;
392 }
393
394 RTCritSectLeave(&pThis->CritSect);
395 return rc;
396}
397
398
399/** @copydoc PDMIBLOCKBIOS::pfnGetLCHSGeometry */
400static DECLCALLBACK(int) drvHostBaseGetLCHSGeometry(PPDMIBLOCKBIOS pInterface, PPDMMEDIAGEOMETRY pLCHSGeometry)
401{
402 PDRVHOSTBASE pThis = PDMIBLOCKBIOS_2_DRVHOSTBASE(pInterface);
403 RTCritSectEnter(&pThis->CritSect);
404
405 int rc = VINF_SUCCESS;
406 if (pThis->fMediaPresent)
407 {
408 if ( pThis->LCHSGeometry.cCylinders > 0
409 && pThis->LCHSGeometry.cHeads > 0
410 && pThis->LCHSGeometry.cSectors > 0)
411 {
412 *pLCHSGeometry = pThis->LCHSGeometry;
413 }
414 else
415 rc = VERR_PDM_GEOMETRY_NOT_SET;
416 }
417 else
418 rc = VERR_PDM_MEDIA_NOT_MOUNTED;
419
420 RTCritSectLeave(&pThis->CritSect);
421 LogFlow(("%s-%d: %s: returns %Rrc CHS={%d,%d,%d}\n",
422 pThis->pDrvIns->pReg->szName, pThis->pDrvIns->iInstance, __FUNCTION__, rc, pThis->LCHSGeometry.cCylinders, pThis->LCHSGeometry.cHeads, pThis->LCHSGeometry.cSectors));
423 return rc;
424}
425
426
427/** @copydoc PDMIBLOCKBIOS::pfnSetLCHSGeometry */
428static DECLCALLBACK(int) drvHostBaseSetLCHSGeometry(PPDMIBLOCKBIOS pInterface, PCPDMMEDIAGEOMETRY pLCHSGeometry)
429{
430 PDRVHOSTBASE pThis = PDMIBLOCKBIOS_2_DRVHOSTBASE(pInterface);
431 LogFlow(("%s-%d: %s: cCylinders=%d cHeads=%d cSectors=%d\n",
432 pThis->pDrvIns->pReg->szName, pThis->pDrvIns->iInstance, __FUNCTION__, pLCHSGeometry->cCylinders, pLCHSGeometry->cHeads, pLCHSGeometry->cSectors));
433 RTCritSectEnter(&pThis->CritSect);
434
435 int rc = VINF_SUCCESS;
436 if (pThis->fMediaPresent)
437 {
438 pThis->LCHSGeometry = *pLCHSGeometry;
439 }
440 else
441 {
442 AssertMsgFailed(("Invalid state! Not mounted!\n"));
443 rc = VERR_PDM_MEDIA_NOT_MOUNTED;
444 }
445
446 RTCritSectLeave(&pThis->CritSect);
447 return rc;
448}
449
450
451/** @copydoc PDMIBLOCKBIOS::pfnIsVisible */
452static DECLCALLBACK(bool) drvHostBaseIsVisible(PPDMIBLOCKBIOS pInterface)
453{
454 PDRVHOSTBASE pThis = PDMIBLOCKBIOS_2_DRVHOSTBASE(pInterface);
455 return pThis->fBiosVisible;
456}
457
458
459/** @copydoc PDMIBLOCKBIOS::pfnGetType */
460static DECLCALLBACK(PDMBLOCKTYPE) drvHostBaseBiosGetType(PPDMIBLOCKBIOS pInterface)
461{
462 PDRVHOSTBASE pThis = PDMIBLOCKBIOS_2_DRVHOSTBASE(pInterface);
463 return pThis->enmType;
464}
465
466
467
468/* -=-=-=-=- IMount -=-=-=-=- */
469
470/** @copydoc PDMIMOUNT::pfnMount */
471static DECLCALLBACK(int) drvHostBaseMount(PPDMIMOUNT pInterface, const char *pszFilename, const char *pszCoreDriver)
472{
473 /* We're not mountable. */
474 AssertMsgFailed(("drvHostBaseMount: This shouldn't be called!\n"));
475 return VERR_PDM_MEDIA_MOUNTED;
476}
477
478
479/** @copydoc PDMIMOUNT::pfnUnmount */
480static DECLCALLBACK(int) drvHostBaseUnmount(PPDMIMOUNT pInterface, bool fForce, bool fEject)
481{
482 LogFlow(("drvHostBaseUnmount: returns VERR_NOT_SUPPORTED\n"));
483 return VERR_NOT_SUPPORTED;
484}
485
486
487/** @copydoc PDMIMOUNT::pfnIsMounted */
488static DECLCALLBACK(bool) drvHostBaseIsMounted(PPDMIMOUNT pInterface)
489{
490 PDRVHOSTBASE pThis = PDMIMOUNT_2_DRVHOSTBASE(pInterface);
491 RTCritSectEnter(&pThis->CritSect);
492
493 bool fRc = pThis->fMediaPresent;
494
495 RTCritSectLeave(&pThis->CritSect);
496 return fRc;
497}
498
499
500/** @copydoc PDMIMOUNT::pfnIsLocked */
501static DECLCALLBACK(int) drvHostBaseLock(PPDMIMOUNT pInterface)
502{
503 PDRVHOSTBASE pThis = PDMIMOUNT_2_DRVHOSTBASE(pInterface);
504 RTCritSectEnter(&pThis->CritSect);
505
506 int rc = VINF_SUCCESS;
507 if (!pThis->fLocked)
508 {
509 if (pThis->pfnDoLock)
510 rc = pThis->pfnDoLock(pThis, true);
511 if (RT_SUCCESS(rc))
512 pThis->fLocked = true;
513 }
514 else
515 LogFlow(("%s-%d: drvHostBaseLock: already locked\n", pThis->pDrvIns->pReg->szName, pThis->pDrvIns->iInstance));
516
517 RTCritSectLeave(&pThis->CritSect);
518 LogFlow(("%s-%d: drvHostBaseLock: returns %Rrc\n", pThis->pDrvIns->pReg->szName, pThis->pDrvIns->iInstance, rc));
519 return rc;
520}
521
522
523/** @copydoc PDMIMOUNT::pfnIsLocked */
524static DECLCALLBACK(int) drvHostBaseUnlock(PPDMIMOUNT pInterface)
525{
526 PDRVHOSTBASE pThis = PDMIMOUNT_2_DRVHOSTBASE(pInterface);
527 RTCritSectEnter(&pThis->CritSect);
528
529 int rc = VINF_SUCCESS;
530 if (pThis->fLocked)
531 {
532 if (pThis->pfnDoLock)
533 rc = pThis->pfnDoLock(pThis, false);
534 if (RT_SUCCESS(rc))
535 pThis->fLocked = false;
536 }
537 else
538 LogFlow(("%s-%d: drvHostBaseUnlock: not locked\n", pThis->pDrvIns->pReg->szName, pThis->pDrvIns->iInstance));
539
540 RTCritSectLeave(&pThis->CritSect);
541 LogFlow(("%s-%d: drvHostBaseUnlock: returns %Rrc\n", pThis->pDrvIns->pReg->szName, pThis->pDrvIns->iInstance, rc));
542 return rc;
543}
544
545
546/** @copydoc PDMIMOUNT::pfnIsLocked */
547static DECLCALLBACK(bool) drvHostBaseIsLocked(PPDMIMOUNT pInterface)
548{
549 PDRVHOSTBASE pThis = PDMIMOUNT_2_DRVHOSTBASE(pInterface);
550 RTCritSectEnter(&pThis->CritSect);
551
552 bool fRc = pThis->fLocked;
553
554 RTCritSectLeave(&pThis->CritSect);
555 return fRc;
556}
557
558
559/* -=-=-=-=- IBase -=-=-=-=- */
560
561/**
562 * @interface_method_impl{PDMIBASE,pfnQueryInterface}
563 */
564static DECLCALLBACK(void *) drvHostBaseQueryInterface(PPDMIBASE pInterface, const char *pszIID)
565{
566 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
567 PDRVHOSTBASE pThis = PDMINS_2_DATA(pDrvIns, PDRVHOSTBASE);
568
569 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pDrvIns->IBase);
570 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBLOCK, &pThis->IBlock);
571 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBLOCKBIOS, pThis->fBiosVisible ? &pThis->IBlockBios : NULL);
572 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIMOUNT, &pThis->IMount);
573 return NULL;
574}
575
576
577/* -=-=-=-=- poller thread -=-=-=-=- */
578
579#ifdef RT_OS_DARWIN
580/** The runloop input source name for the disk arbitration events. */
581# define MY_RUN_LOOP_MODE CFSTR("drvHostBaseDA") /** @todo r=bird: Check if this will cause trouble in the same way that the one in the USB code did. */
582
583/**
584 * Gets the BSD Name (/dev/disc[0-9]+) for the service.
585 *
586 * This is done by recursing down the I/O registry until we hit upon an entry
587 * with a BSD Name. Usually we find it two levels down. (Further down under
588 * the IOCDPartitionScheme, the volume (slices) BSD Name is found. We don't
589 * seem to have to go this far fortunately.)
590 *
591 * @return VINF_SUCCESS if found, VERR_FILE_NOT_FOUND otherwise.
592 * @param Entry The current I/O registry entry reference.
593 * @param pszName Where to store the name. 128 bytes.
594 * @param cRecursions Number of recursions. This is used as an precaution
595 * just to limit the depth and avoid blowing the stack
596 * should we hit a bug or something.
597 */
598static int drvHostBaseGetBSDName(io_registry_entry_t Entry, char *pszName, unsigned cRecursions)
599{
600 int rc = VERR_FILE_NOT_FOUND;
601 io_iterator_t Children = 0;
602 kern_return_t krc = IORegistryEntryGetChildIterator(Entry, kIOServicePlane, &Children);
603 if (krc == KERN_SUCCESS)
604 {
605 io_object_t Child;
606 while ( rc == VERR_FILE_NOT_FOUND
607 && (Child = IOIteratorNext(Children)) != 0)
608 {
609 CFStringRef BSDNameStrRef = (CFStringRef)IORegistryEntryCreateCFProperty(Child, CFSTR(kIOBSDNameKey), kCFAllocatorDefault, 0);
610 if (BSDNameStrRef)
611 {
612 if (CFStringGetCString(BSDNameStrRef, pszName, 128, kCFStringEncodingUTF8))
613 rc = VINF_SUCCESS;
614 else
615 AssertFailed();
616 CFRelease(BSDNameStrRef);
617 }
618 if (rc == VERR_FILE_NOT_FOUND && cRecursions < 10)
619 rc = drvHostBaseGetBSDName(Child, pszName, cRecursions + 1);
620 IOObjectRelease(Child);
621 }
622 IOObjectRelease(Children);
623 }
624 return rc;
625}
626
627
628/**
629 * Callback notifying us that the async DADiskClaim()/DADiskUnmount call has completed.
630 *
631 * @param DiskRef The disk that was attempted claimed / unmounted.
632 * @param DissenterRef NULL on success, contains details on failure.
633 * @param pvContext Pointer to the return code variable.
634 */
635static void drvHostBaseDADoneCallback(DADiskRef DiskRef, DADissenterRef DissenterRef, void *pvContext)
636{
637 int *prc = (int *)pvContext;
638 if (!DissenterRef)
639 *prc = 0;
640 else
641 *prc = DADissenterGetStatus(DissenterRef) ? DADissenterGetStatus(DissenterRef) : -1;
642 CFRunLoopStop(CFRunLoopGetCurrent());
643}
644
645
646/**
647 * Obtain exclusive access to the DVD device, umount it if necessary.
648 *
649 * @return VBox status code.
650 * @param pThis The driver instance.
651 * @param DVDService The DVD service object.
652 */
653static int drvHostBaseObtainExclusiveAccess(PDRVHOSTBASE pThis, io_object_t DVDService)
654{
655 PPDMDRVINS pDrvIns = pThis->pDrvIns; NOREF(pDrvIns);
656
657 for (unsigned iTry = 0;; iTry++)
658 {
659 IOReturn irc = (*pThis->ppScsiTaskDI)->ObtainExclusiveAccess(pThis->ppScsiTaskDI);
660 if (irc == kIOReturnSuccess)
661 {
662 /*
663 * This is a bit weird, but if we unmounted the DVD drive we also need to
664 * unlock it afterwards or the guest won't be able to eject it later on.
665 */
666 if (pThis->pDADisk)
667 {
668 uint8_t abCmd[16] =
669 {
670 SCSI_PREVENT_ALLOW_MEDIUM_REMOVAL, 0, 0, 0, false, 0,
671 0,0,0,0,0,0,0,0,0,0
672 };
673 DRVHostBaseScsiCmd(pThis, abCmd, 6, PDMBLOCKTXDIR_NONE, NULL, NULL, NULL, 0, 0);
674 }
675 return VINF_SUCCESS;
676 }
677 if (irc == kIOReturnExclusiveAccess)
678 return VERR_SHARING_VIOLATION; /* already used exclusivly. */
679 if (irc != kIOReturnBusy)
680 return VERR_GENERAL_FAILURE; /* not mounted */
681
682 /*
683 * Attempt to the unmount all volumes of the device.
684 * It seems we can can do this all in one go without having to enumerate the
685 * volumes (sessions) and deal with them one by one. This is very fortuitous
686 * as the disk arbitration API is a bit cumbersome to deal with.
687 */
688 if (iTry > 2)
689 return VERR_DRIVE_LOCKED;
690 char szName[128];
691 int rc = drvHostBaseGetBSDName(DVDService, &szName[0], 0);
692 if (RT_SUCCESS(rc))
693 {
694 pThis->pDASession = DASessionCreate(kCFAllocatorDefault);
695 if (pThis->pDASession)
696 {
697 DASessionScheduleWithRunLoop(pThis->pDASession, CFRunLoopGetCurrent(), MY_RUN_LOOP_MODE);
698 pThis->pDADisk = DADiskCreateFromBSDName(kCFAllocatorDefault, pThis->pDASession, szName);
699 if (pThis->pDADisk)
700 {
701 /*
702 * Try claim the device.
703 */
704 Log(("%s-%d: calling DADiskClaim on '%s'.\n", pDrvIns->pReg->szName, pDrvIns->iInstance, szName));
705 int rcDA = -2;
706 DADiskClaim(pThis->pDADisk, kDADiskClaimOptionDefault, NULL, NULL, drvHostBaseDADoneCallback, &rcDA);
707 SInt32 rc32 = CFRunLoopRunInMode(MY_RUN_LOOP_MODE, 120.0, FALSE);
708 AssertMsg(rc32 == kCFRunLoopRunStopped, ("rc32=%RI32 (%RX32)\n", rc32, rc32));
709 if ( rc32 == kCFRunLoopRunStopped
710 && !rcDA)
711 {
712 /*
713 * Try unmount the device.
714 */
715 Log(("%s-%d: calling DADiskUnmount on '%s'.\n", pDrvIns->pReg->szName, pDrvIns->iInstance, szName));
716 rcDA = -2;
717 DADiskUnmount(pThis->pDADisk, kDADiskUnmountOptionWhole, drvHostBaseDADoneCallback, &rcDA);
718 rc32 = CFRunLoopRunInMode(MY_RUN_LOOP_MODE, 120.0, FALSE);
719 AssertMsg(rc32 == kCFRunLoopRunStopped, ("rc32=%RI32 (%RX32)\n", rc32, rc32));
720 if ( rc32 == kCFRunLoopRunStopped
721 && !rcDA)
722 {
723 iTry = 99;
724 DASessionUnscheduleFromRunLoop(pThis->pDASession, CFRunLoopGetCurrent(), MY_RUN_LOOP_MODE);
725 Log(("%s-%d: unmount succeed - retrying.\n", pDrvIns->pReg->szName, pDrvIns->iInstance));
726 continue;
727 }
728 Log(("%s-%d: umount => rc32=%d & rcDA=%#x\n", pDrvIns->pReg->szName, pDrvIns->iInstance, rc32, rcDA));
729
730 /* failed - cleanup */
731 DADiskUnclaim(pThis->pDADisk);
732 }
733 else
734 Log(("%s-%d: claim => rc32=%d & rcDA=%#x\n", pDrvIns->pReg->szName, pDrvIns->iInstance, rc32, rcDA));
735
736 CFRelease(pThis->pDADisk);
737 pThis->pDADisk = NULL;
738 }
739 else
740 Log(("%s-%d: failed to open disk '%s'!\n", pDrvIns->pReg->szName, pDrvIns->iInstance, szName));
741
742 DASessionUnscheduleFromRunLoop(pThis->pDASession, CFRunLoopGetCurrent(), MY_RUN_LOOP_MODE);
743 CFRelease(pThis->pDASession);
744 pThis->pDASession = NULL;
745 }
746 else
747 Log(("%s-%d: failed to create DA session!\n", pDrvIns->pReg->szName, pDrvIns->iInstance));
748 }
749 RTThreadSleep(10);
750 }
751}
752#endif /* RT_OS_DARWIN */
753
754
755#ifndef RT_OS_SOLARIS
756/**
757 * Wrapper for open / RTFileOpen / IOKit.
758 *
759 * @remark The Darwin code must correspond exactly to the enumeration
760 * done in Main/darwin/iokit.c.
761 */
762static int drvHostBaseOpen(PDRVHOSTBASE pThis, PRTFILE pFileDevice, bool fReadOnly)
763{
764#ifdef RT_OS_DARWIN
765 /* Darwin is kind of special... */
766 Assert(!pFileDevice); NOREF(pFileDevice);
767 Assert(!pThis->cbBlock);
768 Assert(!pThis->MasterPort);
769 Assert(!pThis->ppMMCDI);
770 Assert(!pThis->ppScsiTaskDI);
771
772 /*
773 * Open the master port on the first invocation.
774 */
775 kern_return_t krc = IOMasterPort(MACH_PORT_NULL, &pThis->MasterPort);
776 AssertReturn(krc == KERN_SUCCESS, VERR_GENERAL_FAILURE);
777
778 /*
779 * Create a matching dictionary for searching for DVD services in the IOKit.
780 *
781 * [If I understand this correctly, plain CDROMs doesn't show up as
782 * IODVDServices. Too keep things simple, we will only support DVDs
783 * until somebody complains about it and we get hardware to test it on.
784 * (Unless I'm much mistaken, there aren't any (orignal) intel macs with
785 * plain cdroms.)]
786 */
787 CFMutableDictionaryRef RefMatchingDict = IOServiceMatching("IODVDServices");
788 AssertReturn(RefMatchingDict, NULL);
789
790 /*
791 * do the search and get a collection of keyboards.
792 */
793 io_iterator_t DVDServices = NULL;
794 IOReturn irc = IOServiceGetMatchingServices(pThis->MasterPort, RefMatchingDict, &DVDServices);
795 AssertMsgReturn(irc == kIOReturnSuccess, ("irc=%d\n", irc), NULL);
796 RefMatchingDict = NULL; /* the reference is consumed by IOServiceGetMatchingServices. */
797
798 /*
799 * Enumerate the DVD drives (services).
800 * (This enumeration must be identical to the one performed in DrvHostBase.cpp.)
801 */
802 int rc = VERR_FILE_NOT_FOUND;
803 unsigned i = 0;
804 io_object_t DVDService;
805 while ((DVDService = IOIteratorNext(DVDServices)) != 0)
806 {
807 /*
808 * Get the properties we use to identify the DVD drive.
809 *
810 * While there is a (weird 12 byte) GUID, it isn't persistent
811 * across boots. So, we have to use a combination of the
812 * vendor name and product name properties with an optional
813 * sequence number for identification.
814 */
815 CFMutableDictionaryRef PropsRef = 0;
816 krc = IORegistryEntryCreateCFProperties(DVDService, &PropsRef, kCFAllocatorDefault, kNilOptions);
817 if (krc == KERN_SUCCESS)
818 {
819 /* Get the Device Characteristics dictionary. */
820 CFDictionaryRef DevCharRef = (CFDictionaryRef)CFDictionaryGetValue(PropsRef, CFSTR(kIOPropertyDeviceCharacteristicsKey));
821 if (DevCharRef)
822 {
823 /* The vendor name. */
824 char szVendor[128];
825 char *pszVendor = &szVendor[0];
826 CFTypeRef ValueRef = CFDictionaryGetValue(DevCharRef, CFSTR(kIOPropertyVendorNameKey));
827 if ( ValueRef
828 && CFGetTypeID(ValueRef) == CFStringGetTypeID()
829 && CFStringGetCString((CFStringRef)ValueRef, szVendor, sizeof(szVendor), kCFStringEncodingUTF8))
830 pszVendor = RTStrStrip(szVendor);
831 else
832 *pszVendor = '\0';
833
834 /* The product name. */
835 char szProduct[128];
836 char *pszProduct = &szProduct[0];
837 ValueRef = CFDictionaryGetValue(DevCharRef, CFSTR(kIOPropertyProductNameKey));
838 if ( ValueRef
839 && CFGetTypeID(ValueRef) == CFStringGetTypeID()
840 && CFStringGetCString((CFStringRef)ValueRef, szProduct, sizeof(szProduct), kCFStringEncodingUTF8))
841 pszProduct = RTStrStrip(szProduct);
842 else
843 *pszProduct = '\0';
844
845 /* Construct the two names and compare thwm with the one we're searching for. */
846 char szName1[256 + 32];
847 char szName2[256 + 32];
848 if (*pszVendor || *pszProduct)
849 {
850 if (*pszVendor && *pszProduct)
851 {
852 RTStrPrintf(szName1, sizeof(szName1), "%s %s", pszVendor, pszProduct);
853 RTStrPrintf(szName2, sizeof(szName2), "%s %s (#%u)", pszVendor, pszProduct, i);
854 }
855 else
856 {
857 strcpy(szName1, *pszVendor ? pszVendor : pszProduct);
858 RTStrPrintf(szName2, sizeof(szName2), "%s %s (#%u)", *pszVendor ? pszVendor : pszProduct, i);
859 }
860 }
861 else
862 {
863 RTStrPrintf(szName1, sizeof(szName1), "(#%u)", i);
864 strcpy(szName2, szName1);
865 }
866
867 if ( !strcmp(szName1, pThis->pszDeviceOpen)
868 || !strcmp(szName2, pThis->pszDeviceOpen))
869 {
870 /*
871 * Found it! Now, get the client interface and stuff.
872 * Note that we could also query kIOSCSITaskDeviceUserClientTypeID here if the
873 * MMC client plugin is missing. For now we assume this won't be necessary.
874 */
875 SInt32 Score = 0;
876 IOCFPlugInInterface **ppPlugInInterface = NULL;
877 krc = IOCreatePlugInInterfaceForService(DVDService, kIOMMCDeviceUserClientTypeID, kIOCFPlugInInterfaceID,
878 &ppPlugInInterface, &Score);
879 if (krc == KERN_SUCCESS)
880 {
881 HRESULT hrc = (*ppPlugInInterface)->QueryInterface(ppPlugInInterface,
882 CFUUIDGetUUIDBytes(kIOMMCDeviceInterfaceID),
883 (LPVOID *)&pThis->ppMMCDI);
884 (*ppPlugInInterface)->Release(ppPlugInInterface);
885 ppPlugInInterface = NULL;
886 if (hrc == S_OK)
887 {
888 pThis->ppScsiTaskDI = (*pThis->ppMMCDI)->GetSCSITaskDeviceInterface(pThis->ppMMCDI);
889 if (pThis->ppScsiTaskDI)
890 rc = VINF_SUCCESS;
891 else
892 {
893 LogRel(("GetSCSITaskDeviceInterface failed on '%s'\n", pThis->pszDeviceOpen));
894 rc = VERR_NOT_SUPPORTED;
895 (*pThis->ppMMCDI)->Release(pThis->ppMMCDI);
896 }
897 }
898 else
899 {
900 rc = VERR_GENERAL_FAILURE;//RTErrConvertFromDarwinCOM(krc);
901 pThis->ppMMCDI = NULL;
902 }
903 }
904 else /* Check for kIOSCSITaskDeviceUserClientTypeID? */
905 rc = VERR_GENERAL_FAILURE;//RTErrConvertFromDarwinKern(krc);
906
907 /* Obtain exclusive access to the device so we can send SCSI commands. */
908 if (RT_SUCCESS(rc))
909 rc = drvHostBaseObtainExclusiveAccess(pThis, DVDService);
910
911 /* Cleanup on failure. */
912 if (RT_FAILURE(rc))
913 {
914 if (pThis->ppScsiTaskDI)
915 {
916 (*pThis->ppScsiTaskDI)->Release(pThis->ppScsiTaskDI);
917 pThis->ppScsiTaskDI = NULL;
918 }
919 if (pThis->ppMMCDI)
920 {
921 (*pThis->ppMMCDI)->Release(pThis->ppMMCDI);
922 pThis->ppMMCDI = NULL;
923 }
924 }
925
926 IOObjectRelease(DVDService);
927 break;
928 }
929 }
930 CFRelease(PropsRef);
931 }
932 else
933 AssertMsgFailed(("krc=%#x\n", krc));
934
935 IOObjectRelease(DVDService);
936 i++;
937 }
938
939 IOObjectRelease(DVDServices);
940 return rc;
941
942#elif defined(RT_OS_LINUX)
943 /** @todo we've got RTFILE_O_NON_BLOCK now. Change the code to use RTFileOpen. */
944 int FileDevice = open(pThis->pszDeviceOpen, (pThis->fReadOnlyConfig ? O_RDONLY : O_RDWR) | O_NONBLOCK);
945 if (FileDevice < 0)
946 return RTErrConvertFromErrno(errno);
947 *pFileDevice = FileDevice;
948 return VINF_SUCCESS;
949
950#elif defined(RT_OS_FREEBSD)
951 int rc = VINF_SUCCESS;
952 RTFILE FileDevice;
953
954 rc = RTFileOpen(&FileDevice, pThis->pszDeviceOpen, RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_NONE);
955 if (RT_FAILURE(rc))
956 return rc;
957
958 /*
959 * The current device handle can't passthrough SCSI commands.
960 * We have to get he passthrough device path and open this.
961 */
962 union ccb DeviceCCB;
963 memset(&DeviceCCB, 0, sizeof(DeviceCCB));
964
965 DeviceCCB.ccb_h.func_code = XPT_GDEVLIST;
966 int rcBSD = ioctl(FileDevice, CAMGETPASSTHRU, &DeviceCCB);
967 if (!rcBSD)
968 {
969 char *pszPassthroughDevice = NULL;
970 rc = RTStrAPrintf(&pszPassthroughDevice, "/dev/%s%u",
971 DeviceCCB.cgdl.periph_name, DeviceCCB.cgdl.unit_number);
972 if (rc >= 0)
973 {
974 RTFILE PassthroughDevice;
975
976 rc = RTFileOpen(&PassthroughDevice, pszPassthroughDevice, RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_NONE);
977
978 RTStrFree(pszPassthroughDevice);
979
980 if (RT_SUCCESS(rc))
981 {
982 /* Get needed device parameters. */
983
984 /*
985 * The device path, target id and lun id. Those are
986 * needed for the SCSI passthrough ioctl.
987 */
988 memset(&DeviceCCB, 0, sizeof(DeviceCCB));
989 DeviceCCB.ccb_h.func_code = XPT_GDEVLIST;
990
991 rcBSD = ioctl(PassthroughDevice, CAMGETPASSTHRU, &DeviceCCB);
992 if (!rcBSD)
993 {
994 if (DeviceCCB.cgdl.status != CAM_GDEVLIST_ERROR)
995 {
996 pThis->ScsiBus = DeviceCCB.ccb_h.path_id;
997 pThis->ScsiTargetID = DeviceCCB.ccb_h.target_id;
998 pThis->ScsiLunID = DeviceCCB.ccb_h.target_lun;
999 *pFileDevice = PassthroughDevice;
1000 }
1001 else
1002 {
1003 /* The passthrough device wasn't found. */
1004 rc = VERR_NOT_FOUND;
1005 }
1006 }
1007 else
1008 rc = RTErrConvertFromErrno(errno);
1009
1010 if (RT_FAILURE(rc))
1011 RTFileClose(PassthroughDevice);
1012 }
1013 }
1014 else
1015 rc = VERR_NO_STR_MEMORY;
1016 }
1017 else
1018 rc = RTErrConvertFromErrno(errno);
1019
1020 RTFileClose(FileDevice);
1021 return rc;
1022#else
1023 return RTFileOpen(pFileDevice, pThis->pszDeviceOpen,
1024 (fReadOnly ? RTFILE_O_READ : RTFILE_O_READWRITE) | RTFILE_O_OPEN | RTFILE_O_DENY_NONE);
1025#endif
1026}
1027
1028#else /* RT_OS_SOLARIS */
1029
1030/**
1031 * Solaris wrapper for RTFileOpen.
1032 *
1033 * Solaris has to deal with two filehandles, a block and a raw one. Rather than messing
1034 * with drvHostBaseOpen's function signature & body, having a separate one is better.
1035 *
1036 * @returns VBox status code.
1037 */
1038static int drvHostBaseOpen(PDRVHOSTBASE pThis, PRTFILE pFileBlockDevice, PRTFILE pFileRawDevice, bool fReadOnly)
1039{
1040 unsigned fFlags = (fReadOnly ? RTFILE_O_READ : RTFILE_O_READWRITE)
1041 | RTFILE_O_OPEN | RTFILE_O_DENY_NONE | RTFILE_O_NON_BLOCK;
1042 int rc = RTFileOpen(pFileBlockDevice, pThis->pszDeviceOpen, fFlags);
1043 if (RT_SUCCESS(rc))
1044 {
1045 rc = RTFileOpen(pFileRawDevice, pThis->pszRawDeviceOpen, fFlags);
1046 if (RT_SUCCESS(rc))
1047 return rc;
1048
1049 LogRel(("DVD: failed to open device %s rc=%Rrc\n", pThis->pszRawDeviceOpen, rc));
1050 RTFileClose(*pFileBlockDevice);
1051 }
1052 else
1053 LogRel(("DVD: failed to open device %s rc=%Rrc\n", pThis->pszDeviceOpen, rc));
1054 return rc;
1055}
1056#endif /* RT_OS_SOLARIS */
1057
1058
1059/**
1060 * (Re)opens the device.
1061 *
1062 * This is used to open the device during construction, but it's also used to re-open
1063 * the device when a media is inserted. This re-open will kill off any cached data
1064 * that Linux for some peculiar reason thinks should survive a media change...
1065 *
1066 * @returns VBOX status code.
1067 * @param pThis Instance data.
1068 */
1069static int drvHostBaseReopen(PDRVHOSTBASE pThis)
1070{
1071#ifndef RT_OS_DARWIN /* Only *one* open for darwin. */
1072 LogFlow(("%s-%d: drvHostBaseReopen: '%s'\n", pThis->pDrvIns->pReg->szName, pThis->pDrvIns->iInstance, pThis->pszDeviceOpen));
1073
1074 RTFILE FileDevice;
1075#ifdef RT_OS_SOLARIS
1076 if (pThis->FileRawDevice != NIL_RTFILE)
1077 {
1078 RTFileClose(pThis->FileRawDevice);
1079 pThis->FileRawDevice = NIL_RTFILE;
1080 }
1081 if (pThis->FileDevice != NIL_RTFILE)
1082 {
1083 RTFileClose(pThis->FileDevice);
1084 pThis->FileDevice = NIL_RTFILE;
1085 }
1086 RTFILE FileRawDevice;
1087 int rc = drvHostBaseOpen(pThis, &FileDevice, &FileRawDevice, pThis->fReadOnlyConfig);
1088#else
1089 int rc = drvHostBaseOpen(pThis, &FileDevice, pThis->fReadOnlyConfig);
1090#endif
1091 if (RT_FAILURE(rc))
1092 {
1093 if (!pThis->fReadOnlyConfig)
1094 {
1095 LogFlow(("%s-%d: drvHostBaseReopen: '%s' - retry readonly (%Rrc)\n", pThis->pDrvIns->pReg->szName, pThis->pDrvIns->iInstance, pThis->pszDeviceOpen, rc));
1096#ifdef RT_OS_SOLARIS
1097 rc = drvHostBaseOpen(pThis, &FileDevice, &FileRawDevice, false);
1098#else
1099 rc = drvHostBaseOpen(pThis, &FileDevice, false);
1100#endif
1101 }
1102 if (RT_FAILURE(rc))
1103 {
1104 LogFlow(("%s-%d: failed to open device '%s', rc=%Rrc\n",
1105 pThis->pDrvIns->pReg->szName, pThis->pDrvIns->iInstance, pThis->pszDevice, rc));
1106 return rc;
1107 }
1108 pThis->fReadOnly = true;
1109 }
1110 else
1111 pThis->fReadOnly = pThis->fReadOnlyConfig;
1112
1113#ifdef RT_OS_SOLARIS
1114 if (pThis->FileRawDevice != NIL_RTFILE)
1115 RTFileClose(pThis->FileRawDevice);
1116 pThis->FileRawDevice = FileRawDevice;
1117#endif
1118
1119 if (pThis->FileDevice != NIL_RTFILE)
1120 RTFileClose(pThis->FileDevice);
1121 pThis->FileDevice = FileDevice;
1122#endif /* !RT_OS_DARWIN */
1123 return VINF_SUCCESS;
1124}
1125
1126
1127/**
1128 * Queries the media size.
1129 *
1130 * @returns VBox status code.
1131 * @param pThis Pointer to the instance data.
1132 * @param pcb Where to store the media size in bytes.
1133 */
1134static int drvHostBaseGetMediaSize(PDRVHOSTBASE pThis, uint64_t *pcb)
1135{
1136#if defined(RT_OS_DARWIN) || defined(RT_OS_FREEBSD)
1137 /*
1138 * Try a READ_CAPACITY command...
1139 */
1140 struct
1141 {
1142 uint32_t cBlocks;
1143 uint32_t cbBlock;
1144 } Buf = {0, 0};
1145 uint32_t cbBuf = sizeof(Buf);
1146 uint8_t abCmd[16] =
1147 {
1148 SCSI_READ_CAPACITY, 0, 0, 0, 0, 0, 0,
1149 0,0,0,0,0,0,0,0,0
1150 };
1151 int rc = DRVHostBaseScsiCmd(pThis, abCmd, 6, PDMBLOCKTXDIR_FROM_DEVICE, &Buf, &cbBuf, NULL, 0, 0);
1152 if (RT_SUCCESS(rc))
1153 {
1154 Assert(cbBuf == sizeof(Buf));
1155 Buf.cBlocks = RT_BE2H_U32(Buf.cBlocks);
1156 Buf.cbBlock = RT_BE2H_U32(Buf.cbBlock);
1157 //if (Buf.cbBlock > 2048) /* everyone else is doing this... check if it needed/right.*/
1158 // Buf.cbBlock = 2048;
1159 pThis->cbBlock = Buf.cbBlock;
1160
1161 *pcb = (uint64_t)Buf.cBlocks * Buf.cbBlock;
1162 }
1163 return rc;
1164
1165#elif defined(RT_OS_SOLARIS)
1166 /*
1167 * Sun docs suggests using DKIOCGGEOM instead of DKIOCGMEDIAINFO, but
1168 * Sun themselves use DKIOCGMEDIAINFO for DVDs/CDs, and use DKIOCGGEOM
1169 * for secondary storage devices.
1170 */
1171 struct dk_minfo MediaInfo;
1172 if (ioctl(pThis->FileRawDevice, DKIOCGMEDIAINFO, &MediaInfo) == 0)
1173 {
1174 *pcb = MediaInfo.dki_capacity * (uint64_t)MediaInfo.dki_lbsize;
1175 return VINF_SUCCESS;
1176 }
1177 return RTFileSeek(pThis->FileDevice, 0, RTFILE_SEEK_END, pcb);
1178
1179#elif defined(RT_OS_WINDOWS)
1180 /* use NT api, retry a few times if the media is being verified. */
1181 IO_STATUS_BLOCK IoStatusBlock = {0};
1182 FILE_FS_SIZE_INFORMATION FsSize= {0};
1183 NTSTATUS rcNt = NtQueryVolumeInformationFile((HANDLE)pThis->FileDevice, &IoStatusBlock,
1184 &FsSize, sizeof(FsSize), FileFsSizeInformation);
1185 int cRetries = 5;
1186 while (rcNt == STATUS_VERIFY_REQUIRED && cRetries-- > 0)
1187 {
1188 RTThreadSleep(10);
1189 rcNt = NtQueryVolumeInformationFile((HANDLE)pThis->FileDevice, &IoStatusBlock,
1190 &FsSize, sizeof(FsSize), FileFsSizeInformation);
1191 }
1192 if (rcNt >= 0)
1193 {
1194 *pcb = FsSize.TotalAllocationUnits.QuadPart * FsSize.BytesPerSector;
1195 return VINF_SUCCESS;
1196 }
1197
1198 /* convert nt status code to VBox status code. */
1199 /** @todo Make conversion function!. */
1200 int rc = VERR_GENERAL_FAILURE;
1201 switch (rcNt)
1202 {
1203 case STATUS_NO_MEDIA_IN_DEVICE: rc = VERR_MEDIA_NOT_PRESENT; break;
1204 case STATUS_VERIFY_REQUIRED: rc = VERR_TRY_AGAIN; break;
1205 }
1206 LogFlow(("drvHostBaseGetMediaSize: NtQueryVolumeInformationFile -> %#lx\n", rcNt, rc));
1207 return rc;
1208#else
1209 return RTFileSeek(pThis->FileDevice, 0, RTFILE_SEEK_END, pcb);
1210#endif
1211}
1212
1213
1214#if defined(RT_OS_DARWIN) || defined(RT_OS_FREEBSD)
1215/**
1216 * Execute a SCSI command.
1217 *
1218 * @param pThis The instance data.
1219 * @param pbCmd Pointer to the SCSI command.
1220 * @param cbCmd The size of the SCSI command.
1221 * @param enmTxDir The transfer direction.
1222 * @param pvBuf The buffer. Can be NULL if enmTxDir is PDMBLOCKTXDIR_NONE.
1223 * @param pcbBuf Where to get the buffer size from and put the actual transfer size. Can be NULL.
1224 * @param pbSense Where to put the sense data. Can be NULL.
1225 * @param cbSense Size of the sense data buffer.
1226 * @param cTimeoutMillies The timeout. 0 mean the default timeout.
1227 *
1228 * @returns VINF_SUCCESS on success (no sense code).
1229 * @returns VERR_UNRESOLVED_ERROR if sense code is present.
1230 * @returns Some other VBox status code on failures without sense code.
1231 *
1232 * @todo Fix VERR_UNRESOLVED_ERROR abuse.
1233 */
1234DECLCALLBACK(int) DRVHostBaseScsiCmd(PDRVHOSTBASE pThis, const uint8_t *pbCmd, size_t cbCmd, PDMBLOCKTXDIR enmTxDir,
1235 void *pvBuf, uint32_t *pcbBuf, uint8_t *pbSense, size_t cbSense, uint32_t cTimeoutMillies)
1236{
1237 /*
1238 * Minimal input validation.
1239 */
1240 Assert(enmTxDir == PDMBLOCKTXDIR_NONE || enmTxDir == PDMBLOCKTXDIR_FROM_DEVICE || enmTxDir == PDMBLOCKTXDIR_TO_DEVICE);
1241 Assert(!pvBuf || pcbBuf);
1242 Assert(pvBuf || enmTxDir == PDMBLOCKTXDIR_NONE);
1243 Assert(pbSense || !cbSense);
1244 AssertPtr(pbCmd);
1245 Assert(cbCmd <= 16 && cbCmd >= 1);
1246 const uint32_t cbBuf = pcbBuf ? *pcbBuf : 0;
1247 if (pcbBuf)
1248 *pcbBuf = 0;
1249
1250# ifdef RT_OS_DARWIN
1251 Assert(pThis->ppScsiTaskDI);
1252
1253 int rc = VERR_GENERAL_FAILURE;
1254 SCSITaskInterface **ppScsiTaskI = (*pThis->ppScsiTaskDI)->CreateSCSITask(pThis->ppScsiTaskDI);
1255 if (!ppScsiTaskI)
1256 return VERR_NO_MEMORY;
1257 do
1258 {
1259 /* Setup the scsi command. */
1260 SCSICommandDescriptorBlock cdb = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 };
1261 memcpy(&cdb[0], pbCmd, cbCmd);
1262 IOReturn irc = (*ppScsiTaskI)->SetCommandDescriptorBlock(ppScsiTaskI, cdb, cbCmd);
1263 AssertBreak(irc == kIOReturnSuccess);
1264
1265 /* Setup the buffer. */
1266 if (enmTxDir == PDMBLOCKTXDIR_NONE)
1267 irc = (*ppScsiTaskI)->SetScatterGatherEntries(ppScsiTaskI, NULL, 0, 0, kSCSIDataTransfer_NoDataTransfer);
1268 else
1269 {
1270 IOVirtualRange Range = { (IOVirtualAddress)pvBuf, cbBuf };
1271 irc = (*ppScsiTaskI)->SetScatterGatherEntries(ppScsiTaskI, &Range, 1, cbBuf,
1272 enmTxDir == PDMBLOCKTXDIR_FROM_DEVICE
1273 ? kSCSIDataTransfer_FromTargetToInitiator
1274 : kSCSIDataTransfer_FromInitiatorToTarget);
1275 }
1276 AssertBreak(irc == kIOReturnSuccess);
1277
1278 /* Set the timeout. */
1279 irc = (*ppScsiTaskI)->SetTimeoutDuration(ppScsiTaskI, cTimeoutMillies ? cTimeoutMillies : 30000 /*ms*/);
1280 AssertBreak(irc == kIOReturnSuccess);
1281
1282 /* Execute the command and get the response. */
1283 SCSI_Sense_Data SenseData = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 };
1284 SCSIServiceResponse ServiceResponse = kSCSIServiceResponse_Request_In_Process;
1285 SCSITaskStatus TaskStatus = kSCSITaskStatus_GOOD;
1286 UInt64 cbReturned = 0;
1287 irc = (*ppScsiTaskI)->ExecuteTaskSync(ppScsiTaskI, &SenseData, &TaskStatus, &cbReturned);
1288 AssertBreak(irc == kIOReturnSuccess);
1289 if (pcbBuf)
1290 *pcbBuf = (int32_t)cbReturned;
1291
1292 irc = (*ppScsiTaskI)->GetSCSIServiceResponse(ppScsiTaskI, &ServiceResponse);
1293 AssertBreak(irc == kIOReturnSuccess);
1294 AssertBreak(ServiceResponse == kSCSIServiceResponse_TASK_COMPLETE);
1295
1296 if (TaskStatus == kSCSITaskStatus_GOOD)
1297 rc = VINF_SUCCESS;
1298 else if ( TaskStatus == kSCSITaskStatus_CHECK_CONDITION
1299 && pbSense)
1300 {
1301 memset(pbSense, 0, cbSense); /* lazy */
1302 memcpy(pbSense, &SenseData, RT_MIN(sizeof(SenseData), cbSense));
1303 rc = VERR_UNRESOLVED_ERROR;
1304 }
1305 /** @todo convert sense codes when caller doesn't wish to do this himself. */
1306 /*else if ( TaskStatus == kSCSITaskStatus_CHECK_CONDITION
1307 && SenseData.ADDITIONAL_SENSE_CODE == 0x3A)
1308 rc = VERR_MEDIA_NOT_PRESENT; */
1309 else
1310 {
1311 rc = enmTxDir == PDMBLOCKTXDIR_NONE
1312 ? VERR_DEV_IO_ERROR
1313 : enmTxDir == PDMBLOCKTXDIR_FROM_DEVICE
1314 ? VERR_READ_ERROR
1315 : VERR_WRITE_ERROR;
1316 if (pThis->cLogRelErrors++ < 10)
1317 LogRel(("DVD scsi error: cmd={%.*Rhxs} TaskStatus=%#x key=%#x ASC=%#x ASCQ=%#x (%Rrc)\n",
1318 cbCmd, pbCmd, TaskStatus, SenseData.SENSE_KEY, SenseData.ADDITIONAL_SENSE_CODE,
1319 SenseData.ADDITIONAL_SENSE_CODE_QUALIFIER, rc));
1320 }
1321 } while (0);
1322
1323 (*ppScsiTaskI)->Release(ppScsiTaskI);
1324
1325# elif defined(RT_OS_FREEBSD)
1326 int rc = VINF_SUCCESS;
1327 int rcBSD = 0;
1328 union ccb DeviceCCB;
1329 union ccb *pDeviceCCB = &DeviceCCB;
1330 u_int32_t fFlags;
1331
1332 memset(pDeviceCCB, 0, sizeof(DeviceCCB));
1333 pDeviceCCB->ccb_h.path_id = pThis->ScsiBus;
1334 pDeviceCCB->ccb_h.target_id = pThis->ScsiTargetID;
1335 pDeviceCCB->ccb_h.target_lun = pThis->ScsiLunID;
1336
1337 /* The SCSI INQUIRY command can't be passed through directly. */
1338 if (pbCmd[0] == SCSI_INQUIRY)
1339 {
1340 pDeviceCCB->ccb_h.func_code = XPT_GDEV_TYPE;
1341
1342 rcBSD = ioctl(pThis->FileDevice, CAMIOCOMMAND, pDeviceCCB);
1343 if (!rcBSD)
1344 {
1345 uint32_t cbCopy = cbBuf < sizeof(struct scsi_inquiry_data)
1346 ? cbBuf
1347 : sizeof(struct scsi_inquiry_data);;
1348 memcpy(pvBuf, &pDeviceCCB->cgd.inq_data, cbCopy);
1349 memset(pbSense, 0, cbSense);
1350
1351 if (pcbBuf)
1352 *pcbBuf = cbCopy;
1353 }
1354 else
1355 rc = RTErrConvertFromErrno(errno);
1356 }
1357 else
1358 {
1359 /* Copy the CDB. */
1360 memcpy(&pDeviceCCB->csio.cdb_io.cdb_bytes, pbCmd, cbCmd);
1361
1362 /* Set direction. */
1363 if (enmTxDir == PDMBLOCKTXDIR_NONE)
1364 fFlags = CAM_DIR_NONE;
1365 else if (enmTxDir == PDMBLOCKTXDIR_FROM_DEVICE)
1366 fFlags = CAM_DIR_IN;
1367 else
1368 fFlags = CAM_DIR_OUT;
1369
1370 fFlags |= CAM_DEV_QFRZDIS;
1371
1372 cam_fill_csio(&pDeviceCCB->csio, 1, NULL, fFlags, MSG_SIMPLE_Q_TAG,
1373 (u_int8_t *)pvBuf, cbBuf, cbSense, cbCmd,
1374 cTimeoutMillies ? cTimeoutMillies : 30000/* timeout */);
1375
1376 /* Send command */
1377 rcBSD = ioctl(pThis->FileDevice, CAMIOCOMMAND, pDeviceCCB);
1378 if (!rcBSD)
1379 {
1380 switch (pDeviceCCB->ccb_h.status & CAM_STATUS_MASK)
1381 {
1382 case CAM_REQ_CMP:
1383 rc = VINF_SUCCESS;
1384 break;
1385 case CAM_SEL_TIMEOUT:
1386 rc = VERR_DEV_IO_ERROR;
1387 break;
1388 case CAM_CMD_TIMEOUT:
1389 rc = VERR_TIMEOUT;
1390 break;
1391 default:
1392 rc = VERR_DEV_IO_ERROR;
1393 }
1394
1395 if (pcbBuf)
1396 *pcbBuf = cbBuf - pDeviceCCB->csio.resid;
1397
1398 if (pbSense)
1399 memcpy(pbSense, &pDeviceCCB->csio.sense_data,
1400 cbSense - pDeviceCCB->csio.sense_resid);
1401 }
1402 else
1403 rc = RTErrConvertFromErrno(errno);
1404 }
1405# endif
1406
1407 return rc;
1408}
1409#endif
1410
1411
1412/**
1413 * Media present.
1414 * Query the size and notify the above driver / device.
1415 *
1416 * @param pThis The instance data.
1417 */
1418int DRVHostBaseMediaPresent(PDRVHOSTBASE pThis)
1419{
1420 /*
1421 * Open the drive.
1422 */
1423 int rc = drvHostBaseReopen(pThis);
1424 if (RT_FAILURE(rc))
1425 return rc;
1426
1427 /*
1428 * Determine the size.
1429 */
1430 uint64_t cb;
1431 rc = pThis->pfnGetMediaSize(pThis, &cb);
1432 if (RT_FAILURE(rc))
1433 {
1434 LogFlow(("%s-%d: failed to figure media size of %s, rc=%Rrc\n",
1435 pThis->pDrvIns->pReg->szName, pThis->pDrvIns->iInstance, pThis->pszDevice, rc));
1436 return rc;
1437 }
1438
1439 /*
1440 * Update the data and inform the unit.
1441 */
1442 pThis->cbSize = cb;
1443 pThis->fMediaPresent = true;
1444 if (pThis->pDrvMountNotify)
1445 pThis->pDrvMountNotify->pfnMountNotify(pThis->pDrvMountNotify);
1446 LogFlow(("%s-%d: drvHostBaseMediaPresent: cbSize=%lld (%#llx)\n",
1447 pThis->pDrvIns->pReg->szName, pThis->pDrvIns->iInstance, pThis->cbSize, pThis->cbSize));
1448 return VINF_SUCCESS;
1449}
1450
1451
1452/**
1453 * Media no longer present.
1454 * @param pThis The instance data.
1455 */
1456void DRVHostBaseMediaNotPresent(PDRVHOSTBASE pThis)
1457{
1458 pThis->fMediaPresent = false;
1459 pThis->fLocked = false;
1460 pThis->PCHSGeometry.cCylinders = 0;
1461 pThis->PCHSGeometry.cHeads = 0;
1462 pThis->PCHSGeometry.cSectors = 0;
1463 pThis->LCHSGeometry.cCylinders = 0;
1464 pThis->LCHSGeometry.cHeads = 0;
1465 pThis->LCHSGeometry.cSectors = 0;
1466 if (pThis->pDrvMountNotify)
1467 pThis->pDrvMountNotify->pfnUnmountNotify(pThis->pDrvMountNotify);
1468}
1469
1470
1471#ifdef RT_OS_WINDOWS
1472
1473/**
1474 * Window procedure for the invisible window used to catch the WM_DEVICECHANGE broadcasts.
1475 */
1476static LRESULT CALLBACK DeviceChangeWindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
1477{
1478 Log2(("DeviceChangeWindowProc: hwnd=%08x uMsg=%08x\n", hwnd, uMsg));
1479 if (uMsg == WM_DESTROY)
1480 {
1481 PDRVHOSTBASE pThis = (PDRVHOSTBASE)GetWindowLong(hwnd, GWLP_USERDATA);
1482 if (pThis)
1483 ASMAtomicXchgSize(&pThis->hwndDeviceChange, NULL);
1484 PostQuitMessage(0);
1485 }
1486
1487 if (uMsg != WM_DEVICECHANGE)
1488 return DefWindowProc(hwnd, uMsg, wParam, lParam);
1489
1490 PDEV_BROADCAST_HDR lpdb = (PDEV_BROADCAST_HDR)lParam;
1491 PDRVHOSTBASE pThis = (PDRVHOSTBASE)GetWindowLongPtr(hwnd, GWLP_USERDATA);
1492 Assert(pThis);
1493 if (pThis == NULL)
1494 return 0;
1495
1496 switch (wParam)
1497 {
1498 case DBT_DEVICEARRIVAL:
1499 case DBT_DEVICEREMOVECOMPLETE:
1500 // Check whether a CD or DVD was inserted into or removed from a drive.
1501 if (lpdb->dbch_devicetype == DBT_DEVTYP_VOLUME)
1502 {
1503 PDEV_BROADCAST_VOLUME lpdbv = (PDEV_BROADCAST_VOLUME)lpdb;
1504 if ( (lpdbv->dbcv_flags & DBTF_MEDIA)
1505 && (pThis->fUnitMask & lpdbv->dbcv_unitmask))
1506 {
1507 RTCritSectEnter(&pThis->CritSect);
1508 if (wParam == DBT_DEVICEARRIVAL)
1509 {
1510 int cRetries = 10;
1511 int rc = DRVHostBaseMediaPresent(pThis);
1512 while (RT_FAILURE(rc) && cRetries-- > 0)
1513 {
1514 RTThreadSleep(50);
1515 rc = DRVHostBaseMediaPresent(pThis);
1516 }
1517 }
1518 else
1519 DRVHostBaseMediaNotPresent(pThis);
1520 RTCritSectLeave(&pThis->CritSect);
1521 }
1522 }
1523 break;
1524 }
1525 return TRUE;
1526}
1527
1528#endif /* RT_OS_WINDOWS */
1529
1530
1531/**
1532 * This thread will periodically poll the device for media presence.
1533 *
1534 * @returns Ignored.
1535 * @param ThreadSelf Handle of this thread. Ignored.
1536 * @param pvUser Pointer to the driver instance structure.
1537 */
1538static DECLCALLBACK(int) drvHostBaseMediaThread(RTTHREAD ThreadSelf, void *pvUser)
1539{
1540 PDRVHOSTBASE pThis = (PDRVHOSTBASE)pvUser;
1541 LogFlow(("%s-%d: drvHostBaseMediaThread: ThreadSelf=%p pvUser=%p\n",
1542 pThis->pDrvIns->pReg->szName, pThis->pDrvIns->iInstance, ThreadSelf, pvUser));
1543#ifdef RT_OS_WINDOWS
1544 static WNDCLASS s_classDeviceChange = {0};
1545 static ATOM s_hAtomDeviceChange = 0;
1546
1547 /*
1548 * Register custom window class.
1549 */
1550 if (s_hAtomDeviceChange == 0)
1551 {
1552 memset(&s_classDeviceChange, 0, sizeof(s_classDeviceChange));
1553 s_classDeviceChange.lpfnWndProc = DeviceChangeWindowProc;
1554 s_classDeviceChange.lpszClassName = "VBOX_DeviceChangeClass";
1555 s_classDeviceChange.hInstance = GetModuleHandle("VBOXDD.DLL");
1556 Assert(s_classDeviceChange.hInstance);
1557 s_hAtomDeviceChange = RegisterClassA(&s_classDeviceChange);
1558 Assert(s_hAtomDeviceChange);
1559 }
1560
1561 /*
1562 * Create Window w/ the pThis as user data.
1563 */
1564 HWND hwnd = CreateWindow((LPCTSTR)s_hAtomDeviceChange, "", WS_POPUP, 0, 0, 0, 0, 0, 0, s_classDeviceChange.hInstance, 0);
1565 AssertMsg(hwnd, ("CreateWindow failed with %d\n", GetLastError()));
1566 SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR)pThis);
1567
1568 /*
1569 * Signal the waiting EMT thread that everything went fine.
1570 */
1571 ASMAtomicXchgSize(&pThis->hwndDeviceChange, hwnd);
1572 RTThreadUserSignal(ThreadSelf);
1573 if (!hwnd)
1574 {
1575 LogFlow(("%s-%d: drvHostBaseMediaThread: returns VERR_GENERAL_FAILURE\n", pThis->pDrvIns->pReg->szName, pThis->pDrvIns->iInstance));
1576 return VERR_GENERAL_FAILURE;
1577 }
1578 LogFlow(("%s-%d: drvHostBaseMediaThread: Created hwndDeviceChange=%p\n", pThis->pDrvIns->pReg->szName, pThis->pDrvIns->iInstance, hwnd));
1579
1580 /*
1581 * Message pump.
1582 */
1583 MSG Msg;
1584 BOOL fRet;
1585 while ((fRet = GetMessage(&Msg, NULL, 0, 0)) != FALSE)
1586 {
1587 if (fRet != -1)
1588 {
1589 TranslateMessage(&Msg);
1590 DispatchMessage(&Msg);
1591 }
1592 //else: handle the error and possibly exit
1593 }
1594 Assert(!pThis->hwndDeviceChange);
1595
1596#else /* !RT_OS_WINDOWS */
1597 bool fFirst = true;
1598 int cRetries = 10;
1599 while (!pThis->fShutdownPoller)
1600 {
1601 /*
1602 * Perform the polling (unless we've run out of 50ms retries).
1603 */
1604 if ( pThis->pfnPoll
1605 && cRetries-- > 0)
1606 {
1607
1608 int rc = pThis->pfnPoll(pThis);
1609 if (RT_FAILURE(rc))
1610 {
1611 RTSemEventWait(pThis->EventPoller, 50);
1612 continue;
1613 }
1614 }
1615
1616 /*
1617 * Signal EMT after the first go.
1618 */
1619 if (fFirst)
1620 {
1621 RTThreadUserSignal(ThreadSelf);
1622 fFirst = false;
1623 }
1624
1625 /*
1626 * Sleep.
1627 */
1628 int rc = RTSemEventWait(pThis->EventPoller, pThis->cMilliesPoller);
1629 if ( RT_FAILURE(rc)
1630 && rc != VERR_TIMEOUT)
1631 {
1632 AssertMsgFailed(("rc=%Rrc\n", rc));
1633 pThis->ThreadPoller = NIL_RTTHREAD;
1634 LogFlow(("drvHostBaseMediaThread: returns %Rrc\n", rc));
1635 return rc;
1636 }
1637 cRetries = 10;
1638 }
1639
1640#endif /* !RT_OS_WINDOWS */
1641
1642 /* (Don't clear the thread handle here, the destructor thread is using it to wait.) */
1643 LogFlow(("%s-%d: drvHostBaseMediaThread: returns VINF_SUCCESS\n", pThis->pDrvIns->pReg->szName, pThis->pDrvIns->iInstance));
1644 return VINF_SUCCESS;
1645}
1646
1647/* -=-=-=-=- driver interface -=-=-=-=- */
1648
1649
1650/**
1651 * Done state load operation.
1652 *
1653 * @returns VBox load code.
1654 * @param pDrvIns Driver instance of the driver which registered the data unit.
1655 * @param pSSM SSM operation handle.
1656 */
1657static DECLCALLBACK(int) drvHostBaseLoadDone(PPDMDRVINS pDrvIns, PSSMHANDLE pSSM)
1658{
1659 PDRVHOSTBASE pThis = PDMINS_2_DATA(pDrvIns, PDRVHOSTBASE);
1660 LogFlow(("%s-%d: drvHostBaseMediaThread:\n", pThis->pDrvIns->pReg->szName, pThis->pDrvIns->iInstance));
1661 RTCritSectEnter(&pThis->CritSect);
1662
1663 /*
1664 * Tell the device/driver above us that the media status is uncertain.
1665 */
1666 if (pThis->pDrvMountNotify)
1667 {
1668 pThis->pDrvMountNotify->pfnUnmountNotify(pThis->pDrvMountNotify);
1669 if (pThis->fMediaPresent)
1670 pThis->pDrvMountNotify->pfnMountNotify(pThis->pDrvMountNotify);
1671 }
1672
1673 RTCritSectLeave(&pThis->CritSect);
1674 return VINF_SUCCESS;
1675}
1676
1677
1678/** @copydoc FNPDMDRVDESTRUCT */
1679DECLCALLBACK(void) DRVHostBaseDestruct(PPDMDRVINS pDrvIns)
1680{
1681 PDRVHOSTBASE pThis = PDMINS_2_DATA(pDrvIns, PDRVHOSTBASE);
1682 LogFlow(("%s-%d: drvHostBaseDestruct: iInstance=%d\n", pDrvIns->pReg->szName, pDrvIns->iInstance, pDrvIns->iInstance));
1683
1684 /*
1685 * Terminate the thread.
1686 */
1687 if (pThis->ThreadPoller != NIL_RTTHREAD)
1688 {
1689 pThis->fShutdownPoller = true;
1690 int rc;
1691 int cTimes = 50;
1692 do
1693 {
1694#ifdef RT_OS_WINDOWS
1695 if (pThis->hwndDeviceChange)
1696 PostMessage(pThis->hwndDeviceChange, WM_CLOSE, 0, 0); /* default win proc will destroy the window */
1697#else
1698 RTSemEventSignal(pThis->EventPoller);
1699#endif
1700 rc = RTThreadWait(pThis->ThreadPoller, 100, NULL);
1701 } while (cTimes-- > 0 && rc == VERR_TIMEOUT);
1702
1703 if (!rc)
1704 pThis->ThreadPoller = NIL_RTTHREAD;
1705 }
1706
1707 /*
1708 * Unlock the drive if we've locked it or we're in passthru mode.
1709 */
1710#ifdef RT_OS_DARWIN
1711 if ( ( pThis->fLocked
1712 || pThis->IBlock.pfnSendCmd)
1713 && pThis->ppScsiTaskDI
1714#else /** @todo Check if the other guys can mix pfnDoLock with scsi passthru.
1715 * (We're currently not unlocking the device after use. See todo in DevATA.cpp.) */
1716 if ( pThis->fLocked
1717 && pThis->FileDevice != NIL_RTFILE
1718#endif
1719 && pThis->pfnDoLock)
1720 {
1721 int rc = pThis->pfnDoLock(pThis, false);
1722 if (RT_SUCCESS(rc))
1723 pThis->fLocked = false;
1724 }
1725
1726 /*
1727 * Cleanup the other resources.
1728 */
1729#ifdef RT_OS_WINDOWS
1730 if (pThis->hwndDeviceChange)
1731 {
1732 if (SetWindowLongPtr(pThis->hwndDeviceChange, GWLP_USERDATA, 0) == (LONG_PTR)pThis)
1733 PostMessage(pThis->hwndDeviceChange, WM_CLOSE, 0, 0); /* default win proc will destroy the window */
1734 pThis->hwndDeviceChange = NULL;
1735 }
1736#else
1737 if (pThis->EventPoller != NULL)
1738 {
1739 RTSemEventDestroy(pThis->EventPoller);
1740 pThis->EventPoller = NULL;
1741 }
1742#endif
1743
1744#ifdef RT_OS_DARWIN
1745 /*
1746 * The unclaiming doesn't seem to mean much, the DVD is actually
1747 * remounted when we release exclusive access. I'm not quite sure
1748 * if I should put the unclaim first or not...
1749 *
1750 * Anyway, that it's automatically remounted very good news for us,
1751 * because that means we don't have to mess with that ourselves. Of
1752 * course there is the unlikely scenario that we've succeeded in claiming
1753 * and umount the DVD but somehow failed to gain exclusive scsi access...
1754 */
1755 if (pThis->ppScsiTaskDI)
1756 {
1757 LogFlow(("%s-%d: releasing exclusive scsi access!\n", pDrvIns->pReg->szName, pDrvIns->iInstance));
1758 (*pThis->ppScsiTaskDI)->ReleaseExclusiveAccess(pThis->ppScsiTaskDI);
1759 (*pThis->ppScsiTaskDI)->Release(pThis->ppScsiTaskDI);
1760 pThis->ppScsiTaskDI = NULL;
1761 }
1762 if (pThis->pDADisk)
1763 {
1764 LogFlow(("%s-%d: unclaiming the disk!\n", pDrvIns->pReg->szName, pDrvIns->iInstance));
1765 DADiskUnclaim(pThis->pDADisk);
1766 CFRelease(pThis->pDADisk);
1767 pThis->pDADisk = NULL;
1768 }
1769 if (pThis->ppMMCDI)
1770 {
1771 LogFlow(("%s-%d: releasing the MMC object!\n", pDrvIns->pReg->szName, pDrvIns->iInstance));
1772 (*pThis->ppMMCDI)->Release(pThis->ppMMCDI);
1773 pThis->ppMMCDI = NULL;
1774 }
1775 if (pThis->MasterPort)
1776 {
1777 mach_port_deallocate(mach_task_self(), pThis->MasterPort);
1778 pThis->MasterPort = NULL;
1779 }
1780 if (pThis->pDASession)
1781 {
1782 LogFlow(("%s-%d: releasing the DA session!\n", pDrvIns->pReg->szName, pDrvIns->iInstance));
1783 CFRelease(pThis->pDASession);
1784 pThis->pDASession = NULL;
1785 }
1786#else
1787 if (pThis->FileDevice != NIL_RTFILE)
1788 {
1789 int rc = RTFileClose(pThis->FileDevice);
1790 AssertRC(rc);
1791 pThis->FileDevice = NIL_RTFILE;
1792 }
1793#endif
1794
1795#ifdef RT_OS_SOLARIS
1796 if (pThis->FileRawDevice != NIL_RTFILE)
1797 {
1798 int rc = RTFileClose(pThis->FileRawDevice);
1799 AssertRC(rc);
1800 pThis->FileRawDevice = NIL_RTFILE;
1801 }
1802
1803 if (pThis->pszRawDeviceOpen)
1804 {
1805 RTStrFree(pThis->pszRawDeviceOpen);
1806 pThis->pszRawDeviceOpen = NULL;
1807 }
1808#endif
1809
1810 if (pThis->pszDevice)
1811 {
1812 MMR3HeapFree(pThis->pszDevice);
1813 pThis->pszDevice = NULL;
1814 }
1815
1816 if (pThis->pszDeviceOpen)
1817 {
1818 RTStrFree(pThis->pszDeviceOpen);
1819 pThis->pszDeviceOpen = NULL;
1820 }
1821
1822 /* Forget about the notifications. */
1823 pThis->pDrvMountNotify = NULL;
1824
1825 /* Leave the instance operational if this is just a cleanup of the state
1826 * after an attach error happened. So don't destroy the critsect then. */
1827 if (!pThis->fKeepInstance && RTCritSectIsInitialized(&pThis->CritSect))
1828 RTCritSectDelete(&pThis->CritSect);
1829 LogFlow(("%s-%d: drvHostBaseDestruct completed\n", pDrvIns->pReg->szName, pDrvIns->iInstance));
1830}
1831
1832
1833/**
1834 * Initializes the instance data (init part 1).
1835 *
1836 * The driver which derives from this base driver will override function pointers after
1837 * calling this method, and complete the construction by calling DRVHostBaseInitFinish().
1838 *
1839 * On failure call DRVHostBaseDestruct().
1840 *
1841 * @returns VBox status code.
1842 * @param pDrvIns Driver instance.
1843 * @param pCfg Configuration handle.
1844 * @param enmType Device type.
1845 */
1846int DRVHostBaseInitData(PPDMDRVINS pDrvIns, PCFGMNODE pCfg, PDMBLOCKTYPE enmType)
1847{
1848 PDRVHOSTBASE pThis = PDMINS_2_DATA(pDrvIns, PDRVHOSTBASE);
1849 LogFlow(("%s-%d: DRVHostBaseInitData: iInstance=%d\n", pDrvIns->pReg->szName, pDrvIns->iInstance, pDrvIns->iInstance));
1850
1851 /*
1852 * Initialize most of the data members.
1853 */
1854 pThis->pDrvIns = pDrvIns;
1855 pThis->fKeepInstance = false;
1856 pThis->ThreadPoller = NIL_RTTHREAD;
1857#ifdef RT_OS_DARWIN
1858 pThis->MasterPort = NULL;
1859 pThis->ppMMCDI = NULL;
1860 pThis->ppScsiTaskDI = NULL;
1861 pThis->cbBlock = 0;
1862 pThis->pDADisk = NULL;
1863 pThis->pDASession = NULL;
1864#else
1865 pThis->FileDevice = NIL_RTFILE;
1866#endif
1867#ifdef RT_OS_SOLARIS
1868 pThis->FileRawDevice = NIL_RTFILE;
1869#endif
1870 pThis->enmType = enmType;
1871 //pThis->cErrors = 0;
1872
1873 pThis->pfnGetMediaSize = drvHostBaseGetMediaSize;
1874
1875 /* IBase. */
1876 pDrvIns->IBase.pfnQueryInterface = drvHostBaseQueryInterface;
1877
1878 /* IBlock. */
1879 pThis->IBlock.pfnRead = drvHostBaseRead;
1880 pThis->IBlock.pfnWrite = drvHostBaseWrite;
1881 pThis->IBlock.pfnFlush = drvHostBaseFlush;
1882 pThis->IBlock.pfnIsReadOnly = drvHostBaseIsReadOnly;
1883 pThis->IBlock.pfnGetSize = drvHostBaseGetSize;
1884 pThis->IBlock.pfnGetType = drvHostBaseGetType;
1885 pThis->IBlock.pfnGetUuid = drvHostBaseGetUuid;
1886
1887 /* IBlockBios. */
1888 pThis->IBlockBios.pfnGetPCHSGeometry = drvHostBaseGetPCHSGeometry;
1889 pThis->IBlockBios.pfnSetPCHSGeometry = drvHostBaseSetPCHSGeometry;
1890 pThis->IBlockBios.pfnGetLCHSGeometry = drvHostBaseGetLCHSGeometry;
1891 pThis->IBlockBios.pfnSetLCHSGeometry = drvHostBaseSetLCHSGeometry;
1892 pThis->IBlockBios.pfnIsVisible = drvHostBaseIsVisible;
1893 pThis->IBlockBios.pfnGetType = drvHostBaseBiosGetType;
1894
1895 /* IMount. */
1896 pThis->IMount.pfnMount = drvHostBaseMount;
1897 pThis->IMount.pfnUnmount = drvHostBaseUnmount;
1898 pThis->IMount.pfnIsMounted = drvHostBaseIsMounted;
1899 pThis->IMount.pfnLock = drvHostBaseLock;
1900 pThis->IMount.pfnUnlock = drvHostBaseUnlock;
1901 pThis->IMount.pfnIsLocked = drvHostBaseIsLocked;
1902
1903 /*
1904 * Get the IBlockPort & IMountNotify interfaces of the above driver/device.
1905 */
1906 pThis->pDrvBlockPort = PDMIBASE_QUERY_INTERFACE(pDrvIns->pUpBase, PDMIBLOCKPORT);
1907 if (!pThis->pDrvBlockPort)
1908 {
1909 AssertMsgFailed(("Configuration error: No block port interface above!\n"));
1910 return VERR_PDM_MISSING_INTERFACE_ABOVE;
1911 }
1912 pThis->pDrvMountNotify = PDMIBASE_QUERY_INTERFACE(pDrvIns->pUpBase, PDMIMOUNTNOTIFY);
1913
1914 /*
1915 * Query configuration.
1916 */
1917 /* Device */
1918 int rc = CFGMR3QueryStringAlloc(pCfg, "Path", &pThis->pszDevice);
1919 if (RT_FAILURE(rc))
1920 {
1921 AssertMsgFailed(("Configuration error: query for \"Path\" string returned %Rra.\n", rc));
1922 return rc;
1923 }
1924
1925 /* Mountable */
1926 uint32_t u32;
1927 rc = CFGMR3QueryU32(pCfg, "Interval", &u32);
1928 if (RT_SUCCESS(rc))
1929 pThis->cMilliesPoller = u32;
1930 else if (rc == VERR_CFGM_VALUE_NOT_FOUND)
1931 pThis->cMilliesPoller = 1000;
1932 else if (RT_FAILURE(rc))
1933 {
1934 AssertMsgFailed(("Configuration error: Query \"Mountable\" resulted in %Rrc.\n", rc));
1935 return rc;
1936 }
1937
1938 /* ReadOnly */
1939 rc = CFGMR3QueryBool(pCfg, "ReadOnly", &pThis->fReadOnlyConfig);
1940 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
1941 pThis->fReadOnlyConfig = enmType == PDMBLOCKTYPE_DVD || enmType == PDMBLOCKTYPE_CDROM ? true : false;
1942 else if (RT_FAILURE(rc))
1943 {
1944 AssertMsgFailed(("Configuration error: Query \"ReadOnly\" resulted in %Rrc.\n", rc));
1945 return rc;
1946 }
1947
1948 /* Locked */
1949 rc = CFGMR3QueryBool(pCfg, "Locked", &pThis->fLocked);
1950 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
1951 pThis->fLocked = false;
1952 else if (RT_FAILURE(rc))
1953 {
1954 AssertMsgFailed(("Configuration error: Query \"Locked\" resulted in %Rrc.\n", rc));
1955 return rc;
1956 }
1957
1958 /* BIOS visible */
1959 rc = CFGMR3QueryBool(pCfg, "BIOSVisible", &pThis->fBiosVisible);
1960 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
1961 pThis->fBiosVisible = true;
1962 else if (RT_FAILURE(rc))
1963 {
1964 AssertMsgFailed(("Configuration error: Query \"BIOSVisible\" resulted in %Rrc.\n", rc));
1965 return rc;
1966 }
1967
1968 /* Uuid */
1969 char *psz;
1970 rc = CFGMR3QueryStringAlloc(pCfg, "Uuid", &psz);
1971 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
1972 RTUuidClear(&pThis->Uuid);
1973 else if (RT_SUCCESS(rc))
1974 {
1975 rc = RTUuidFromStr(&pThis->Uuid, psz);
1976 if (RT_FAILURE(rc))
1977 {
1978 AssertMsgFailed(("Configuration error: Uuid from string failed on \"%s\", rc=%Rrc.\n", psz, rc));
1979 MMR3HeapFree(psz);
1980 return rc;
1981 }
1982 MMR3HeapFree(psz);
1983 }
1984 else
1985 {
1986 AssertMsgFailed(("Configuration error: Failed to obtain the uuid, rc=%Rrc.\n", rc));
1987 return rc;
1988 }
1989
1990 /* Define whether attach failure is an error (default) or not. */
1991 bool fAttachFailError;
1992 rc = CFGMR3QueryBool(pCfg, "AttachFailError", &fAttachFailError);
1993 if (RT_FAILURE(rc))
1994 fAttachFailError = true;
1995 pThis->fAttachFailError = fAttachFailError;
1996
1997 /* name to open & watch for */
1998#ifdef RT_OS_WINDOWS
1999 int iBit = RT_C_TO_UPPER(pThis->pszDevice[0]) - 'A';
2000 if ( iBit > 'Z' - 'A'
2001 || pThis->pszDevice[1] != ':'
2002 || pThis->pszDevice[2])
2003 {
2004 AssertMsgFailed(("Configuration error: Invalid drive specification: '%s'\n", pThis->pszDevice));
2005 return VERR_INVALID_PARAMETER;
2006 }
2007 pThis->fUnitMask = 1 << iBit;
2008 RTStrAPrintf(&pThis->pszDeviceOpen, "\\\\.\\%s", pThis->pszDevice);
2009
2010#elif defined(RT_OS_SOLARIS)
2011 char *pszBlockDevName = getfullblkname(pThis->pszDevice);
2012 if (!pszBlockDevName)
2013 return VERR_NO_MEMORY;
2014 pThis->pszDeviceOpen = RTStrDup(pszBlockDevName); /* for RTStrFree() */
2015 free(pszBlockDevName);
2016 pThis->pszRawDeviceOpen = RTStrDup(pThis->pszDevice);
2017
2018#else
2019 pThis->pszDeviceOpen = RTStrDup(pThis->pszDevice);
2020#endif
2021
2022 if (!pThis->pszDeviceOpen)
2023 return VERR_NO_MEMORY;
2024
2025 return VINF_SUCCESS;
2026}
2027
2028
2029/**
2030 * Do the 2nd part of the init after the derived driver has overridden the defaults.
2031 *
2032 * On failure call DRVHostBaseDestruct().
2033 *
2034 * @returns VBox status code.
2035 * @param pThis Pointer to the instance data.
2036 */
2037int DRVHostBaseInitFinish(PDRVHOSTBASE pThis)
2038{
2039 int src = VINF_SUCCESS;
2040 PPDMDRVINS pDrvIns = pThis->pDrvIns;
2041
2042 /* log config summary */
2043 Log(("%s-%d: pszDevice='%s' (%s) cMilliesPoller=%d fReadOnlyConfig=%d fLocked=%d fBIOSVisible=%d Uuid=%RTuuid\n",
2044 pDrvIns->pReg->szName, pDrvIns->iInstance, pThis->pszDevice, pThis->pszDeviceOpen, pThis->cMilliesPoller,
2045 pThis->fReadOnlyConfig, pThis->fLocked, pThis->fBiosVisible, &pThis->Uuid));
2046
2047 /*
2048 * Check that there are no drivers below us.
2049 */
2050 AssertMsgReturn(PDMDrvHlpNoAttach(pDrvIns) == VERR_PDM_NO_ATTACHED_DRIVER,
2051 ("Configuration error: Not possible to attach anything to this driver!\n"),
2052 VERR_PDM_DRVINS_NO_ATTACH);
2053
2054 /*
2055 * Register saved state.
2056 */
2057 int rc = PDMDrvHlpSSMRegisterLoadDone(pDrvIns, drvHostBaseLoadDone);
2058 if (RT_FAILURE(rc))
2059 return rc;
2060
2061 /*
2062 * Verify type.
2063 */
2064#ifdef RT_OS_WINDOWS
2065 UINT uDriveType = GetDriveType(pThis->pszDevice);
2066 switch (pThis->enmType)
2067 {
2068 case PDMBLOCKTYPE_FLOPPY_360:
2069 case PDMBLOCKTYPE_FLOPPY_720:
2070 case PDMBLOCKTYPE_FLOPPY_1_20:
2071 case PDMBLOCKTYPE_FLOPPY_1_44:
2072 case PDMBLOCKTYPE_FLOPPY_2_88:
2073 if (uDriveType != DRIVE_REMOVABLE)
2074 {
2075 AssertMsgFailed(("Configuration error: '%s' is not a floppy (type=%d)\n",
2076 pThis->pszDevice, uDriveType));
2077 return VERR_INVALID_PARAMETER;
2078 }
2079 break;
2080 case PDMBLOCKTYPE_CDROM:
2081 case PDMBLOCKTYPE_DVD:
2082 if (uDriveType != DRIVE_CDROM)
2083 {
2084 AssertMsgFailed(("Configuration error: '%s' is not a cdrom (type=%d)\n",
2085 pThis->pszDevice, uDriveType));
2086 return VERR_INVALID_PARAMETER;
2087 }
2088 break;
2089 case PDMBLOCKTYPE_HARD_DISK:
2090 default:
2091 AssertMsgFailed(("enmType=%d\n", pThis->enmType));
2092 return VERR_INVALID_PARAMETER;
2093 }
2094#endif
2095
2096 /*
2097 * Open the device.
2098 */
2099#if defined(RT_OS_DARWIN)
2100 rc = drvHostBaseOpen(pThis, NULL, pThis->fReadOnlyConfig);
2101#else
2102 rc = drvHostBaseReopen(pThis);
2103#endif
2104 if (RT_FAILURE(rc))
2105 {
2106 char *pszDevice = pThis->pszDevice;
2107#ifndef RT_OS_DARWIN
2108 char szPathReal[256];
2109 if ( RTPathExists(pszDevice)
2110 && RT_SUCCESS(RTPathReal(pszDevice, szPathReal, sizeof(szPathReal))))
2111 pszDevice = szPathReal;
2112 pThis->FileDevice = NIL_RTFILE;
2113#endif
2114#ifdef RT_OS_SOLARIS
2115 pThis->FileRawDevice = NIL_RTFILE;
2116#endif
2117
2118 /*
2119 * Disable CD/DVD passthrough in case it was enabled. Would cause
2120 * weird failures later when the guest issues commands. These would
2121 * all fail because of the invalid file handle. So use the normal
2122 * virtual CD/DVD code, which deals more gracefully with unavailable
2123 * "media" - actually a complete drive in this case.
2124 */
2125 pThis->IBlock.pfnSendCmd = NULL;
2126 AssertMsgFailed(("Could not open host device %s, rc=%Rrc\n", pszDevice, rc));
2127 switch (rc)
2128 {
2129 case VERR_ACCESS_DENIED:
2130 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS,
2131#ifdef RT_OS_LINUX
2132 N_("Cannot open host device '%s' for %s access. Check the permissions "
2133 "of that device ('/bin/ls -l %s'): Most probably you need to be member "
2134 "of the device group. Make sure that you logout/login after changing "
2135 "the group settings of the current user"),
2136#else
2137 N_("Cannot open host device '%s' for %s access. Check the permissions "
2138 "of that device"),
2139#endif
2140 pszDevice, pThis->fReadOnlyConfig ? "readonly" : "read/write",
2141 pszDevice);
2142 default:
2143 {
2144 if (pThis->fAttachFailError)
2145 return rc;
2146 int erc = PDMDrvHlpVMSetRuntimeError(pDrvIns, 0 /*fFlags*/,
2147 "DrvHost_MOUNTFAIL",
2148 N_("Cannot attach to host device '%s'"), pszDevice);
2149 AssertRC(erc);
2150 src = rc;
2151 }
2152 }
2153 }
2154#ifdef RT_OS_WINDOWS
2155 if (RT_SUCCESS(src))
2156 DRVHostBaseMediaPresent(pThis);
2157#endif
2158
2159 /*
2160 * Lock the drive if that's required by the configuration.
2161 */
2162 if (pThis->fLocked)
2163 {
2164 if (pThis->pfnDoLock)
2165 rc = pThis->pfnDoLock(pThis, true);
2166 if (RT_FAILURE(rc))
2167 {
2168 AssertMsgFailed(("Failed to lock the dvd drive. rc=%Rrc\n", rc));
2169 return rc;
2170 }
2171 }
2172
2173#ifndef RT_OS_WINDOWS
2174 if (RT_SUCCESS(src))
2175 {
2176 /*
2177 * Create the event semaphore which the poller thread will wait on.
2178 */
2179 rc = RTSemEventCreate(&pThis->EventPoller);
2180 if (RT_FAILURE(rc))
2181 return rc;
2182 }
2183#endif
2184
2185 /*
2186 * Initialize the critical section used for serializing the access to the media.
2187 */
2188 rc = RTCritSectInit(&pThis->CritSect);
2189 if (RT_FAILURE(rc))
2190 return rc;
2191
2192 if (RT_SUCCESS(src))
2193 {
2194 /*
2195 * Start the thread which will poll for the media.
2196 */
2197 rc = RTThreadCreate(&pThis->ThreadPoller, drvHostBaseMediaThread, pThis, 0,
2198 RTTHREADTYPE_INFREQUENT_POLLER, RTTHREADFLAGS_WAITABLE, "DVDMEDIA");
2199 if (RT_FAILURE(rc))
2200 {
2201 AssertMsgFailed(("Failed to create poller thread. rc=%Rrc\n", rc));
2202 return rc;
2203 }
2204
2205 /*
2206 * Wait for the thread to start up (!w32:) and do one detection loop.
2207 */
2208 rc = RTThreadUserWait(pThis->ThreadPoller, 10000);
2209 AssertRC(rc);
2210#ifdef RT_OS_WINDOWS
2211 if (!pThis->hwndDeviceChange)
2212 return VERR_GENERAL_FAILURE;
2213#endif
2214 }
2215
2216 if (RT_FAILURE(src))
2217 return src;
2218 return rc;
2219}
2220
Note: See TracBrowser for help on using the repository browser.

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