VirtualBox

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

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

Automated rebranding to Oracle copyright/license strings via filemuncher

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

© 2023 Oracle
ContactPrivacy policyTerms of Use