VirtualBox

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

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

AssertBreakVoid -> AssertBreak

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