VirtualBox

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

Last change on this file since 25974 was 25974, checked in by vboxsync, 15 years ago

pdmifs.h: another batch of _IID changes.

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

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