VirtualBox

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

Last change on this file since 18436 was 18436, checked in by vboxsync, 16 years ago

DrvHostBase.cpp/h: Grumble. forgot about this bugger.

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

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