VirtualBox

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

Last change on this file since 5999 was 5999, checked in by vboxsync, 17 years ago

The Giant CDDL Dual-License Header Change.

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