VirtualBox

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

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

*: Fixes for incorrect RTStrAPrintf usage (it does NOT return an IPRT status code) and the odd bugs nearby.

  • 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 33464 2010-10-26 12:27:50Z 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/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)
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 precation
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 * accross 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 union ccb DeviceCCB;
984
985 /*
986 * The device path, target id and lun id. Those are
987 * needed for the SCSI passthrough ioctl.
988 */
989 memset(&DeviceCCB, 0, sizeof(DeviceCCB));
990 DeviceCCB.ccb_h.func_code = XPT_GDEVLIST;
991
992 rcBSD = ioctl(PassthroughDevice, CAMGETPASSTHRU, &DeviceCCB);
993 if (!rcBSD)
994 {
995 if (DeviceCCB.cgdl.status != CAM_GDEVLIST_ERROR)
996 {
997 pThis->ScsiBus = DeviceCCB.ccb_h.path_id;
998 pThis->ScsiTargetID = DeviceCCB.ccb_h.target_id;
999 pThis->ScsiLunID = DeviceCCB.ccb_h.target_lun;
1000 *pFileDevice = PassthroughDevice;
1001 }
1002 else
1003 {
1004 /* The passthrough device wasn't found. */
1005 rc = VERR_NOT_FOUND;
1006 }
1007 }
1008 else
1009 rc = RTErrConvertFromErrno(errno);
1010
1011 if (RT_FAILURE(rc))
1012 RTFileClose(PassthroughDevice);
1013 }
1014 }
1015 else
1016 rc = VERR_NO_STR_MEMORY;
1017 }
1018 else
1019 rc = RTErrConvertFromErrno(errno);
1020
1021 RTFileClose(FileDevice);
1022 return rc;
1023#else
1024 return RTFileOpen(pFileDevice, pThis->pszDeviceOpen,
1025 (fReadOnly ? RTFILE_O_READ : RTFILE_O_READWRITE) | RTFILE_O_OPEN | RTFILE_O_DENY_NONE);
1026#endif
1027}
1028
1029#else /* RT_OS_SOLARIS */
1030
1031/**
1032 * Solaris wrapper for RTFileOpen.
1033 *
1034 * Solaris has to deal with two filehandles, a block and a raw one. Rather than messing
1035 * with drvHostBaseOpen's function signature & body, having a seperate one is better.
1036 *
1037 * @returns VBox status code.
1038 */
1039static int drvHostBaseOpen(PDRVHOSTBASE pThis, PRTFILE pFileBlockDevice, PRTFILE pFileRawDevice, bool fReadOnly)
1040{
1041 unsigned fFlags = (fReadOnly ? RTFILE_O_READ : RTFILE_O_READWRITE)
1042 | RTFILE_O_OPEN | RTFILE_O_DENY_NONE | RTFILE_O_NON_BLOCK;
1043 int rc = RTFileOpen(pFileBlockDevice, pThis->pszDeviceOpen, fFlags);
1044 if (RT_SUCCESS(rc))
1045 {
1046 rc = RTFileOpen(pFileRawDevice, pThis->pszRawDeviceOpen, fFlags);
1047 if (RT_SUCCESS(rc))
1048 return rc;
1049
1050 LogRel(("DVD: failed to open device %s rc=%Rrc\n", pThis->pszRawDeviceOpen, rc));
1051 RTFileClose(*pFileBlockDevice);
1052 }
1053 else
1054 LogRel(("DVD: failed to open device %s rc=%Rrc\n", pThis->pszDeviceOpen, rc));
1055 return rc;
1056}
1057#endif /* RT_OS_SOLARIS */
1058
1059
1060/**
1061 * (Re)opens the device.
1062 *
1063 * This is used to open the device during construction, but it's also used to re-open
1064 * the device when a media is inserted. This re-open will kill off any cached data
1065 * that Linux for some peculiar reason thinks should survive a media change...
1066 *
1067 * @returns VBOX status code.
1068 * @param pThis Instance data.
1069 */
1070static int drvHostBaseReopen(PDRVHOSTBASE pThis)
1071{
1072#ifndef RT_OS_DARWIN /* Only *one* open for darwin. */
1073 LogFlow(("%s-%d: drvHostBaseReopen: '%s'\n", pThis->pDrvIns->pReg->szName, pThis->pDrvIns->iInstance, pThis->pszDeviceOpen));
1074
1075 RTFILE FileDevice;
1076#ifdef RT_OS_SOLARIS
1077 if (pThis->FileRawDevice != NIL_RTFILE)
1078 {
1079 RTFileClose(pThis->FileRawDevice);
1080 pThis->FileRawDevice = NIL_RTFILE;
1081 }
1082 if (pThis->FileDevice != NIL_RTFILE)
1083 {
1084 RTFileClose(pThis->FileDevice);
1085 pThis->FileDevice = NIL_RTFILE;
1086 }
1087 RTFILE FileRawDevice;
1088 int rc = drvHostBaseOpen(pThis, &FileDevice, &FileRawDevice, pThis->fReadOnlyConfig);
1089#else
1090 int rc = drvHostBaseOpen(pThis, &FileDevice, pThis->fReadOnlyConfig);
1091#endif
1092 if (RT_FAILURE(rc))
1093 {
1094 if (!pThis->fReadOnlyConfig)
1095 {
1096 LogFlow(("%s-%d: drvHostBaseReopen: '%s' - retry readonly (%Rrc)\n", pThis->pDrvIns->pReg->szName, pThis->pDrvIns->iInstance, pThis->pszDeviceOpen, rc));
1097#ifdef RT_OS_SOLARIS
1098 rc = drvHostBaseOpen(pThis, &FileDevice, &FileRawDevice, false);
1099#else
1100 rc = drvHostBaseOpen(pThis, &FileDevice, false);
1101#endif
1102 }
1103 if (RT_FAILURE(rc))
1104 {
1105 LogFlow(("%s-%d: failed to open device '%s', rc=%Rrc\n",
1106 pThis->pDrvIns->pReg->szName, pThis->pDrvIns->iInstance, pThis->pszDevice, rc));
1107 return rc;
1108 }
1109 pThis->fReadOnly = true;
1110 }
1111 else
1112 pThis->fReadOnly = pThis->fReadOnlyConfig;
1113
1114#ifdef RT_OS_SOLARIS
1115 if (pThis->FileRawDevice != NIL_RTFILE)
1116 RTFileClose(pThis->FileRawDevice);
1117 pThis->FileRawDevice = FileRawDevice;
1118#endif
1119
1120 if (pThis->FileDevice != NIL_RTFILE)
1121 RTFileClose(pThis->FileDevice);
1122 pThis->FileDevice = FileDevice;
1123#endif /* !RT_OS_DARWIN */
1124 return VINF_SUCCESS;
1125}
1126
1127
1128/**
1129 * Queries the media size.
1130 *
1131 * @returns VBox status code.
1132 * @param pThis Pointer to the instance data.
1133 * @param pcb Where to store the media size in bytes.
1134 */
1135static int drvHostBaseGetMediaSize(PDRVHOSTBASE pThis, uint64_t *pcb)
1136{
1137#if defined(RT_OS_DARWIN) || defined(RT_OS_FREEBSD)
1138 /*
1139 * Try a READ_CAPACITY command...
1140 */
1141 struct
1142 {
1143 uint32_t cBlocks;
1144 uint32_t cbBlock;
1145 } Buf = {0, 0};
1146 uint32_t cbBuf = sizeof(Buf);
1147 uint8_t abCmd[16] =
1148 {
1149 SCSI_READ_CAPACITY, 0, 0, 0, 0, 0, 0,
1150 0,0,0,0,0,0,0,0,0
1151 };
1152 int rc = DRVHostBaseScsiCmd(pThis, abCmd, 6, PDMBLOCKTXDIR_FROM_DEVICE, &Buf, &cbBuf, NULL, 0, 0);
1153 if (RT_SUCCESS(rc))
1154 {
1155 Assert(cbBuf == sizeof(Buf));
1156 Buf.cBlocks = RT_BE2H_U32(Buf.cBlocks);
1157 Buf.cbBlock = RT_BE2H_U32(Buf.cbBlock);
1158 //if (Buf.cbBlock > 2048) /* everyone else is doing this... check if it needed/right.*/
1159 // Buf.cbBlock = 2048;
1160 pThis->cbBlock = Buf.cbBlock;
1161
1162 *pcb = (uint64_t)Buf.cBlocks * Buf.cbBlock;
1163 }
1164 return rc;
1165
1166#elif defined(RT_OS_SOLARIS)
1167 /*
1168 * Sun docs suggests using DKIOCGGEOM instead of DKIOCGMEDIAINFO, but
1169 * Sun themselves use DKIOCGMEDIAINFO for DVDs/CDs, and use DKIOCGGEOM
1170 * for secondary storage devices.
1171 */
1172 struct dk_minfo MediaInfo;
1173 if (ioctl(pThis->FileRawDevice, DKIOCGMEDIAINFO, &MediaInfo) == 0)
1174 {
1175 *pcb = MediaInfo.dki_capacity * (uint64_t)MediaInfo.dki_lbsize;
1176 return VINF_SUCCESS;
1177 }
1178 return RTFileSeek(pThis->FileDevice, 0, RTFILE_SEEK_END, pcb);
1179
1180#elif defined(RT_OS_WINDOWS)
1181 /* use NT api, retry a few times if the media is being verified. */
1182 IO_STATUS_BLOCK IoStatusBlock = {0};
1183 FILE_FS_SIZE_INFORMATION FsSize= {0};
1184 NTSTATUS rcNt = NtQueryVolumeInformationFile((HANDLE)pThis->FileDevice, &IoStatusBlock,
1185 &FsSize, sizeof(FsSize), FileFsSizeInformation);
1186 int cRetries = 5;
1187 while (rcNt == STATUS_VERIFY_REQUIRED && cRetries-- > 0)
1188 {
1189 RTThreadSleep(10);
1190 rcNt = NtQueryVolumeInformationFile((HANDLE)pThis->FileDevice, &IoStatusBlock,
1191 &FsSize, sizeof(FsSize), FileFsSizeInformation);
1192 }
1193 if (rcNt >= 0)
1194 {
1195 *pcb = FsSize.TotalAllocationUnits.QuadPart * FsSize.BytesPerSector;
1196 return VINF_SUCCESS;
1197 }
1198
1199 /* convert nt status code to VBox status code. */
1200 /** @todo Make convertion function!. */
1201 int rc = VERR_GENERAL_FAILURE;
1202 switch (rcNt)
1203 {
1204 case STATUS_NO_MEDIA_IN_DEVICE: rc = VERR_MEDIA_NOT_PRESENT; break;
1205 case STATUS_VERIFY_REQUIRED: rc = VERR_TRY_AGAIN; break;
1206 }
1207 LogFlow(("drvHostBaseGetMediaSize: NtQueryVolumeInformationFile -> %#lx\n", rcNt, rc));
1208 return rc;
1209#else
1210 return RTFileSeek(pThis->FileDevice, 0, RTFILE_SEEK_END, pcb);
1211#endif
1212}
1213
1214
1215#if defined(RT_OS_DARWIN) || defined(RT_OS_FREEBSD)
1216/**
1217 * Execute a SCSI command.
1218 *
1219 * @param pThis The instance data.
1220 * @param pbCmd Pointer to the SCSI command.
1221 * @param cbCmd The size of the SCSI command.
1222 * @param enmTxDir The transfer direction.
1223 * @param pvBuf The buffer. Can be NULL if enmTxDir is PDMBLOCKTXDIR_NONE.
1224 * @param pcbBuf Where to get the buffer size from and put the actual transfer size. Can be NULL.
1225 * @param pbSense Where to put the sense data. Can be NULL.
1226 * @param cbSense Size of the sense data buffer.
1227 * @param cTimeoutMillies The timeout. 0 mean the default timeout.
1228 *
1229 * @returns VINF_SUCCESS on success (no sense code).
1230 * @returns VERR_UNRESOLVED_ERROR if sense code is present.
1231 * @returns Some other VBox status code on failures without sense code.
1232 *
1233 * @todo Fix VERR_UNRESOLVED_ERROR abuse.
1234 */
1235DECLCALLBACK(int) DRVHostBaseScsiCmd(PDRVHOSTBASE pThis, const uint8_t *pbCmd, size_t cbCmd, PDMBLOCKTXDIR enmTxDir,
1236 void *pvBuf, uint32_t *pcbBuf, uint8_t *pbSense, size_t cbSense, uint32_t cTimeoutMillies)
1237{
1238 /*
1239 * Minimal input validation.
1240 */
1241 Assert(enmTxDir == PDMBLOCKTXDIR_NONE || enmTxDir == PDMBLOCKTXDIR_FROM_DEVICE || enmTxDir == PDMBLOCKTXDIR_TO_DEVICE);
1242 Assert(!pvBuf || pcbBuf);
1243 Assert(pvBuf || enmTxDir == PDMBLOCKTXDIR_NONE);
1244 Assert(pbSense || !cbSense);
1245 AssertPtr(pbCmd);
1246 Assert(cbCmd <= 16 && cbCmd >= 1);
1247 const uint32_t cbBuf = pcbBuf ? *pcbBuf : 0;
1248 if (pcbBuf)
1249 *pcbBuf = 0;
1250
1251# ifdef RT_OS_DARWIN
1252 Assert(pThis->ppScsiTaskDI);
1253
1254 int rc = VERR_GENERAL_FAILURE;
1255 SCSITaskInterface **ppScsiTaskI = (*pThis->ppScsiTaskDI)->CreateSCSITask(pThis->ppScsiTaskDI);
1256 if (!ppScsiTaskI)
1257 return VERR_NO_MEMORY;
1258 do
1259 {
1260 /* Setup the scsi command. */
1261 SCSICommandDescriptorBlock cdb = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 };
1262 memcpy(&cdb[0], pbCmd, cbCmd);
1263 IOReturn irc = (*ppScsiTaskI)->SetCommandDescriptorBlock(ppScsiTaskI, cdb, cbCmd);
1264 AssertBreak(irc == kIOReturnSuccess);
1265
1266 /* Setup the buffer. */
1267 if (enmTxDir == PDMBLOCKTXDIR_NONE)
1268 irc = (*ppScsiTaskI)->SetScatterGatherEntries(ppScsiTaskI, NULL, 0, 0, kSCSIDataTransfer_NoDataTransfer);
1269 else
1270 {
1271 IOVirtualRange Range = { (IOVirtualAddress)pvBuf, cbBuf };
1272 irc = (*ppScsiTaskI)->SetScatterGatherEntries(ppScsiTaskI, &Range, 1, cbBuf,
1273 enmTxDir == PDMBLOCKTXDIR_FROM_DEVICE
1274 ? kSCSIDataTransfer_FromTargetToInitiator
1275 : kSCSIDataTransfer_FromInitiatorToTarget);
1276 }
1277 AssertBreak(irc == kIOReturnSuccess);
1278
1279 /* Set the timeout. */
1280 irc = (*ppScsiTaskI)->SetTimeoutDuration(ppScsiTaskI, cTimeoutMillies ? cTimeoutMillies : 30000 /*ms*/);
1281 AssertBreak(irc == kIOReturnSuccess);
1282
1283 /* Execute the command and get the response. */
1284 SCSI_Sense_Data SenseData = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 };
1285 SCSIServiceResponse ServiceResponse = kSCSIServiceResponse_Request_In_Process;
1286 SCSITaskStatus TaskStatus = kSCSITaskStatus_GOOD;
1287 UInt64 cbReturned = 0;
1288 irc = (*ppScsiTaskI)->ExecuteTaskSync(ppScsiTaskI, &SenseData, &TaskStatus, &cbReturned);
1289 AssertBreak(irc == kIOReturnSuccess);
1290 if (pcbBuf)
1291 *pcbBuf = (int32_t)cbReturned;
1292
1293 irc = (*ppScsiTaskI)->GetSCSIServiceResponse(ppScsiTaskI, &ServiceResponse);
1294 AssertBreak(irc == kIOReturnSuccess);
1295 AssertBreak(ServiceResponse == kSCSIServiceResponse_TASK_COMPLETE);
1296
1297 if (TaskStatus == kSCSITaskStatus_GOOD)
1298 rc = VINF_SUCCESS;
1299 else if ( TaskStatus == kSCSITaskStatus_CHECK_CONDITION
1300 && pbSense)
1301 {
1302 memset(pbSense, 0, cbSense); /* lazy */
1303 memcpy(pbSense, &SenseData, RT_MIN(sizeof(SenseData), cbSense));
1304 rc = VERR_UNRESOLVED_ERROR;
1305 }
1306 /** @todo convert sense codes when caller doesn't wish to do this himself. */
1307 /*else if ( TaskStatus == kSCSITaskStatus_CHECK_CONDITION
1308 && SenseData.ADDITIONAL_SENSE_CODE == 0x3A)
1309 rc = VERR_MEDIA_NOT_PRESENT; */
1310 else
1311 {
1312 rc = enmTxDir == PDMBLOCKTXDIR_NONE
1313 ? VERR_DEV_IO_ERROR
1314 : enmTxDir == PDMBLOCKTXDIR_FROM_DEVICE
1315 ? VERR_READ_ERROR
1316 : VERR_WRITE_ERROR;
1317 if (pThis->cLogRelErrors++ < 10)
1318 LogRel(("DVD scsi error: cmd={%.*Rhxs} TaskStatus=%#x key=%#x ASC=%#x ASCQ=%#x (%Rrc)\n",
1319 cbCmd, pbCmd, TaskStatus, SenseData.SENSE_KEY, SenseData.ADDITIONAL_SENSE_CODE,
1320 SenseData.ADDITIONAL_SENSE_CODE_QUALIFIER, rc));
1321 }
1322 } while (0);
1323
1324 (*ppScsiTaskI)->Release(ppScsiTaskI);
1325
1326# elif defined(RT_OS_FREEBSD)
1327 int rc = VINF_SUCCESS;
1328 int rcBSD = 0;
1329 union ccb DeviceCCB;
1330 union ccb *pDeviceCCB = &DeviceCCB;
1331 u_int32_t fFlags;
1332
1333 memset(pDeviceCCB, 0, sizeof(DeviceCCB));
1334 pDeviceCCB->ccb_h.path_id = pThis->ScsiBus;
1335 pDeviceCCB->ccb_h.target_id = pThis->ScsiTargetID;
1336 pDeviceCCB->ccb_h.target_lun = pThis->ScsiLunID;
1337
1338 /* The SCSI INQUIRY command can't be passed through directly. */
1339 if (pbCmd[0] == SCSI_INQUIRY)
1340 {
1341 pDeviceCCB->ccb_h.func_code = XPT_GDEV_TYPE;
1342
1343 rcBSD = ioctl(pThis->FileDevice, CAMIOCOMMAND, pDeviceCCB);
1344 if (!rcBSD)
1345 {
1346 uint32_t cbCopy = cbBuf < sizeof(struct scsi_inquiry_data)
1347 ? cbBuf
1348 : sizeof(struct scsi_inquiry_data);;
1349 memcpy(pvBuf, &pDeviceCCB->cgd.inq_data, cbCopy);
1350 memset(pbSense, 0, cbSense);
1351
1352 if (pcbBuf)
1353 *pcbBuf = cbCopy;
1354 }
1355 else
1356 rc = RTErrConvertFromErrno(errno);
1357 }
1358 else
1359 {
1360 /* Copy the CDB. */
1361 memcpy(&pDeviceCCB->csio.cdb_io.cdb_bytes, pbCmd, cbCmd);
1362
1363 /* Set direction. */
1364 if (enmTxDir == PDMBLOCKTXDIR_NONE)
1365 fFlags = CAM_DIR_NONE;
1366 else if (enmTxDir == PDMBLOCKTXDIR_FROM_DEVICE)
1367 fFlags = CAM_DIR_IN;
1368 else
1369 fFlags = CAM_DIR_OUT;
1370
1371 fFlags |= CAM_DEV_QFRZDIS;
1372
1373 cam_fill_csio(&pDeviceCCB->csio, 1, NULL, fFlags, MSG_SIMPLE_Q_TAG,
1374 (u_int8_t *)pvBuf, cbBuf, cbSense, cbCmd,
1375 cTimeoutMillies ? cTimeoutMillies : 30000/* timeout */);
1376
1377 /* Send command */
1378 rcBSD = ioctl(pThis->FileDevice, CAMIOCOMMAND, pDeviceCCB);
1379 if (!rcBSD)
1380 {
1381 switch (pDeviceCCB->ccb_h.status & CAM_STATUS_MASK)
1382 {
1383 case CAM_REQ_CMP:
1384 rc = VINF_SUCCESS;
1385 break;
1386 case CAM_SEL_TIMEOUT:
1387 rc = VERR_DEV_IO_ERROR;
1388 break;
1389 case CAM_CMD_TIMEOUT:
1390 rc = VERR_TIMEOUT;
1391 break;
1392 default:
1393 rc = VERR_DEV_IO_ERROR;
1394 }
1395
1396 if (pcbBuf)
1397 *pcbBuf = cbBuf - pDeviceCCB->csio.resid;
1398
1399 if (pbSense)
1400 memcpy(pbSense, &pDeviceCCB->csio.sense_data,
1401 cbSense - pDeviceCCB->csio.sense_resid);
1402 }
1403 else
1404 rc = RTErrConvertFromErrno(errno);
1405 }
1406# endif
1407
1408 return rc;
1409}
1410#endif
1411
1412
1413/**
1414 * Media present.
1415 * Query the size and notify the above driver / device.
1416 *
1417 * @param pThis The instance data.
1418 */
1419int DRVHostBaseMediaPresent(PDRVHOSTBASE pThis)
1420{
1421 /*
1422 * Open the drive.
1423 */
1424 int rc = drvHostBaseReopen(pThis);
1425 if (RT_FAILURE(rc))
1426 return rc;
1427
1428 /*
1429 * Determine the size.
1430 */
1431 uint64_t cb;
1432 rc = pThis->pfnGetMediaSize(pThis, &cb);
1433 if (RT_FAILURE(rc))
1434 {
1435 LogFlow(("%s-%d: failed to figure media size of %s, rc=%Rrc\n",
1436 pThis->pDrvIns->pReg->szName, pThis->pDrvIns->iInstance, pThis->pszDevice, rc));
1437 return rc;
1438 }
1439
1440 /*
1441 * Update the data and inform the unit.
1442 */
1443 pThis->cbSize = cb;
1444 pThis->fMediaPresent = true;
1445 if (pThis->pDrvMountNotify)
1446 pThis->pDrvMountNotify->pfnMountNotify(pThis->pDrvMountNotify);
1447 LogFlow(("%s-%d: drvHostBaseMediaPresent: cbSize=%lld (%#llx)\n",
1448 pThis->pDrvIns->pReg->szName, pThis->pDrvIns->iInstance, pThis->cbSize, pThis->cbSize));
1449 return VINF_SUCCESS;
1450}
1451
1452
1453/**
1454 * Media no longer present.
1455 * @param pThis The instance data.
1456 */
1457void DRVHostBaseMediaNotPresent(PDRVHOSTBASE pThis)
1458{
1459 pThis->fMediaPresent = false;
1460 pThis->fLocked = false;
1461 pThis->PCHSGeometry.cCylinders = 0;
1462 pThis->PCHSGeometry.cHeads = 0;
1463 pThis->PCHSGeometry.cSectors = 0;
1464 pThis->LCHSGeometry.cCylinders = 0;
1465 pThis->LCHSGeometry.cHeads = 0;
1466 pThis->LCHSGeometry.cSectors = 0;
1467 if (pThis->pDrvMountNotify)
1468 pThis->pDrvMountNotify->pfnUnmountNotify(pThis->pDrvMountNotify);
1469}
1470
1471
1472#ifdef RT_OS_WINDOWS
1473
1474/**
1475 * Window procedure for the invisible window used to catch the WM_DEVICECHANGE broadcasts.
1476 */
1477static LRESULT CALLBACK DeviceChangeWindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
1478{
1479 Log2(("DeviceChangeWindowProc: hwnd=%08x uMsg=%08x\n", hwnd, uMsg));
1480 if (uMsg == WM_DESTROY)
1481 {
1482 PDRVHOSTBASE pThis = (PDRVHOSTBASE)GetWindowLong(hwnd, GWLP_USERDATA);
1483 if (pThis)
1484 ASMAtomicXchgSize(&pThis->hwndDeviceChange, NULL);
1485 PostQuitMessage(0);
1486 }
1487
1488 if (uMsg != WM_DEVICECHANGE)
1489 return DefWindowProc(hwnd, uMsg, wParam, lParam);
1490
1491 PDEV_BROADCAST_HDR lpdb = (PDEV_BROADCAST_HDR)lParam;
1492 PDRVHOSTBASE pThis = (PDRVHOSTBASE)GetWindowLongPtr(hwnd, GWLP_USERDATA);
1493 Assert(pThis);
1494 if (pThis == NULL)
1495 return 0;
1496
1497 switch (wParam)
1498 {
1499 case DBT_DEVICEARRIVAL:
1500 case DBT_DEVICEREMOVECOMPLETE:
1501 // Check whether a CD or DVD was inserted into or removed from a drive.
1502 if (lpdb->dbch_devicetype == DBT_DEVTYP_VOLUME)
1503 {
1504 PDEV_BROADCAST_VOLUME lpdbv = (PDEV_BROADCAST_VOLUME)lpdb;
1505 if ( (lpdbv->dbcv_flags & DBTF_MEDIA)
1506 && (pThis->fUnitMask & lpdbv->dbcv_unitmask))
1507 {
1508 RTCritSectEnter(&pThis->CritSect);
1509 if (wParam == DBT_DEVICEARRIVAL)
1510 {
1511 int cRetries = 10;
1512 int rc = DRVHostBaseMediaPresent(pThis);
1513 while (RT_FAILURE(rc) && cRetries-- > 0)
1514 {
1515 RTThreadSleep(50);
1516 rc = DRVHostBaseMediaPresent(pThis);
1517 }
1518 }
1519 else
1520 DRVHostBaseMediaNotPresent(pThis);
1521 RTCritSectLeave(&pThis->CritSect);
1522 }
1523 }
1524 break;
1525 }
1526 return TRUE;
1527}
1528
1529#endif /* RT_OS_WINDOWS */
1530
1531
1532/**
1533 * This thread will periodically poll the device for media presence.
1534 *
1535 * @returns Ignored.
1536 * @param ThreadSelf Handle of this thread. Ignored.
1537 * @param pvUser Pointer to the driver instance structure.
1538 */
1539static DECLCALLBACK(int) drvHostBaseMediaThread(RTTHREAD ThreadSelf, void *pvUser)
1540{
1541 PDRVHOSTBASE pThis = (PDRVHOSTBASE)pvUser;
1542 LogFlow(("%s-%d: drvHostBaseMediaThread: ThreadSelf=%p pvUser=%p\n",
1543 pThis->pDrvIns->pReg->szName, pThis->pDrvIns->iInstance, ThreadSelf, pvUser));
1544#ifdef RT_OS_WINDOWS
1545 static WNDCLASS s_classDeviceChange = {0};
1546 static ATOM s_hAtomDeviceChange = 0;
1547
1548 /*
1549 * Register custom window class.
1550 */
1551 if (s_hAtomDeviceChange == 0)
1552 {
1553 memset(&s_classDeviceChange, 0, sizeof(s_classDeviceChange));
1554 s_classDeviceChange.lpfnWndProc = DeviceChangeWindowProc;
1555 s_classDeviceChange.lpszClassName = "VBOX_DeviceChangeClass";
1556 s_classDeviceChange.hInstance = GetModuleHandle("VBOXDD.DLL");
1557 Assert(s_classDeviceChange.hInstance);
1558 s_hAtomDeviceChange = RegisterClassA(&s_classDeviceChange);
1559 Assert(s_hAtomDeviceChange);
1560 }
1561
1562 /*
1563 * Create Window w/ the pThis as user data.
1564 */
1565 HWND hwnd = CreateWindow((LPCTSTR)s_hAtomDeviceChange, "", WS_POPUP, 0, 0, 0, 0, 0, 0, s_classDeviceChange.hInstance, 0);
1566 AssertMsg(hwnd, ("CreateWindow failed with %d\n", GetLastError()));
1567 SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR)pThis);
1568
1569 /*
1570 * Signal the waiting EMT thread that everything went fine.
1571 */
1572 ASMAtomicXchgSize(&pThis->hwndDeviceChange, hwnd);
1573 RTThreadUserSignal(ThreadSelf);
1574 if (!hwnd)
1575 {
1576 LogFlow(("%s-%d: drvHostBaseMediaThread: returns VERR_GENERAL_FAILURE\n", pThis->pDrvIns->pReg->szName, pThis->pDrvIns->iInstance));
1577 return VERR_GENERAL_FAILURE;
1578 }
1579 LogFlow(("%s-%d: drvHostBaseMediaThread: Created hwndDeviceChange=%p\n", pThis->pDrvIns->pReg->szName, pThis->pDrvIns->iInstance, hwnd));
1580
1581 /*
1582 * Message pump.
1583 */
1584 MSG Msg;
1585 BOOL fRet;
1586 while ((fRet = GetMessage(&Msg, NULL, 0, 0)) != FALSE)
1587 {
1588 if (fRet != -1)
1589 {
1590 TranslateMessage(&Msg);
1591 DispatchMessage(&Msg);
1592 }
1593 //else: handle the error and possibly exit
1594 }
1595 Assert(!pThis->hwndDeviceChange);
1596
1597#else /* !RT_OS_WINDOWS */
1598 bool fFirst = true;
1599 int cRetries = 10;
1600 while (!pThis->fShutdownPoller)
1601 {
1602 /*
1603 * Perform the polling (unless we've run out of 50ms retries).
1604 */
1605 if ( pThis->pfnPoll
1606 && cRetries-- > 0)
1607 {
1608
1609 int rc = pThis->pfnPoll(pThis);
1610 if (RT_FAILURE(rc))
1611 {
1612 RTSemEventWait(pThis->EventPoller, 50);
1613 continue;
1614 }
1615 }
1616
1617 /*
1618 * Signal EMT after the first go.
1619 */
1620 if (fFirst)
1621 {
1622 RTThreadUserSignal(ThreadSelf);
1623 fFirst = false;
1624 }
1625
1626 /*
1627 * Sleep.
1628 */
1629 int rc = RTSemEventWait(pThis->EventPoller, pThis->cMilliesPoller);
1630 if ( RT_FAILURE(rc)
1631 && rc != VERR_TIMEOUT)
1632 {
1633 AssertMsgFailed(("rc=%Rrc\n", rc));
1634 pThis->ThreadPoller = NIL_RTTHREAD;
1635 LogFlow(("drvHostBaseMediaThread: returns %Rrc\n", rc));
1636 return rc;
1637 }
1638 cRetries = 10;
1639 }
1640
1641#endif /* !RT_OS_WINDOWS */
1642
1643 /* (Don't clear the thread handle here, the destructor thread is using it to wait.) */
1644 LogFlow(("%s-%d: drvHostBaseMediaThread: returns VINF_SUCCESS\n", pThis->pDrvIns->pReg->szName, pThis->pDrvIns->iInstance));
1645 return VINF_SUCCESS;
1646}
1647
1648/* -=-=-=-=- driver interface -=-=-=-=- */
1649
1650
1651/**
1652 * Done state load operation.
1653 *
1654 * @returns VBox load code.
1655 * @param pDrvIns Driver instance of the driver which registered the data unit.
1656 * @param pSSM SSM operation handle.
1657 */
1658static DECLCALLBACK(int) drvHostBaseLoadDone(PPDMDRVINS pDrvIns, PSSMHANDLE pSSM)
1659{
1660 PDRVHOSTBASE pThis = PDMINS_2_DATA(pDrvIns, PDRVHOSTBASE);
1661 LogFlow(("%s-%d: drvHostBaseMediaThread:\n", pThis->pDrvIns->pReg->szName, pThis->pDrvIns->iInstance));
1662 RTCritSectEnter(&pThis->CritSect);
1663
1664 /*
1665 * Tell the device/driver above us that the media status is uncertain.
1666 */
1667 if (pThis->pDrvMountNotify)
1668 {
1669 pThis->pDrvMountNotify->pfnUnmountNotify(pThis->pDrvMountNotify);
1670 if (pThis->fMediaPresent)
1671 pThis->pDrvMountNotify->pfnMountNotify(pThis->pDrvMountNotify);
1672 }
1673
1674 RTCritSectLeave(&pThis->CritSect);
1675 return VINF_SUCCESS;
1676}
1677
1678
1679/** @copydoc FNPDMDRVDESTRUCT */
1680DECLCALLBACK(void) DRVHostBaseDestruct(PPDMDRVINS pDrvIns)
1681{
1682 PDRVHOSTBASE pThis = PDMINS_2_DATA(pDrvIns, PDRVHOSTBASE);
1683 LogFlow(("%s-%d: drvHostBaseDestruct: iInstance=%d\n", pDrvIns->pReg->szName, pDrvIns->iInstance, pDrvIns->iInstance));
1684
1685 /*
1686 * Terminate the thread.
1687 */
1688 if (pThis->ThreadPoller != NIL_RTTHREAD)
1689 {
1690 pThis->fShutdownPoller = true;
1691 int rc;
1692 int cTimes = 50;
1693 do
1694 {
1695#ifdef RT_OS_WINDOWS
1696 if (pThis->hwndDeviceChange)
1697 PostMessage(pThis->hwndDeviceChange, WM_CLOSE, 0, 0); /* default win proc will destroy the window */
1698#else
1699 RTSemEventSignal(pThis->EventPoller);
1700#endif
1701 rc = RTThreadWait(pThis->ThreadPoller, 100, NULL);
1702 } while (cTimes-- > 0 && rc == VERR_TIMEOUT);
1703
1704 if (!rc)
1705 pThis->ThreadPoller = NIL_RTTHREAD;
1706 }
1707
1708 /*
1709 * Unlock the drive if we've locked it or we're in passthru mode.
1710 */
1711#ifdef RT_OS_DARWIN
1712 if ( ( pThis->fLocked
1713 || pThis->IBlock.pfnSendCmd)
1714 && pThis->ppScsiTaskDI
1715#else /** @todo Check if the other guys can mix pfnDoLock with scsi passthru.
1716 * (We're currently not unlocking the device after use. See todo in DevATA.cpp.) */
1717 if ( pThis->fLocked
1718 && pThis->FileDevice != NIL_RTFILE
1719#endif
1720 && pThis->pfnDoLock)
1721 {
1722 int rc = pThis->pfnDoLock(pThis, false);
1723 if (RT_SUCCESS(rc))
1724 pThis->fLocked = false;
1725 }
1726
1727 /*
1728 * Cleanup the other resources.
1729 */
1730#ifdef RT_OS_WINDOWS
1731 if (pThis->hwndDeviceChange)
1732 {
1733 if (SetWindowLongPtr(pThis->hwndDeviceChange, GWLP_USERDATA, 0) == (LONG_PTR)pThis)
1734 PostMessage(pThis->hwndDeviceChange, WM_CLOSE, 0, 0); /* default win proc will destroy the window */
1735 pThis->hwndDeviceChange = NULL;
1736 }
1737#else
1738 if (pThis->EventPoller != NULL)
1739 {
1740 RTSemEventDestroy(pThis->EventPoller);
1741 pThis->EventPoller = NULL;
1742 }
1743#endif
1744
1745#ifdef RT_OS_DARWIN
1746 /*
1747 * The unclaiming doesn't seem to mean much, the DVD is actaully
1748 * remounted when we release exclusive access. I'm not quite sure
1749 * if I should put the unclaim first or not...
1750 *
1751 * Anyway, that it's automatically remounted very good news for us,
1752 * because that means we don't have to mess with that ourselves. Of
1753 * course there is the unlikely scenario that we've succeeded in claiming
1754 * and umount the DVD but somehow failed to gain exclusive scsi access...
1755 */
1756 if (pThis->ppScsiTaskDI)
1757 {
1758 LogFlow(("%s-%d: releasing exclusive scsi access!\n", pDrvIns->pReg->szName, pDrvIns->iInstance));
1759 (*pThis->ppScsiTaskDI)->ReleaseExclusiveAccess(pThis->ppScsiTaskDI);
1760 (*pThis->ppScsiTaskDI)->Release(pThis->ppScsiTaskDI);
1761 pThis->ppScsiTaskDI = NULL;
1762 }
1763 if (pThis->pDADisk)
1764 {
1765 LogFlow(("%s-%d: unclaiming the disk!\n", pDrvIns->pReg->szName, pDrvIns->iInstance));
1766 DADiskUnclaim(pThis->pDADisk);
1767 CFRelease(pThis->pDADisk);
1768 pThis->pDADisk = NULL;
1769 }
1770 if (pThis->ppMMCDI)
1771 {
1772 LogFlow(("%s-%d: releasing the MMC object!\n", pDrvIns->pReg->szName, pDrvIns->iInstance));
1773 (*pThis->ppMMCDI)->Release(pThis->ppMMCDI);
1774 pThis->ppMMCDI = NULL;
1775 }
1776 if (pThis->MasterPort)
1777 {
1778 mach_port_deallocate(mach_task_self(), pThis->MasterPort);
1779 pThis->MasterPort = NULL;
1780 }
1781 if (pThis->pDASession)
1782 {
1783 LogFlow(("%s-%d: releasing the DA session!\n", pDrvIns->pReg->szName, pDrvIns->iInstance));
1784 CFRelease(pThis->pDASession);
1785 pThis->pDASession = NULL;
1786 }
1787#else
1788 if (pThis->FileDevice != NIL_RTFILE)
1789 {
1790 int rc = RTFileClose(pThis->FileDevice);
1791 AssertRC(rc);
1792 pThis->FileDevice = NIL_RTFILE;
1793 }
1794#endif
1795
1796#ifdef RT_OS_SOLARIS
1797 if (pThis->FileRawDevice != NIL_RTFILE)
1798 {
1799 int rc = RTFileClose(pThis->FileRawDevice);
1800 AssertRC(rc);
1801 pThis->FileRawDevice = NIL_RTFILE;
1802 }
1803
1804 if (pThis->pszRawDeviceOpen)
1805 {
1806 RTStrFree(pThis->pszRawDeviceOpen);
1807 pThis->pszRawDeviceOpen = NULL;
1808 }
1809#endif
1810
1811 if (pThis->pszDevice)
1812 {
1813 MMR3HeapFree(pThis->pszDevice);
1814 pThis->pszDevice = NULL;
1815 }
1816
1817 if (pThis->pszDeviceOpen)
1818 {
1819 RTStrFree(pThis->pszDeviceOpen);
1820 pThis->pszDeviceOpen = NULL;
1821 }
1822
1823 /* Forget about the notifications. */
1824 pThis->pDrvMountNotify = NULL;
1825
1826 /* Leave the instance operational if this is just a cleanup of the state
1827 * after an attach error happened. So don't destry the critsect then. */
1828 if (!pThis->fKeepInstance && RTCritSectIsInitialized(&pThis->CritSect))
1829 RTCritSectDelete(&pThis->CritSect);
1830 LogFlow(("%s-%d: drvHostBaseDestruct completed\n", pDrvIns->pReg->szName, pDrvIns->iInstance));
1831}
1832
1833
1834/**
1835 * Initializes the instance data (init part 1).
1836 *
1837 * The driver which derives from this base driver will override function pointers after
1838 * calling this method, and complete the construction by calling DRVHostBaseInitFinish().
1839 *
1840 * On failure call DRVHostBaseDestruct().
1841 *
1842 * @returns VBox status code.
1843 * @param pDrvIns Driver instance.
1844 * @param pCfg Configuration handle.
1845 * @param enmType Device type.
1846 */
1847int DRVHostBaseInitData(PPDMDRVINS pDrvIns, PCFGMNODE pCfg, PDMBLOCKTYPE enmType)
1848{
1849 PDRVHOSTBASE pThis = PDMINS_2_DATA(pDrvIns, PDRVHOSTBASE);
1850 LogFlow(("%s-%d: DRVHostBaseInitData: iInstance=%d\n", pDrvIns->pReg->szName, pDrvIns->iInstance, pDrvIns->iInstance));
1851
1852 /*
1853 * Initialize most of the data members.
1854 */
1855 pThis->pDrvIns = pDrvIns;
1856 pThis->fKeepInstance = false;
1857 pThis->ThreadPoller = NIL_RTTHREAD;
1858#ifdef RT_OS_DARWIN
1859 pThis->MasterPort = NULL;
1860 pThis->ppMMCDI = NULL;
1861 pThis->ppScsiTaskDI = NULL;
1862 pThis->cbBlock = 0;
1863 pThis->pDADisk = NULL;
1864 pThis->pDASession = NULL;
1865#else
1866 pThis->FileDevice = NIL_RTFILE;
1867#endif
1868#ifdef RT_OS_SOLARIS
1869 pThis->FileRawDevice = NIL_RTFILE;
1870#endif
1871 pThis->enmType = enmType;
1872 //pThis->cErrors = 0;
1873
1874 pThis->pfnGetMediaSize = drvHostBaseGetMediaSize;
1875
1876 /* IBase. */
1877 pDrvIns->IBase.pfnQueryInterface = drvHostBaseQueryInterface;
1878
1879 /* IBlock. */
1880 pThis->IBlock.pfnRead = drvHostBaseRead;
1881 pThis->IBlock.pfnWrite = drvHostBaseWrite;
1882 pThis->IBlock.pfnFlush = drvHostBaseFlush;
1883 pThis->IBlock.pfnIsReadOnly = drvHostBaseIsReadOnly;
1884 pThis->IBlock.pfnGetSize = drvHostBaseGetSize;
1885 pThis->IBlock.pfnGetType = drvHostBaseGetType;
1886 pThis->IBlock.pfnGetUuid = drvHostBaseGetUuid;
1887
1888 /* IBlockBios. */
1889 pThis->IBlockBios.pfnGetPCHSGeometry = drvHostBaseGetPCHSGeometry;
1890 pThis->IBlockBios.pfnSetPCHSGeometry = drvHostBaseSetPCHSGeometry;
1891 pThis->IBlockBios.pfnGetLCHSGeometry = drvHostBaseGetLCHSGeometry;
1892 pThis->IBlockBios.pfnSetLCHSGeometry = drvHostBaseSetLCHSGeometry;
1893 pThis->IBlockBios.pfnIsVisible = drvHostBaseIsVisible;
1894 pThis->IBlockBios.pfnGetType = drvHostBaseBiosGetType;
1895
1896 /* IMount. */
1897 pThis->IMount.pfnMount = drvHostBaseMount;
1898 pThis->IMount.pfnUnmount = drvHostBaseUnmount;
1899 pThis->IMount.pfnIsMounted = drvHostBaseIsMounted;
1900 pThis->IMount.pfnLock = drvHostBaseLock;
1901 pThis->IMount.pfnUnlock = drvHostBaseUnlock;
1902 pThis->IMount.pfnIsLocked = drvHostBaseIsLocked;
1903
1904 /*
1905 * Get the IBlockPort & IMountNotify interfaces of the above driver/device.
1906 */
1907 pThis->pDrvBlockPort = PDMIBASE_QUERY_INTERFACE(pDrvIns->pUpBase, PDMIBLOCKPORT);
1908 if (!pThis->pDrvBlockPort)
1909 {
1910 AssertMsgFailed(("Configuration error: No block port interface above!\n"));
1911 return VERR_PDM_MISSING_INTERFACE_ABOVE;
1912 }
1913 pThis->pDrvMountNotify = PDMIBASE_QUERY_INTERFACE(pDrvIns->pUpBase, PDMIMOUNTNOTIFY);
1914
1915 /*
1916 * Query configuration.
1917 */
1918 /* Device */
1919 int rc = CFGMR3QueryStringAlloc(pCfg, "Path", &pThis->pszDevice);
1920 if (RT_FAILURE(rc))
1921 {
1922 AssertMsgFailed(("Configuration error: query for \"Path\" string returned %Rra.\n", rc));
1923 return rc;
1924 }
1925
1926 /* Mountable */
1927 uint32_t u32;
1928 rc = CFGMR3QueryU32(pCfg, "Interval", &u32);
1929 if (RT_SUCCESS(rc))
1930 pThis->cMilliesPoller = u32;
1931 else if (rc == VERR_CFGM_VALUE_NOT_FOUND)
1932 pThis->cMilliesPoller = 1000;
1933 else if (RT_FAILURE(rc))
1934 {
1935 AssertMsgFailed(("Configuration error: Query \"Mountable\" resulted in %Rrc.\n", rc));
1936 return rc;
1937 }
1938
1939 /* ReadOnly */
1940 rc = CFGMR3QueryBool(pCfg, "ReadOnly", &pThis->fReadOnlyConfig);
1941 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
1942 pThis->fReadOnlyConfig = enmType == PDMBLOCKTYPE_DVD || enmType == PDMBLOCKTYPE_CDROM ? true : false;
1943 else if (RT_FAILURE(rc))
1944 {
1945 AssertMsgFailed(("Configuration error: Query \"ReadOnly\" resulted in %Rrc.\n", rc));
1946 return rc;
1947 }
1948
1949 /* Locked */
1950 rc = CFGMR3QueryBool(pCfg, "Locked", &pThis->fLocked);
1951 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
1952 pThis->fLocked = false;
1953 else if (RT_FAILURE(rc))
1954 {
1955 AssertMsgFailed(("Configuration error: Query \"Locked\" resulted in %Rrc.\n", rc));
1956 return rc;
1957 }
1958
1959 /* BIOS visible */
1960 rc = CFGMR3QueryBool(pCfg, "BIOSVisible", &pThis->fBiosVisible);
1961 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
1962 pThis->fBiosVisible = true;
1963 else if (RT_FAILURE(rc))
1964 {
1965 AssertMsgFailed(("Configuration error: Query \"BIOSVisible\" resulted in %Rrc.\n", rc));
1966 return rc;
1967 }
1968
1969 /* Uuid */
1970 char *psz;
1971 rc = CFGMR3QueryStringAlloc(pCfg, "Uuid", &psz);
1972 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
1973 RTUuidClear(&pThis->Uuid);
1974 else if (RT_SUCCESS(rc))
1975 {
1976 rc = RTUuidFromStr(&pThis->Uuid, psz);
1977 if (RT_FAILURE(rc))
1978 {
1979 AssertMsgFailed(("Configuration error: Uuid from string failed on \"%s\", rc=%Rrc.\n", psz, rc));
1980 MMR3HeapFree(psz);
1981 return rc;
1982 }
1983 MMR3HeapFree(psz);
1984 }
1985 else
1986 {
1987 AssertMsgFailed(("Configuration error: Failed to obtain the uuid, rc=%Rrc.\n", rc));
1988 return rc;
1989 }
1990
1991 /* Define whether attach failure is an error (default) or not. */
1992 bool fAttachFailError;
1993 rc = CFGMR3QueryBool(pCfg, "AttachFailError", &fAttachFailError);
1994 if (RT_FAILURE(rc))
1995 fAttachFailError = true;
1996 pThis->fAttachFailError = fAttachFailError;
1997
1998 /* name to open & watch for */
1999#ifdef RT_OS_WINDOWS
2000 int iBit = RT_C_TO_UPPER(pThis->pszDevice[0]) - 'A';
2001 if ( iBit > 'Z' - 'A'
2002 || pThis->pszDevice[1] != ':'
2003 || pThis->pszDevice[2])
2004 {
2005 AssertMsgFailed(("Configuration error: Invalid drive specification: '%s'\n", pThis->pszDevice));
2006 return VERR_INVALID_PARAMETER;
2007 }
2008 pThis->fUnitMask = 1 << iBit;
2009 RTStrAPrintf(&pThis->pszDeviceOpen, "\\\\.\\%s", pThis->pszDevice);
2010
2011#elif defined(RT_OS_SOLARIS)
2012 char *pszBlockDevName = getfullblkname(pThis->pszDevice);
2013 if (!pszBlockDevName)
2014 return VERR_NO_MEMORY;
2015 pThis->pszDeviceOpen = RTStrDup(pszBlockDevName); /* for RTStrFree() */
2016 free(pszBlockDevName);
2017 pThis->pszRawDeviceOpen = RTStrDup(pThis->pszDevice);
2018
2019#else
2020 pThis->pszDeviceOpen = RTStrDup(pThis->pszDevice);
2021#endif
2022
2023 if (!pThis->pszDeviceOpen)
2024 return VERR_NO_MEMORY;
2025
2026 return VINF_SUCCESS;
2027}
2028
2029
2030/**
2031 * Do the 2nd part of the init after the derived driver has overridden the defaults.
2032 *
2033 * On failure call DRVHostBaseDestruct().
2034 *
2035 * @returns VBox status code.
2036 * @param pThis Pointer to the instance data.
2037 */
2038int DRVHostBaseInitFinish(PDRVHOSTBASE pThis)
2039{
2040 int src = VINF_SUCCESS;
2041 PPDMDRVINS pDrvIns = pThis->pDrvIns;
2042
2043 /* log config summary */
2044 Log(("%s-%d: pszDevice='%s' (%s) cMilliesPoller=%d fReadOnlyConfig=%d fLocked=%d fBIOSVisible=%d Uuid=%RTuuid\n",
2045 pDrvIns->pReg->szName, pDrvIns->iInstance, pThis->pszDevice, pThis->pszDeviceOpen, pThis->cMilliesPoller,
2046 pThis->fReadOnlyConfig, pThis->fLocked, pThis->fBiosVisible, &pThis->Uuid));
2047
2048 /*
2049 * Check that there are no drivers below us.
2050 */
2051 AssertMsgReturn(PDMDrvHlpNoAttach(pDrvIns) == VERR_PDM_NO_ATTACHED_DRIVER,
2052 ("Configuration error: Not possible to attach anything to this driver!\n"),
2053 VERR_PDM_DRVINS_NO_ATTACH);
2054
2055 /*
2056 * Register saved state.
2057 */
2058 int rc = PDMDrvHlpSSMRegisterLoadDone(pDrvIns, drvHostBaseLoadDone);
2059 if (RT_FAILURE(rc))
2060 return rc;
2061
2062 /*
2063 * Verify type.
2064 */
2065#ifdef RT_OS_WINDOWS
2066 UINT uDriveType = GetDriveType(pThis->pszDevice);
2067 switch (pThis->enmType)
2068 {
2069 case PDMBLOCKTYPE_FLOPPY_360:
2070 case PDMBLOCKTYPE_FLOPPY_720:
2071 case PDMBLOCKTYPE_FLOPPY_1_20:
2072 case PDMBLOCKTYPE_FLOPPY_1_44:
2073 case PDMBLOCKTYPE_FLOPPY_2_88:
2074 if (uDriveType != DRIVE_REMOVABLE)
2075 {
2076 AssertMsgFailed(("Configuration error: '%s' is not a floppy (type=%d)\n",
2077 pThis->pszDevice, uDriveType));
2078 return VERR_INVALID_PARAMETER;
2079 }
2080 break;
2081 case PDMBLOCKTYPE_CDROM:
2082 case PDMBLOCKTYPE_DVD:
2083 if (uDriveType != DRIVE_CDROM)
2084 {
2085 AssertMsgFailed(("Configuration error: '%s' is not a cdrom (type=%d)\n",
2086 pThis->pszDevice, uDriveType));
2087 return VERR_INVALID_PARAMETER;
2088 }
2089 break;
2090 case PDMBLOCKTYPE_HARD_DISK:
2091 default:
2092 AssertMsgFailed(("enmType=%d\n", pThis->enmType));
2093 return VERR_INVALID_PARAMETER;
2094 }
2095#endif
2096
2097 /*
2098 * Open the device.
2099 */
2100#if defined(RT_OS_DARWIN)
2101 rc = drvHostBaseOpen(pThis, NULL, pThis->fReadOnlyConfig);
2102#else
2103 rc = drvHostBaseReopen(pThis);
2104#endif
2105 if (RT_FAILURE(rc))
2106 {
2107 char *pszDevice = pThis->pszDevice;
2108#ifndef RT_OS_DARWIN
2109 char szPathReal[256];
2110 if ( RTPathExists(pszDevice)
2111 && RT_SUCCESS(RTPathReal(pszDevice, szPathReal, sizeof(szPathReal))))
2112 pszDevice = szPathReal;
2113 pThis->FileDevice = NIL_RTFILE;
2114#endif
2115#ifdef RT_OS_SOLARIS
2116 pThis->FileRawDevice = NIL_RTFILE;
2117#endif
2118
2119 /*
2120 * Disable CD/DVD passthrough in case it was enabled. Would cause
2121 * weird failures later when the guest issues commands. These would
2122 * all fail because of the invalid file handle. So use the normal
2123 * virtual CD/DVD code, which deals more gracefully with unavailable
2124 * "media" - actually a complete drive in this case.
2125 */
2126 pThis->IBlock.pfnSendCmd = NULL;
2127 AssertMsgFailed(("Could not open host device %s, rc=%Rrc\n", pszDevice, rc));
2128 switch (rc)
2129 {
2130 case VERR_ACCESS_DENIED:
2131 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS,
2132#ifdef RT_OS_LINUX
2133 N_("Cannot open host device '%s' for %s access. Check the permissions "
2134 "of that device ('/bin/ls -l %s'): Most probably you need to be member "
2135 "of the device group. Make sure that you logout/login after changing "
2136 "the group settings of the current user"),
2137#else
2138 N_("Cannot open host device '%s' for %s access. Check the permissions "
2139 "of that device"),
2140#endif
2141 pszDevice, pThis->fReadOnlyConfig ? "readonly" : "read/write",
2142 pszDevice);
2143 default:
2144 {
2145 if (pThis->fAttachFailError)
2146 return rc;
2147 int erc = PDMDrvHlpVMSetRuntimeError(pDrvIns, 0 /*fFlags*/,
2148 "DrvHost_MOUNTFAIL",
2149 N_("Cannot attach to host device '%s'"), pszDevice);
2150 AssertRC(erc);
2151 src = rc;
2152 }
2153 }
2154 }
2155#ifdef RT_OS_WINDOWS
2156 if (RT_SUCCESS(src))
2157 DRVHostBaseMediaPresent(pThis);
2158#endif
2159
2160 /*
2161 * Lock the drive if that's required by the configuration.
2162 */
2163 if (pThis->fLocked)
2164 {
2165 if (pThis->pfnDoLock)
2166 rc = pThis->pfnDoLock(pThis, true);
2167 if (RT_FAILURE(rc))
2168 {
2169 AssertMsgFailed(("Failed to lock the dvd drive. rc=%Rrc\n", rc));
2170 return rc;
2171 }
2172 }
2173
2174#ifndef RT_OS_WINDOWS
2175 if (RT_SUCCESS(src))
2176 {
2177 /*
2178 * Create the event semaphore which the poller thread will wait on.
2179 */
2180 rc = RTSemEventCreate(&pThis->EventPoller);
2181 if (RT_FAILURE(rc))
2182 return rc;
2183 }
2184#endif
2185
2186 /*
2187 * Initialize the critical section used for serializing the access to the media.
2188 */
2189 rc = RTCritSectInit(&pThis->CritSect);
2190 if (RT_FAILURE(rc))
2191 return rc;
2192
2193 if (RT_SUCCESS(src))
2194 {
2195 /*
2196 * Start the thread which will poll for the media.
2197 */
2198 rc = RTThreadCreate(&pThis->ThreadPoller, drvHostBaseMediaThread, pThis, 0,
2199 RTTHREADTYPE_INFREQUENT_POLLER, RTTHREADFLAGS_WAITABLE, "DVDMEDIA");
2200 if (RT_FAILURE(rc))
2201 {
2202 AssertMsgFailed(("Failed to create poller thread. rc=%Rrc\n", rc));
2203 return rc;
2204 }
2205
2206 /*
2207 * Wait for the thread to start up (!w32:) and do one detection loop.
2208 */
2209 rc = RTThreadUserWait(pThis->ThreadPoller, 10000);
2210 AssertRC(rc);
2211#ifdef RT_OS_WINDOWS
2212 if (!pThis->hwndDeviceChange)
2213 return VERR_GENERAL_FAILURE;
2214#endif
2215 }
2216
2217 if (RT_FAILURE(src))
2218 return src;
2219 return rc;
2220}
2221
Note: See TracBrowser for help on using the repository browser.

© 2023 Oracle
ContactPrivacy policyTerms of Use