VirtualBox

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

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

Biggest check-in ever. New source code headers for all (C) innotek files.

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