VirtualBox

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

Last change on this file since 2558 was 2272, checked in by vboxsync, 18 years ago

RTPathReal presumes that the path exists!

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